Skip to main content

smb_server/proto/messages/
create.rs

1//! CREATE Request/Response (MS-SMB2 §2.2.13 / §2.2.14).
2//!
3//! `create_contexts` is a chained sequence of `SMB2_CREATE_CONTEXT` records
4//! (MS-SMB2 §2.2.13.2). Each record has `Next` (offset to the next entry,
5//! relative to the start of *this* entry; 0 marks the last), a name + data
6//! pair, and 8-byte alignment.
7
8use binrw::{BinRead, BinWrite, binrw};
9use std::io::Cursor;
10
11use crate::proto::error::{ProtoError, ProtoResult};
12
13/// SMB2 FileId — opaque 16 bytes (volatile + persistent).
14///
15/// MS-SMB2 §2.2.14.1. We expose both halves; the server uses identical values
16/// for both since durable handles are out of scope (spec §2 in the v1 design).
17#[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    /// MS-SMB2: the "any" FileId is `0xFFFF…FFFF`.
34    pub const fn any() -> Self {
35        Self {
36            persistent: u64::MAX,
37            volatile: u64::MAX,
38        }
39    }
40}
41
42/// MS-SMB2 §2.2.13 CREATE Request — fixed prefix.
43///
44/// Variable-length tail: the file `name` (UTF-16LE) and `create_contexts`
45/// blob, each at absolute offsets from the start of the SMB2 header. We hold
46/// them as length-counted byte buffers immediately following the fixed
47/// portion. The server crate parses contexts with [`CreateContext::parse_chain`].
48#[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    /// UTF-16LE filename.
68    #[br(count = name_length as usize)]
69    pub name: Vec<u8>,
70    /// Raw create-contexts chain bytes; parse with
71    /// [`CreateContext::parse_chain`].
72    #[br(count = create_contexts_length as usize)]
73    pub create_contexts: Vec<u8>,
74}
75
76impl CreateRequest {
77    /// Decode the UTF-16LE filename.
78    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/// MS-SMB2 §2.2.14 CREATE Response.
102#[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// ---------------------------------------------------------------------------
138// Create contexts (MS-SMB2 §2.2.13.2)
139// ---------------------------------------------------------------------------
140
141/// Generic SMB2_CREATE_CONTEXT envelope.
142///
143/// Per MS-SMB2 §2.2.13.2 each entry has:
144/// * `Next` — offset (bytes) from the start of *this* entry to the start of
145///   the next entry in the chain, or 0 for the last entry.
146/// * `NameOffset`/`NameLength` — name (typically a 4-byte ASCII tag) at an
147///   offset relative to the entry start.
148/// * `Reserved` — 2 bytes.
149/// * `DataOffset`/`DataLength` — payload at an offset relative to the entry
150///   start.
151///
152/// We model the entry as `name` + `data` byte vectors plus the raw flags. The
153/// chain reader / writer below handles `Next` and 8-byte alignment between
154/// entries.
155#[derive(Debug, Clone, PartialEq, Eq, Default)]
156pub struct CreateContext {
157    pub name: Vec<u8>,
158    pub data: Vec<u8>,
159}
160
161impl CreateContext {
162    // Well-known names (MS-SMB2 §2.2.13.2 table). 4-byte ASCII tags.
163    pub const NAME_EXTA: &'static [u8; 4] = b"ExtA"; // SMB2_CREATE_EA_BUFFER
164    pub const NAME_SECD: &'static [u8; 4] = b"SecD"; // SMB2_CREATE_SD_BUFFER
165    pub const NAME_DHNQ: &'static [u8; 4] = b"DHnQ"; // DURABLE_HANDLE_REQUEST
166    pub const NAME_DHNC: &'static [u8; 4] = b"DHnC"; // DURABLE_HANDLE_RECONNECT
167    pub const NAME_ALSI: &'static [u8; 4] = b"AlSi"; // ALLOCATION_SIZE
168    pub const NAME_MXAC: &'static [u8; 4] = b"MxAc"; // QUERY_MAXIMAL_ACCESS
169    pub const NAME_TWRP: &'static [u8; 4] = b"TWrp"; // TIMEWARP_TOKEN
170    pub const NAME_QFID: &'static [u8; 4] = b"QFid"; // QUERY_ON_DISK_ID
171    pub const NAME_RQLS: &'static [u8; 4] = b"RqLs"; // REQUEST_LEASE
172    pub const NAME_DH2Q: &'static [u8; 4] = b"DH2Q"; // DURABLE_HANDLE_REQUEST_V2
173    pub const NAME_DH2C: &'static [u8; 4] = b"DH2C"; // DURABLE_HANDLE_RECONNECT_V2
174
175    /// Parse a chain of create-contexts from the raw chain bytes.
176    ///
177    /// The chain is empty if `chain.is_empty()`. Otherwise we walk `Next`
178    /// offsets until we hit a zero terminator, validating bounds at each step.
179    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            // entry[8..10] = reserved
196            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    /// Encode a chain of create-contexts into `out`. Inserts `Next` offsets
225    /// and 8-byte alignment padding between entries.
226    pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
227        if list.is_empty() {
228            return Ok(());
229        }
230        // We build the chain in a scratch buffer, then copy. Each entry is:
231        //   16-byte header + name + (pad to 8) + data + (pad to 8 if not last)
232        // The `Next` of every entry except the last is the size from this
233        // entry's start to the next entry's start.
234        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            // Pad to 8-byte boundary before each entry (except possibly first
239            // — but contexts must be 8-byte aligned, and the chain itself is
240            // anchored at an 8-aligned offset by the server).
241            while !scratch.len().is_multiple_of(8) {
242                scratch.push(0);
243            }
244            entry_starts.push(scratch.len());
245
246            // Reserve 16 bytes for the header; will fill in once we know
247            // the actual offsets.
248            let header_pos = scratch.len();
249            scratch.extend_from_slice(&[0u8; 16]);
250
251            // Name immediately follows the header.
252            let name_offset_rel = (scratch.len() - header_pos) as u16;
253            scratch.extend_from_slice(&ctx.name);
254            // Pad to 8 before data.
255            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            // Now backfill the header bytes (Next is patched after the loop).
262            let hdr = &mut scratch[header_pos..header_pos + 16];
263            hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); // Next, fixed up below
264            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()); // Reserved
267            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            // For non-last, pad the trailing data area to 8 so the next
271            // entry starts aligned.
272            if i + 1 < list.len() {
273                while !scratch.len().is_multiple_of(8) {
274                    scratch.push(0);
275                }
276            }
277        }
278
279        // Patch `Next` offsets.
280        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        // Last entry's Next stays 0.
287
288        out.extend_from_slice(&scratch);
289        Ok(())
290    }
291}
292
293// ---------------------------------------------------------------------------
294// Helper enums (oplock level, impersonation level)
295// ---------------------------------------------------------------------------
296
297/// MS-SMB2 §2.2.13 RequestedOplockLevel / §2.2.14 OplockLevel.
298#[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/// MS-SMB2 §2.2.13 ImpersonationLevel.
322#[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}