smb_server/proto/messages/
create.rs1use 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
42#[binrw]
49#[brw(little)]
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct CreateRequest {
52 pub structure_size: u16,
53 pub security_flags: u8,
54 pub requested_oplock_level: u8,
55 pub impersonation_level: u32,
56 pub smb_create_flags: u64,
57 pub reserved: u64,
58 pub desired_access: u32,
59 pub file_attributes: u32,
60 pub share_access: u32,
61 pub create_disposition: u32,
62 pub create_options: u32,
63 pub name_offset: u16,
64 pub name_length: u16,
65 pub create_contexts_offset: u32,
66 pub create_contexts_length: u32,
67 #[br(count = name_length as usize)]
69 pub name: Vec<u8>,
70 #[br(count = create_contexts_length as usize)]
73 pub create_contexts: Vec<u8>,
74}
75
76impl CreateRequest {
77 pub fn name_str(&self) -> Option<String> {
79 if !self.name.len().is_multiple_of(2) {
80 return None;
81 }
82 let units: Vec<u16> = self
83 .name
84 .chunks_exact(2)
85 .map(|c| u16::from_le_bytes([c[0], c[1]]))
86 .collect();
87 Some(String::from_utf16_lossy(&units))
88 }
89
90 pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
91 Ok(Self::read(&mut Cursor::new(buf))?)
92 }
93 pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
94 let mut c = Cursor::new(Vec::new());
95 BinWrite::write(self, &mut c)?;
96 out.extend_from_slice(&c.into_inner());
97 Ok(())
98 }
99}
100
101#[binrw]
103#[brw(little)]
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct CreateResponse {
106 pub structure_size: u16,
107 pub oplock_level: u8,
108 pub flags: u8,
109 pub create_action: u32,
110 pub creation_time: u64,
111 pub last_access_time: u64,
112 pub last_write_time: u64,
113 pub change_time: u64,
114 pub allocation_size: u64,
115 pub end_of_file: u64,
116 pub file_attributes: u32,
117 pub reserved2: u32,
118 pub file_id: FileId,
119 pub create_contexts_offset: u32,
120 pub create_contexts_length: u32,
121 #[br(count = create_contexts_length as usize)]
122 pub create_contexts: Vec<u8>,
123}
124
125impl CreateResponse {
126 pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
127 Ok(Self::read(&mut Cursor::new(buf))?)
128 }
129 pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
130 let mut c = Cursor::new(Vec::new());
131 BinWrite::write(self, &mut c)?;
132 out.extend_from_slice(&c.into_inner());
133 Ok(())
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Default)]
156pub struct CreateContext {
157 pub name: Vec<u8>,
158 pub data: Vec<u8>,
159}
160
161impl CreateContext {
162 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>> {
180 let mut out = Vec::new();
181 if chain.is_empty() {
182 return Ok(out);
183 }
184 let mut cursor_off = 0usize;
185 loop {
186 let entry = &chain
187 .get(cursor_off..)
188 .ok_or(ProtoError::Malformed("create context out of range"))?;
189 if entry.len() < 16 {
190 return Err(ProtoError::Malformed("create context too short"));
191 }
192 let next = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]) as usize;
193 let name_offset = u16::from_le_bytes([entry[4], entry[5]]) as usize;
194 let name_length = u16::from_le_bytes([entry[6], entry[7]]) as usize;
195 let data_offset = u16::from_le_bytes([entry[10], entry[11]]) as usize;
197 let data_length =
198 u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]) as usize;
199
200 let name = entry
201 .get(name_offset..name_offset + name_length)
202 .ok_or(ProtoError::Malformed("create context name out of range"))?
203 .to_vec();
204 let data = if data_length == 0 {
205 Vec::new()
206 } else {
207 entry
208 .get(data_offset..data_offset + data_length)
209 .ok_or(ProtoError::Malformed("create context data out of range"))?
210 .to_vec()
211 };
212 out.push(CreateContext { name, data });
213
214 if next == 0 {
215 break;
216 }
217 cursor_off = cursor_off
218 .checked_add(next)
219 .ok_or(ProtoError::Malformed("create context next overflow"))?;
220 }
221 Ok(out)
222 }
223
224 pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
227 if list.is_empty() {
228 return Ok(());
229 }
230 let mut scratch: Vec<u8> = Vec::new();
235 let mut entry_starts: Vec<usize> = Vec::with_capacity(list.len());
236
237 for (i, ctx) in list.iter().enumerate() {
238 while !scratch.len().is_multiple_of(8) {
242 scratch.push(0);
243 }
244 entry_starts.push(scratch.len());
245
246 let header_pos = scratch.len();
249 scratch.extend_from_slice(&[0u8; 16]);
250
251 let name_offset_rel = (scratch.len() - header_pos) as u16;
253 scratch.extend_from_slice(&ctx.name);
254 while !(scratch.len() - header_pos).is_multiple_of(8) {
256 scratch.push(0);
257 }
258 let data_offset_rel = (scratch.len() - header_pos) as u16;
259 scratch.extend_from_slice(&ctx.data);
260
261 let hdr = &mut scratch[header_pos..header_pos + 16];
263 hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); hdr[4..6].copy_from_slice(&name_offset_rel.to_le_bytes());
265 hdr[6..8].copy_from_slice(&(ctx.name.len() as u16).to_le_bytes());
266 hdr[8..10].copy_from_slice(&0u16.to_le_bytes()); hdr[10..12].copy_from_slice(&data_offset_rel.to_le_bytes());
268 hdr[12..16].copy_from_slice(&(ctx.data.len() as u32).to_le_bytes());
269
270 if i + 1 < list.len() {
273 while !scratch.len().is_multiple_of(8) {
274 scratch.push(0);
275 }
276 }
277 }
278
279 for i in 0..(entry_starts.len() - 1) {
281 let this = entry_starts[i];
282 let next = entry_starts[i + 1];
283 let delta = (next - this) as u32;
284 scratch[this..this + 4].copy_from_slice(&delta.to_le_bytes());
285 }
286 out.extend_from_slice(&scratch);
289 Ok(())
290 }
291}
292
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299#[repr(u8)]
300pub enum OplockLevel {
301 None = 0x00,
302 Ii = 0x01,
303 Exclusive = 0x08,
304 Batch = 0x09,
305 Lease = 0xFF,
306}
307
308impl OplockLevel {
309 pub fn from_u8(v: u8) -> Option<Self> {
310 Some(match v {
311 0x00 => Self::None,
312 0x01 => Self::Ii,
313 0x08 => Self::Exclusive,
314 0x09 => Self::Batch,
315 0xFF => Self::Lease,
316 _ => return None,
317 })
318 }
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323#[repr(u32)]
324pub enum ImpersonationLevel {
325 Anonymous = 0x0000_0000,
326 Identification = 0x0000_0001,
327 Impersonation = 0x0000_0002,
328 Delegate = 0x0000_0003,
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 fn utf16le(s: &str) -> Vec<u8> {
336 s.encode_utf16().flat_map(u16::to_le_bytes).collect()
337 }
338
339 #[test]
340 fn request_round_trips() {
341 let name = utf16le("dir\\file.txt");
342 let r = CreateRequest {
343 structure_size: 57,
344 security_flags: 0,
345 requested_oplock_level: 0,
346 impersonation_level: ImpersonationLevel::Impersonation as u32,
347 smb_create_flags: 0,
348 reserved: 0,
349 desired_access: 0x0012_0089,
350 file_attributes: 0,
351 share_access: 0x0000_0007,
352 create_disposition: 1,
353 create_options: 0x0000_0040,
354 name_offset: 0x78,
355 name_length: name.len() as u16,
356 create_contexts_offset: 0,
357 create_contexts_length: 0,
358 name,
359 create_contexts: vec![],
360 };
361 let mut buf = Vec::new();
362 r.write_to(&mut buf).unwrap();
363 let decoded = CreateRequest::parse(&buf).unwrap();
364 assert_eq!(decoded, r);
365 assert_eq!(decoded.name_str().unwrap(), "dir\\file.txt");
366 }
367
368 #[test]
369 fn response_round_trips() {
370 let r = CreateResponse {
371 structure_size: 89,
372 oplock_level: 0,
373 flags: 0,
374 create_action: 1,
375 creation_time: 0x01D9_0000_0000_0000,
376 last_access_time: 0x01D9_0000_0000_0000,
377 last_write_time: 0x01D9_0000_0000_0000,
378 change_time: 0x01D9_0000_0000_0000,
379 allocation_size: 0x1000,
380 end_of_file: 0x800,
381 file_attributes: 0x0020,
382 reserved2: 0,
383 file_id: FileId::new(0x1234, 0x5678),
384 create_contexts_offset: 0,
385 create_contexts_length: 0,
386 create_contexts: vec![],
387 };
388 let mut buf = Vec::new();
389 r.write_to(&mut buf).unwrap();
390 let decoded = CreateResponse::parse(&buf).unwrap();
391 assert_eq!(decoded, r);
392 }
393
394 #[test]
395 fn create_context_chain_round_trips_single() {
396 let ctxs = vec![CreateContext {
397 name: b"MxAc".to_vec(),
398 data: vec![],
399 }];
400 let mut buf = Vec::new();
401 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
402 let decoded = CreateContext::parse_chain(&buf).unwrap();
403 assert_eq!(decoded, ctxs);
404 }
405
406 #[test]
407 fn create_context_chain_round_trips_multi() {
408 let ctxs = vec![
409 CreateContext {
410 name: b"DHnQ".to_vec(),
411 data: vec![0u8; 16],
412 },
413 CreateContext {
414 name: b"MxAc".to_vec(),
415 data: vec![],
416 },
417 CreateContext {
418 name: b"QFid".to_vec(),
419 data: vec![0xAA; 32],
420 },
421 ];
422 let mut buf = Vec::new();
423 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
424 let decoded = CreateContext::parse_chain(&buf).unwrap();
425 assert_eq!(decoded, ctxs);
426 }
427
428 #[test]
429 fn empty_chain_round_trips() {
430 let ctxs: Vec<CreateContext> = vec![];
431 let mut buf = Vec::new();
432 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
433 assert!(buf.is_empty());
434 let decoded = CreateContext::parse_chain(&buf).unwrap();
435 assert!(decoded.is_empty());
436 }
437}