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