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. The server sets both halves to the same value.
16#[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    /// MS-SMB2: the "any" FileId is `0xFFFF...FFFF`.
33    pub const fn any() -> Self {
34        Self {
35            persistent: u64::MAX,
36            volatile: u64::MAX,
37        }
38    }
39}
40
41/// Offset of the first byte after the fixed CREATE request fields, counted
42/// from the start of the SMB2 header: 64 + 56.
43const CREATE_BUFFER_OFFSET: u64 = 0x78;
44
45/// MS-SMB2 §2.2.13 CREATE Request.
46///
47/// The file `name` (UTF-16LE) and the `create_contexts` blob sit at
48/// `name_offset` and `create_contexts_offset`, counted from the start of the
49/// SMB2 header, after the fixed fields. `parse` reads them from those offsets
50/// and fails when a non-empty one starts before the end of the fixed fields or
51/// ends past the request. `write_to` writes them back to back after the fixed
52/// fields, so the offsets must match that layout.
53/// [`CreateContext::parse_chain`] decodes the `create_contexts` blob.
54#[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    /// UTF-16LE filename.
74    #[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    /// Raw create-contexts chain bytes; parse with
81    /// [`CreateContext::parse_chain`].
82    #[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    /// Decode the UTF-16LE filename.
92    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/// MS-SMB2 §2.2.14 CREATE Response.
116#[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// ---------------------------------------------------------------------------
152// Create contexts (MS-SMB2 §2.2.13.2)
153// ---------------------------------------------------------------------------
154
155/// Generic SMB2_CREATE_CONTEXT envelope.
156///
157/// Per MS-SMB2 §2.2.13.2 each entry has:
158/// * `Next` - offset (bytes) from the start of *this* entry to the start of
159///   the next entry in the chain, or 0 for the last entry.
160/// * `NameOffset`/`NameLength` - name (typically a 4-byte ASCII tag) at an
161///   offset relative to the entry start.
162/// * `Reserved` - 2 bytes.
163/// * `DataOffset`/`DataLength` - payload at an offset relative to the entry
164///   start.
165///
166/// Each entry is held as `name` and `data` byte vectors. The chain reader and
167/// writer below handle `Next` and 8-byte alignment between entries.
168#[derive(Debug, Clone, PartialEq, Eq, Default)]
169pub struct CreateContext {
170    pub name: Vec<u8>,
171    pub data: Vec<u8>,
172}
173
174impl CreateContext {
175    // Well-known names (MS-SMB2 §2.2.13.2 table). 4-byte ASCII tags.
176    pub const NAME_EXTA: &'static [u8; 4] = b"ExtA"; // SMB2_CREATE_EA_BUFFER
177    pub const NAME_SECD: &'static [u8; 4] = b"SecD"; // SMB2_CREATE_SD_BUFFER
178    pub const NAME_DHNQ: &'static [u8; 4] = b"DHnQ"; // DURABLE_HANDLE_REQUEST
179    pub const NAME_DHNC: &'static [u8; 4] = b"DHnC"; // DURABLE_HANDLE_RECONNECT
180    pub const NAME_ALSI: &'static [u8; 4] = b"AlSi"; // ALLOCATION_SIZE
181    pub const NAME_MXAC: &'static [u8; 4] = b"MxAc"; // QUERY_MAXIMAL_ACCESS
182    pub const NAME_TWRP: &'static [u8; 4] = b"TWrp"; // TIMEWARP_TOKEN
183    pub const NAME_QFID: &'static [u8; 4] = b"QFid"; // QUERY_ON_DISK_ID
184    pub const NAME_RQLS: &'static [u8; 4] = b"RqLs"; // REQUEST_LEASE
185    pub const NAME_DH2Q: &'static [u8; 4] = b"DH2Q"; // DURABLE_HANDLE_REQUEST_V2
186    pub const NAME_DH2C: &'static [u8; 4] = b"DH2C"; // DURABLE_HANDLE_RECONNECT_V2
187
188    /// Parse a chain of create-contexts from the raw chain bytes.
189    ///
190    /// The chain is empty if `chain.is_empty()`. Otherwise `Next` offsets are
191    /// followed until one is zero. Each context spans from its start to the
192    /// next context, or to the end of the chain for the last one. A context
193    /// shorter than its 16-byte header, a name shorter than 4 bytes, or a
194    /// name or data outside the context is malformed.
195    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            // entry[8..10] = reserved
219            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    /// Encode a chain of create-contexts into `out`. Inserts `Next` offsets
251    /// and 8-byte alignment padding between entries.
252    pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
253        if list.is_empty() {
254            return Ok(());
255        }
256        // We build the chain in a scratch buffer, then copy. Each entry is:
257        //   16-byte header + name + (pad to 8) + data + (pad to 8 if not last)
258        // The `Next` of every entry except the last is the size from this
259        // entry's start to the next entry's start.
260        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            // Each entry starts 8-byte aligned; the caller places the chain at
265            // an 8-aligned offset.
266            while !scratch.len().is_multiple_of(8) {
267                scratch.push(0);
268            }
269            entry_starts.push(scratch.len());
270
271            // Reserve 16 bytes for the header; will fill in once we know
272            // the actual offsets.
273            let header_pos = scratch.len();
274            scratch.extend_from_slice(&[0u8; 16]);
275
276            // Name immediately follows the header.
277            let name_offset_rel = (scratch.len() - header_pos) as u16;
278            scratch.extend_from_slice(&ctx.name);
279            // Pad to 8 before data.
280            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            // Now backfill the header bytes (Next is patched after the loop).
287            let hdr = &mut scratch[header_pos..header_pos + 16];
288            hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); // Next, fixed up below
289            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()); // Reserved
292            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            // For non-last, pad the trailing data area to 8 so the next
296            // entry starts aligned.
297            if i + 1 < list.len() {
298                while !scratch.len().is_multiple_of(8) {
299                    scratch.push(0);
300                }
301            }
302        }
303
304        // Patch `Next` offsets.
305        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        // Last entry's Next stays 0.
312
313        out.extend_from_slice(&scratch);
314        Ok(())
315    }
316}
317
318// ---------------------------------------------------------------------------
319// Helper enums (oplock level, impersonation level)
320// ---------------------------------------------------------------------------
321
322/// MS-SMB2 §2.2.13 RequestedOplockLevel / §2.2.14 OplockLevel.
323#[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/// MS-SMB2 §2.2.13 ImpersonationLevel.
347#[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    /// CREATE body with `name` at `name_offset` and `contexts` at
394    /// `contexts_offset`, zero-filling any gap after the fixed fields.
395    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        // Name 8 bytes past the fixed fields, contexts 8-aligned after it.
445        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        // Byte position of NameOffset in the request body.
460        const NAME_OFFSET_FIELD: usize = 44;
461        let name = utf16le("a.txt");
462        // Inside the fixed fields, past the end.
463        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        // Contexts that run past the end of the request.
473        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        // Data that runs from the first context into the second.
570        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        // Next inside the first header, and past the end of the chain.
575        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}