Skip to main content

smb_server/proto/messages/
negotiate.rs

1//! NEGOTIATE Request/Response (MS-SMB2 §2.2.3 / §2.2.4) including the SMB
2//! 3.1.1 negotiate-context machinery from §2.2.3.1.x and §2.2.4.x.
3
4use binrw::{BinRead, BinWrite, binrw};
5use std::io::Cursor;
6
7use crate::proto::error::ProtoResult;
8
9// ---------------------------------------------------------------------------
10// Dialect
11// ---------------------------------------------------------------------------
12
13/// SMB2 dialect revision codes (MS-SMB2 §2.2.3 - DialectRevision).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[repr(u16)]
16pub enum Dialect {
17    Smb202 = 0x0202,
18    Smb210 = 0x0210,
19    Smb300 = 0x0300,
20    Smb302 = 0x0302,
21    Smb311 = 0x0311,
22    /// "SMB 2.???" wildcard (0x02FF), returned in reply to an SMB1 NEGOTIATE
23    /// that offers it.
24    Smb2Wildcard = 0x02FF,
25}
26
27impl Dialect {
28    pub fn from_u16(v: u16) -> Option<Self> {
29        Some(match v {
30            0x0202 => Self::Smb202,
31            0x0210 => Self::Smb210,
32            0x0300 => Self::Smb300,
33            0x0302 => Self::Smb302,
34            0x0311 => Self::Smb311,
35            0x02FF => Self::Smb2Wildcard,
36            _ => return None,
37        })
38    }
39
40    pub const fn as_u16(self) -> u16 {
41        self as u16
42    }
43}
44
45// ---------------------------------------------------------------------------
46// Negotiate request
47// ---------------------------------------------------------------------------
48
49/// MS-SMB2 §2.2.3 NEGOTIATE Request.
50///
51/// `dialects` is a sequence of u16 little-endian dialect codes; for SMB 3.1.1
52/// the trailing `negotiate_context_list` carries variable-length contexts at
53/// `negotiate_context_offset`.
54///
55/// `negotiate_context_list` is not read here: its offset is relative to the
56/// start of the SMB2 header, not to this body. Resolve it against the full
57/// packet and decode the contexts with [`NegotiateContext::parse_list`].
58#[binrw]
59#[brw(little)]
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct NegotiateRequest {
62    pub structure_size: u16,
63    pub dialect_count: u16,
64    pub security_mode: u16,
65    pub reserved: u16,
66    pub capabilities: u32,
67    pub client_guid: [u8; 16],
68    /// 3.1.1: NegotiateContextOffset. 2.x/3.0/3.0.2: ClientStartTime.
69    pub negotiate_context_offset_or_client_start_time: u64,
70    #[br(count = dialect_count as usize)]
71    pub dialects: Vec<u16>,
72}
73
74impl NegotiateRequest {
75    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
76        Ok(Self::read(&mut Cursor::new(buf))?)
77    }
78    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
79        let mut c = Cursor::new(Vec::new());
80        BinWrite::write(self, &mut c)?;
81        out.extend_from_slice(&c.into_inner());
82        Ok(())
83    }
84}
85
86// ---------------------------------------------------------------------------
87// Negotiate response
88// ---------------------------------------------------------------------------
89
90/// MS-SMB2 §2.2.4 NEGOTIATE Response.
91///
92/// The trailing `security_buffer` and (3.1.1) `negotiate_context_list` are
93/// referenced by absolute offsets from the start of the SMB2 header. This
94/// struct holds the fixed portion and a `security_buffer` read immediately
95/// after it. For 3.1.1, set `negotiate_context_offset_or_reserved2` to the
96/// 8-aligned offset after the security buffer, write this struct with
97/// [`NegotiateResponse::write_to`], then pad and append the
98/// [`NegotiateContext::encode_list`] output.
99#[binrw]
100#[brw(little)]
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct NegotiateResponse {
103    pub structure_size: u16,
104    pub security_mode: u16,
105    pub dialect_revision: u16,
106    /// 3.1.1: NegotiateContextCount. 2.x/3.0/3.0.2: Reserved.
107    pub negotiate_context_count_or_reserved: u16,
108    pub server_guid: [u8; 16],
109    pub capabilities: u32,
110    pub max_transact_size: u32,
111    pub max_read_size: u32,
112    pub max_write_size: u32,
113    /// 100ns ticks since 1601-01-01 UTC.
114    pub system_time: u64,
115    pub server_start_time: u64,
116    pub security_buffer_offset: u16,
117    pub security_buffer_length: u16,
118    /// 3.1.1: NegotiateContextOffset. 2.x/3.0/3.0.2: Reserved2.
119    pub negotiate_context_offset_or_reserved2: u32,
120    #[br(parse_with = super::read_buf, args(security_buffer_length as usize))]
121    pub security_buffer: Vec<u8>,
122}
123
124impl NegotiateResponse {
125    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
126        Ok(Self::read(&mut Cursor::new(buf))?)
127    }
128    pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
129        let mut c = Cursor::new(Vec::new());
130        BinWrite::write(self, &mut c)?;
131        out.extend_from_slice(&c.into_inner());
132        Ok(())
133    }
134}
135
136// ---------------------------------------------------------------------------
137// Negotiate contexts (SMB 3.1.1)
138// ---------------------------------------------------------------------------
139
140/// MS-SMB2 §2.2.3.1 / §2.2.4.x - NEGOTIATE_CONTEXT generic header.
141///
142/// Contexts are 8-byte-aligned in the chain (the trailing padding is between
143/// contexts; see §2.2.3.1 "Each NEGOTIATE_CONTEXT MUST be 8-byte aligned").
144/// `parse_list` / `encode_list` handle the alignment.
145#[binrw]
146#[brw(little)]
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct NegotiateContext {
149    pub context_type: u16,
150    pub data_length: u16,
151    pub reserved: u32,
152    #[br(parse_with = super::read_buf, args(data_length as usize))]
153    pub data: Vec<u8>,
154}
155
156impl NegotiateContext {
157    pub const TYPE_PREAUTH_INTEGRITY: u16 = 0x0001;
158    pub const TYPE_ENCRYPTION: u16 = 0x0002;
159    pub const TYPE_COMPRESSION: u16 = 0x0003;
160    pub const TYPE_NETNAME_NEGOTIATE: u16 = 0x0005;
161    pub const TYPE_TRANSPORT_CAPS: u16 = 0x0006;
162    pub const TYPE_RDMA_TRANSFORM: u16 = 0x0007;
163    pub const TYPE_SIGNING: u16 = 0x0008;
164
165    /// Parse a chain of negotiate contexts from `buf`. The chain is a series
166    /// of (8-byte-aligned) [`NegotiateContext`] entries. `count` comes from
167    /// the parent message's `NegotiateContextCount`.
168    pub fn parse_list(mut buf: &[u8], count: u16) -> ProtoResult<Vec<NegotiateContext>> {
169        let mut out = Vec::new();
170        let mut consumed_total = 0usize;
171        for _ in 0..count {
172            // Pad to 8-byte alignment relative to the start of the list.
173            let pad = (8 - (consumed_total % 8)) % 8;
174            if pad > 0 {
175                if buf.len() < pad {
176                    return Err(crate::proto::error::ProtoError::Malformed(
177                        "negotiate context alignment underflow",
178                    ));
179                }
180                buf = &buf[pad..];
181                consumed_total += pad;
182            }
183            let mut c = Cursor::new(buf);
184            let ctx = NegotiateContext::read(&mut c)?;
185            let consumed = c.position() as usize;
186            buf = &buf[consumed..];
187            consumed_total += consumed;
188            out.push(ctx);
189        }
190        Ok(out)
191    }
192
193    /// Encode a chain of negotiate contexts into `out`, inserting 8-byte
194    /// padding between entries.
195    pub fn encode_list(list: &[NegotiateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
196        let start = out.len();
197        for (i, ctx) in list.iter().enumerate() {
198            if i > 0 {
199                let pad = (8 - ((out.len() - start) % 8)) % 8;
200                out.extend(std::iter::repeat_n(0u8, pad));
201            }
202            let mut c = Cursor::new(Vec::new());
203            BinWrite::write(ctx, &mut c)?;
204            out.extend_from_slice(&c.into_inner());
205        }
206        Ok(())
207    }
208}
209
210/// MS-SMB2 §2.2.3.1.1 / §2.2.4.1 SMB2_PREAUTH_INTEGRITY_CAPABILITIES.
211#[binrw]
212#[brw(little)]
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct PreauthIntegrityCapabilities {
215    pub hash_algorithm_count: u16,
216    pub salt_length: u16,
217    #[br(count = hash_algorithm_count as usize)]
218    pub hash_algorithms: Vec<u16>,
219    #[br(parse_with = super::read_buf, args(salt_length as usize))]
220    pub salt: Vec<u8>,
221}
222
223impl PreauthIntegrityCapabilities {
224    /// Hash algorithm: SHA-512 (the only one defined in MS-SMB2 §2.2.3.1.1).
225    pub const HASH_SHA512: u16 = 0x0001;
226}
227
228/// MS-SMB2 §2.2.3.1.2 / §2.2.4.2 SMB2_ENCRYPTION_CAPABILITIES.
229#[binrw]
230#[brw(little)]
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub struct EncryptionCapabilities {
233    pub cipher_count: u16,
234    #[br(count = cipher_count as usize)]
235    pub ciphers: Vec<u16>,
236}
237
238impl EncryptionCapabilities {
239    pub const CIPHER_AES_128_CCM: u16 = 0x0001;
240    pub const CIPHER_AES_128_GCM: u16 = 0x0002;
241    pub const CIPHER_AES_256_CCM: u16 = 0x0003;
242    pub const CIPHER_AES_256_GCM: u16 = 0x0004;
243}
244
245/// MS-SMB2 §2.2.3.1.7 / §2.2.4.7 SMB2_SIGNING_CAPABILITIES.
246#[binrw]
247#[brw(little)]
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct SigningCapabilities {
250    pub signing_algorithm_count: u16,
251    #[br(count = signing_algorithm_count as usize)]
252    pub signing_algorithms: Vec<u16>,
253}
254
255impl SigningCapabilities {
256    pub const ALGORITHM_HMAC_SHA256: u16 = 0x0000;
257    pub const ALGORITHM_AES_CMAC: u16 = 0x0001;
258    pub const ALGORITHM_AES_GMAC: u16 = 0x0002;
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn negotiate_request_round_trips() {
267        let req = NegotiateRequest {
268            structure_size: 36,
269            dialect_count: 5,
270            security_mode: 0x0001, // signing enabled
271            reserved: 0,
272            capabilities: 0x0000_007F,
273            client_guid: [0xAB; 16],
274            negotiate_context_offset_or_client_start_time: 0x0000_0070_0000_0000,
275            dialects: vec![0x0202, 0x0210, 0x0300, 0x0302, 0x0311],
276        };
277        let mut buf = Vec::new();
278        req.write_to(&mut buf).unwrap();
279        let decoded = NegotiateRequest::parse(&buf).unwrap();
280        assert_eq!(decoded, req);
281    }
282
283    #[test]
284    fn negotiate_response_round_trips() {
285        let resp = NegotiateResponse {
286            structure_size: 65,
287            security_mode: 0x0003,
288            dialect_revision: Dialect::Smb311.as_u16(),
289            negotiate_context_count_or_reserved: 3,
290            server_guid: [0xCD; 16],
291            capabilities: 0x0000_007F,
292            max_transact_size: 0x0010_0000,
293            max_read_size: 0x0010_0000,
294            max_write_size: 0x0010_0000,
295            system_time: 0x01D9_1234_5678_9ABC,
296            server_start_time: 0,
297            security_buffer_offset: 0x80,
298            security_buffer_length: 8,
299            negotiate_context_offset_or_reserved2: 0x100,
300            security_buffer: vec![1, 2, 3, 4, 5, 6, 7, 8],
301        };
302        let mut buf = Vec::new();
303        resp.write_to(&mut buf).unwrap();
304        let decoded = NegotiateResponse::parse(&buf).unwrap();
305        assert_eq!(decoded, resp);
306    }
307
308    #[test]
309    fn dialect_round_trips() {
310        for d in [
311            Dialect::Smb202,
312            Dialect::Smb210,
313            Dialect::Smb300,
314            Dialect::Smb302,
315            Dialect::Smb311,
316            Dialect::Smb2Wildcard,
317        ] {
318            assert_eq!(Dialect::from_u16(d.as_u16()), Some(d));
319        }
320        assert_eq!(Dialect::from_u16(0xBEEF), None);
321    }
322
323    #[test]
324    fn preauth_caps_round_trips() {
325        let p = PreauthIntegrityCapabilities {
326            hash_algorithm_count: 1,
327            salt_length: 32,
328            hash_algorithms: vec![PreauthIntegrityCapabilities::HASH_SHA512],
329            salt: vec![0xAA; 32],
330        };
331        let mut buf = Vec::new();
332        let mut c = Cursor::new(&mut buf);
333        BinWrite::write(&p, &mut c).unwrap();
334        let decoded = PreauthIntegrityCapabilities::read(&mut Cursor::new(&buf)).unwrap();
335        assert_eq!(decoded, p);
336    }
337
338    #[test]
339    fn negotiate_context_list_round_trips() {
340        let list = vec![
341            NegotiateContext {
342                context_type: NegotiateContext::TYPE_PREAUTH_INTEGRITY,
343                data_length: 6,
344                reserved: 0,
345                data: vec![0x01, 0x00, 0x20, 0x00, 0x01, 0x00],
346            },
347            NegotiateContext {
348                context_type: NegotiateContext::TYPE_ENCRYPTION,
349                data_length: 4,
350                reserved: 0,
351                data: vec![0x02, 0x00, 0x02, 0x00],
352            },
353            NegotiateContext {
354                context_type: NegotiateContext::TYPE_SIGNING,
355                data_length: 4,
356                reserved: 0,
357                data: vec![0x01, 0x00, 0x01, 0x00],
358            },
359        ];
360        let mut buf = Vec::new();
361        NegotiateContext::encode_list(&list, &mut buf).unwrap();
362        let parsed = NegotiateContext::parse_list(&buf, 3).unwrap();
363        assert_eq!(parsed, list);
364    }
365}