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