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, except
16/// for durable opens, whose persistent half is random.
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/// Offset of the first byte after the fixed CREATE request fields, counted
43/// from the start of the SMB2 header: 64 + 56.
44const CREATE_BUFFER_OFFSET: u64 = 0x78;
45
46/// MS-SMB2 §2.2.13 CREATE Request.
47///
48/// The file `name` (UTF-16LE) and the `create_contexts` blob sit at
49/// `name_offset` and `create_contexts_offset`, counted from the start of the
50/// SMB2 header, after the fixed fields. `parse` reads them from those offsets
51/// and fails when a non-empty one starts before the end of the fixed fields or
52/// ends past the request. `write_to` writes them back to back after the fixed
53/// fields, so the offsets must match that layout.
54/// [`CreateContext::parse_chain`] decodes the `create_contexts` blob.
55#[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    /// UTF-16LE filename.
75    #[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    /// Raw create-contexts chain bytes; parse with
82    /// [`CreateContext::parse_chain`].
83    #[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    /// Decode the UTF-16LE filename.
93    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/// MS-SMB2 §2.2.14 CREATE Response.
117#[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// ---------------------------------------------------------------------------
153// Create contexts (MS-SMB2 §2.2.13.2)
154// ---------------------------------------------------------------------------
155
156/// Generic SMB2_CREATE_CONTEXT envelope.
157///
158/// Per MS-SMB2 §2.2.13.2 each entry has:
159/// * `Next` - offset (bytes) from the start of *this* entry to the start of
160///   the next entry in the chain, or 0 for the last entry.
161/// * `NameOffset`/`NameLength` - name (typically a 4-byte ASCII tag) at an
162///   offset relative to the entry start.
163/// * `Reserved` - 2 bytes.
164/// * `DataOffset`/`DataLength` - payload at an offset relative to the entry
165///   start.
166///
167/// Each entry is held as `name` and `data` byte vectors. The chain reader and
168/// writer below handle `Next` and 8-byte alignment between entries.
169#[derive(Debug, Clone, PartialEq, Eq, Default)]
170pub struct CreateContext {
171    pub name: Vec<u8>,
172    pub data: Vec<u8>,
173}
174
175impl CreateContext {
176    // Well-known names (MS-SMB2 §2.2.13.2 table). 4-byte ASCII tags.
177    pub const NAME_EXTA: &'static [u8; 4] = b"ExtA"; // SMB2_CREATE_EA_BUFFER
178    pub const NAME_SECD: &'static [u8; 4] = b"SecD"; // SMB2_CREATE_SD_BUFFER
179    pub const NAME_DHNQ: &'static [u8; 4] = b"DHnQ"; // DURABLE_HANDLE_REQUEST
180    pub const NAME_DHNC: &'static [u8; 4] = b"DHnC"; // DURABLE_HANDLE_RECONNECT
181    pub const NAME_ALSI: &'static [u8; 4] = b"AlSi"; // ALLOCATION_SIZE
182    pub const NAME_MXAC: &'static [u8; 4] = b"MxAc"; // QUERY_MAXIMAL_ACCESS
183    pub const NAME_TWRP: &'static [u8; 4] = b"TWrp"; // TIMEWARP_TOKEN
184    pub const NAME_QFID: &'static [u8; 4] = b"QFid"; // QUERY_ON_DISK_ID
185    pub const NAME_RQLS: &'static [u8; 4] = b"RqLs"; // REQUEST_LEASE
186    pub const NAME_DH2Q: &'static [u8; 4] = b"DH2Q"; // DURABLE_HANDLE_REQUEST_V2
187    pub const NAME_DH2C: &'static [u8; 4] = b"DH2C"; // DURABLE_HANDLE_RECONNECT_V2
188
189    /// Parse a chain of create-contexts from the raw chain bytes.
190    ///
191    /// The chain is empty if `chain.is_empty()`. Otherwise `Next` offsets are
192    /// followed until one is zero. Each context spans from its start to the
193    /// next context, or to the end of the chain for the last one. A context
194    /// shorter than its 16-byte header, a name shorter than 4 bytes, or a
195    /// name or data outside the context is malformed.
196    pub fn parse_chain(chain: &[u8]) -> ProtoResult<Vec<CreateContext>> {
197        let mut out = Vec::new();
198        if chain.is_empty() {
199            return Ok(out);
200        }
201        let mut cursor_off = 0usize;
202        loop {
203            let rest = chain
204                .get(cursor_off..)
205                .ok_or(ProtoError::Malformed("create context out of range"))?;
206            if rest.len() < 16 {
207                return Err(ProtoError::Malformed("create context too short"));
208            }
209            let next = u32::from_le_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
210            let entry = match next {
211                0 => rest,
212                16.. => rest
213                    .get(..next)
214                    .ok_or(ProtoError::Malformed("create context next out of range"))?,
215                _ => return Err(ProtoError::Malformed("create context too short")),
216            };
217            let name_offset = u16::from_le_bytes([entry[4], entry[5]]) as usize;
218            let name_length = u16::from_le_bytes([entry[6], entry[7]]) as usize;
219            // entry[8..10] = reserved
220            let data_offset = u16::from_le_bytes([entry[10], entry[11]]) as usize;
221            let data_length =
222                u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]) as usize;
223            if name_length < 4 {
224                return Err(ProtoError::Malformed("create context name too short"));
225            }
226
227            let name = entry
228                .get(name_offset..name_offset + name_length)
229                .ok_or(ProtoError::Malformed("create context name out of range"))?
230                .to_vec();
231            let data = if data_length == 0 {
232                Vec::new()
233            } else {
234                data_offset
235                    .checked_add(data_length)
236                    .and_then(|end| entry.get(data_offset..end))
237                    .ok_or(ProtoError::Malformed("create context data out of range"))?
238                    .to_vec()
239            };
240            out.push(CreateContext { name, data });
241
242            if next == 0 {
243                break;
244            }
245            cursor_off = cursor_off
246                .checked_add(next)
247                .ok_or(ProtoError::Malformed("create context next overflow"))?;
248        }
249        Ok(out)
250    }
251
252    /// Encode a chain of create-contexts into `out`. Inserts `Next` offsets
253    /// and 8-byte alignment padding between entries.
254    pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
255        if list.is_empty() {
256            return Ok(());
257        }
258        // We build the chain in a scratch buffer, then copy. Each entry is:
259        //   16-byte header + name + (pad to 8) + data + (pad to 8 if not last)
260        // The `Next` of every entry except the last is the size from this
261        // entry's start to the next entry's start.
262        let mut scratch: Vec<u8> = Vec::new();
263        let mut entry_starts: Vec<usize> = Vec::with_capacity(list.len());
264
265        for (i, ctx) in list.iter().enumerate() {
266            // Each entry starts 8-byte aligned; the caller places the chain at
267            // an 8-aligned offset.
268            while !scratch.len().is_multiple_of(8) {
269                scratch.push(0);
270            }
271            entry_starts.push(scratch.len());
272
273            // Reserve 16 bytes for the header; will fill in once we know
274            // the actual offsets.
275            let header_pos = scratch.len();
276            scratch.extend_from_slice(&[0u8; 16]);
277
278            // Name immediately follows the header.
279            let name_offset_rel = (scratch.len() - header_pos) as u16;
280            scratch.extend_from_slice(&ctx.name);
281            // Pad to 8 before data.
282            while !(scratch.len() - header_pos).is_multiple_of(8) {
283                scratch.push(0);
284            }
285            let data_offset_rel = (scratch.len() - header_pos) as u16;
286            scratch.extend_from_slice(&ctx.data);
287
288            // Now backfill the header bytes (Next is patched after the loop).
289            let hdr = &mut scratch[header_pos..header_pos + 16];
290            hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); // Next, fixed up below
291            hdr[4..6].copy_from_slice(&name_offset_rel.to_le_bytes());
292            hdr[6..8].copy_from_slice(&(ctx.name.len() as u16).to_le_bytes());
293            hdr[8..10].copy_from_slice(&0u16.to_le_bytes()); // Reserved
294            hdr[10..12].copy_from_slice(&data_offset_rel.to_le_bytes());
295            hdr[12..16].copy_from_slice(&(ctx.data.len() as u32).to_le_bytes());
296
297            // For non-last, pad the trailing data area to 8 so the next
298            // entry starts aligned.
299            if i + 1 < list.len() {
300                while !scratch.len().is_multiple_of(8) {
301                    scratch.push(0);
302                }
303            }
304        }
305
306        // Patch `Next` offsets.
307        for i in 0..(entry_starts.len() - 1) {
308            let this = entry_starts[i];
309            let next = entry_starts[i + 1];
310            let delta = (next - this) as u32;
311            scratch[this..this + 4].copy_from_slice(&delta.to_le_bytes());
312        }
313        // Last entry's Next stays 0.
314
315        out.extend_from_slice(&scratch);
316        Ok(())
317    }
318}
319
320// ---------------------------------------------------------------------------
321// Helper enums (oplock level, impersonation level)
322// ---------------------------------------------------------------------------
323
324/// MS-SMB2 §2.2.13 RequestedOplockLevel / §2.2.14 OplockLevel.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326#[repr(u8)]
327pub enum OplockLevel {
328    None = 0x00,
329    Ii = 0x01,
330    Exclusive = 0x08,
331    Batch = 0x09,
332    Lease = 0xFF,
333}
334
335impl OplockLevel {
336    pub fn from_u8(v: u8) -> Option<Self> {
337        Some(match v {
338            0x00 => Self::None,
339            0x01 => Self::Ii,
340            0x08 => Self::Exclusive,
341            0x09 => Self::Batch,
342            0xFF => Self::Lease,
343            _ => return None,
344        })
345    }
346}
347
348/// MS-SMB2 §2.2.13 ImpersonationLevel.
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350#[repr(u32)]
351pub enum ImpersonationLevel {
352    Anonymous = 0x0000_0000,
353    Identification = 0x0000_0001,
354    Impersonation = 0x0000_0002,
355    Delegate = 0x0000_0003,
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    fn utf16le(s: &str) -> Vec<u8> {
363        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
364    }
365
366    #[test]
367    fn request_round_trips() {
368        let name = utf16le("dir\\file.txt");
369        let r = CreateRequest {
370            structure_size: 57,
371            security_flags: 0,
372            requested_oplock_level: 0,
373            impersonation_level: ImpersonationLevel::Impersonation as u32,
374            smb_create_flags: 0,
375            reserved: 0,
376            desired_access: 0x0012_0089,
377            file_attributes: 0,
378            share_access: 0x0000_0007,
379            create_disposition: 1,
380            create_options: 0x0000_0040,
381            name_offset: 0x78,
382            name_length: name.len() as u16,
383            create_contexts_offset: 0,
384            create_contexts_length: 0,
385            name,
386            create_contexts: vec![],
387        };
388        let mut buf = Vec::new();
389        r.write_to(&mut buf).unwrap();
390        let decoded = CreateRequest::parse(&buf).unwrap();
391        assert_eq!(decoded, r);
392        assert_eq!(decoded.name_str().unwrap(), "dir\\file.txt");
393    }
394
395    /// CREATE body with `name` at `name_offset` and `contexts` at
396    /// `contexts_offset`, zero-filling any gap after the fixed fields.
397    fn body_with_buffers(
398        name: &[u8],
399        name_offset: u16,
400        contexts: &[u8],
401        contexts_offset: u32,
402    ) -> Vec<u8> {
403        let fixed = CreateRequest {
404            structure_size: 57,
405            security_flags: 0,
406            requested_oplock_level: 0,
407            impersonation_level: ImpersonationLevel::Impersonation as u32,
408            smb_create_flags: 0,
409            reserved: 0,
410            desired_access: 0x0012_0089,
411            file_attributes: 0,
412            share_access: 0x0000_0007,
413            create_disposition: 1,
414            create_options: 0,
415            name_offset,
416            name_length: name.len() as u16,
417            create_contexts_offset: contexts_offset,
418            create_contexts_length: contexts.len() as u32,
419            name: vec![],
420            create_contexts: vec![],
421        };
422        let mut body = Vec::new();
423        fixed.write_to(&mut body).unwrap();
424        for (data, offset) in [(name, u32::from(name_offset)), (contexts, contexts_offset)] {
425            if data.is_empty() {
426                continue;
427            }
428            let start = offset as usize - 64;
429            if body.len() < start + data.len() {
430                body.resize(start + data.len(), 0);
431            }
432            body[start..start + data.len()].copy_from_slice(data);
433        }
434        body
435    }
436
437    #[test]
438    fn request_reads_name_and_contexts_at_their_offsets() {
439        let name = utf16le("dir\\file.txt");
440        let ctxs = vec![CreateContext {
441            name: CreateContext::NAME_MXAC.to_vec(),
442            data: vec![],
443        }];
444        let mut chain = Vec::new();
445        CreateContext::encode_chain(&ctxs, &mut chain).unwrap();
446        // Name 8 bytes past the fixed fields, contexts 8-aligned after it.
447        let name_offset = 0x80;
448        let contexts_offset = (u32::from(name_offset) + name.len() as u32).next_multiple_of(8);
449        let body = body_with_buffers(&name, name_offset, &chain, contexts_offset);
450
451        let req = CreateRequest::parse(&body).unwrap();
452        assert_eq!(req.name_str().unwrap(), "dir\\file.txt");
453        assert_eq!(
454            CreateContext::parse_chain(&req.create_contexts).unwrap(),
455            ctxs
456        );
457    }
458
459    #[test]
460    fn request_rejects_buffers_outside_the_request() {
461        // Byte position of NameOffset in the request body.
462        const NAME_OFFSET_FIELD: usize = 44;
463        let name = utf16le("a.txt");
464        // Inside the fixed fields, past the end.
465        for name_offset in [0x70, 0x200] {
466            let mut body = body_with_buffers(&name, 0x78, &[], 0x78);
467            body[NAME_OFFSET_FIELD..NAME_OFFSET_FIELD + 2]
468                .copy_from_slice(&u16::to_le_bytes(name_offset));
469            assert!(
470                CreateRequest::parse(&body).is_err(),
471                "name offset {name_offset:#x}"
472            );
473        }
474        // Contexts that run past the end of the request.
475        let mut body = body_with_buffers(&name, 0x78, &[0; 16], 0x88);
476        body.truncate(body.len() - 1);
477        assert!(CreateRequest::parse(&body).is_err());
478    }
479
480    #[test]
481    fn request_accepts_empty_buffers_at_any_offset() {
482        let body = body_with_buffers(&[], 0, &[], 0);
483        let req = CreateRequest::parse(&body).unwrap();
484        assert_eq!(req.name_str().unwrap(), "");
485        assert!(req.create_contexts.is_empty());
486    }
487
488    #[test]
489    fn response_round_trips() {
490        let r = CreateResponse {
491            structure_size: 89,
492            oplock_level: 0,
493            flags: 0,
494            create_action: 1,
495            creation_time: 0x01D9_0000_0000_0000,
496            last_access_time: 0x01D9_0000_0000_0000,
497            last_write_time: 0x01D9_0000_0000_0000,
498            change_time: 0x01D9_0000_0000_0000,
499            allocation_size: 0x1000,
500            end_of_file: 0x800,
501            file_attributes: 0x0020,
502            reserved2: 0,
503            file_id: FileId::new(0x1234, 0x5678),
504            create_contexts_offset: 0,
505            create_contexts_length: 0,
506            create_contexts: vec![],
507        };
508        let mut buf = Vec::new();
509        r.write_to(&mut buf).unwrap();
510        let decoded = CreateResponse::parse(&buf).unwrap();
511        assert_eq!(decoded, r);
512    }
513
514    #[test]
515    fn create_context_chain_round_trips_single() {
516        let ctxs = vec![CreateContext {
517            name: b"MxAc".to_vec(),
518            data: vec![],
519        }];
520        let mut buf = Vec::new();
521        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
522        let decoded = CreateContext::parse_chain(&buf).unwrap();
523        assert_eq!(decoded, ctxs);
524    }
525
526    #[test]
527    fn create_context_chain_round_trips_multi() {
528        let ctxs = vec![
529            CreateContext {
530                name: b"DHnQ".to_vec(),
531                data: vec![0u8; 16],
532            },
533            CreateContext {
534                name: b"MxAc".to_vec(),
535                data: vec![],
536            },
537            CreateContext {
538                name: b"QFid".to_vec(),
539                data: vec![0xAA; 32],
540            },
541        ];
542        let mut buf = Vec::new();
543        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
544        let decoded = CreateContext::parse_chain(&buf).unwrap();
545        assert_eq!(decoded, ctxs);
546    }
547
548    #[test]
549    fn create_context_chain_rejects_malformed_entries() {
550        let short_name = vec![CreateContext {
551            name: b"MxA".to_vec(),
552            data: vec![],
553        }];
554        let mut buf = Vec::new();
555        CreateContext::encode_chain(&short_name, &mut buf).unwrap();
556        assert!(CreateContext::parse_chain(&buf).is_err());
557
558        let pair = vec![
559            CreateContext {
560                name: b"QFid".to_vec(),
561                data: vec![],
562            },
563            CreateContext {
564                name: b"MxAc".to_vec(),
565                data: vec![0; 8],
566            },
567        ];
568        let mut chain = Vec::new();
569        CreateContext::encode_chain(&pair, &mut chain).unwrap();
570        let next = u32::from_le_bytes(chain[0..4].try_into().unwrap());
571        // Data that runs from the first context into the second.
572        let mut bad = chain.clone();
573        bad[10..12].copy_from_slice(&16u16.to_le_bytes());
574        bad[12..16].copy_from_slice(&next.to_le_bytes());
575        assert!(CreateContext::parse_chain(&bad).is_err());
576        // Next inside the first header, and past the end of the chain.
577        for next in [8u32, chain.len() as u32 + 8] {
578            let mut bad = chain.clone();
579            bad[0..4].copy_from_slice(&next.to_le_bytes());
580            assert!(CreateContext::parse_chain(&bad).is_err(), "next {next}");
581        }
582    }
583
584    #[test]
585    fn empty_chain_round_trips() {
586        let ctxs: Vec<CreateContext> = vec![];
587        let mut buf = Vec::new();
588        CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
589        assert!(buf.is_empty());
590        let decoded = CreateContext::parse_chain(&buf).unwrap();
591        assert!(decoded.is_empty());
592    }
593}