Skip to main content

smb_server/proto/auth/
ntlm.rs

1//! NTLMv2 server-side authentication.
2//!
3//! Spec references (all from MS-NLMP):
4//! * §2.2.1 NTLM messages (NEGOTIATE, CHALLENGE, AUTHENTICATE)
5//! * §2.2.2 Common structures (AV_PAIR, NTLMv2_RESPONSE, NTLMv2_CLIENT_CHALLENGE)
6//! * §3.3.2 NTLM v2 Authentication algorithm
7//! * §3.4   Key derivation (`NTOWFv2`, `LMOWFv2`)
8//! * §3.4.4 Message Integrity Code (MIC)
9//! * §4.2.4 Known-answer test vectors
10//!
11//! This module implements the **server side only**. We parse incoming
12//! `NEGOTIATE_MESSAGE` (Type 1) and `AUTHENTICATE_MESSAGE` (Type 3) blobs,
13//! produce the `CHALLENGE_MESSAGE` (Type 2) reply, and validate the client's
14//! NT response to derive a session key.
15
16use hmac::{Hmac, Mac};
17use md4::{Digest, Md4};
18use md5::Md5;
19use rc4::Rc4;
20use rc4::cipher::{KeyInit, StreamCipher};
21
22use crate::proto::error::{ProtoError, ProtoResult};
23
24type HmacMd5 = Hmac<Md5>;
25
26// --- NTLMSSP signature & message types --------------------------------------
27
28/// 8-byte signature `"NTLMSSP\0"` prefixing every NTLMSSP message.
29pub const NTLMSSP_SIGNATURE: &[u8; 8] = b"NTLMSSP\0";
30
31pub const MSG_NEGOTIATE: u32 = 0x0000_0001;
32pub const MSG_CHALLENGE: u32 = 0x0000_0002;
33pub const MSG_AUTHENTICATE: u32 = 0x0000_0003;
34
35// --- NTLMSSP negotiate flags (MS-NLMP §2.2.2.5) -----------------------------
36
37pub mod flags {
38    pub const NTLMSSP_NEGOTIATE_UNICODE: u32 = 0x0000_0001;
39    pub const NTLMSSP_REQUEST_TARGET: u32 = 0x0000_0004;
40    pub const NTLMSSP_NEGOTIATE_SIGN: u32 = 0x0000_0010;
41    pub const NTLMSSP_NEGOTIATE_NTLM: u32 = 0x0000_0200;
42    #[cfg(test)]
43    pub const NTLMSSP_NEGOTIATE_ANONYMOUS: u32 = 0x0000_0800;
44    pub const NTLMSSP_NEGOTIATE_ALWAYS_SIGN: u32 = 0x0000_8000;
45    pub const NTLMSSP_TARGET_TYPE_SERVER: u32 = 0x0002_0000;
46    pub const NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: u32 = 0x0008_0000;
47    pub const NTLMSSP_NEGOTIATE_TARGET_INFO: u32 = 0x0080_0000;
48    pub const NTLMSSP_NEGOTIATE_VERSION: u32 = 0x0200_0000;
49    pub const NTLMSSP_NEGOTIATE_128: u32 = 0x2000_0000;
50    pub const NTLMSSP_NEGOTIATE_KEY_EXCH: u32 = 0x4000_0000;
51    pub const NTLMSSP_NEGOTIATE_56: u32 = 0x8000_0000;
52}
53
54// --- AV_PAIR types (MS-NLMP §2.2.2.1) ---------------------------------------
55
56#[allow(dead_code)]
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58#[repr(u16)]
59pub enum AvId {
60    Eol = 0x0000,
61    NbComputerName = 0x0001,
62    NbDomainName = 0x0002,
63    DnsComputerName = 0x0003,
64    DnsDomainName = 0x0004,
65    DnsTreeName = 0x0005,
66    Flags = 0x0006,
67    Timestamp = 0x0007,
68    SingleHost = 0x0008,
69    TargetName = 0x0009,
70    ChannelBindings = 0x000A,
71}
72
73/// One AV_PAIR (attribute–value pair) from a target-info / authenticate-target-info list.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct AvPair {
76    pub id: u16,
77    pub value: Vec<u8>,
78}
79
80impl AvPair {
81    pub fn new(id: AvId, value: Vec<u8>) -> Self {
82        Self {
83            id: id as u16,
84            value,
85        }
86    }
87}
88
89/// Encode a list of AV_PAIRs in wire format (each: 2-byte LE id, 2-byte LE
90/// length, value bytes), terminated by an `MsvAvEOL` (id=0, len=0) entry.
91pub fn encode_av_pairs(pairs: &[AvPair]) -> Vec<u8> {
92    let mut out = Vec::new();
93    for p in pairs {
94        out.extend_from_slice(&p.id.to_le_bytes());
95        out.extend_from_slice(&(p.value.len() as u16).to_le_bytes());
96        out.extend_from_slice(&p.value);
97    }
98    // Terminator
99    out.extend_from_slice(&(AvId::Eol as u16).to_le_bytes());
100    out.extend_from_slice(&0u16.to_le_bytes());
101    out
102}
103
104/// Decode AV_PAIRs from a byte slice; stops at (and consumes) the EOL entry.
105#[cfg(test)]
106pub fn decode_av_pairs(buf: &[u8]) -> ProtoResult<Vec<AvPair>> {
107    let mut out = Vec::new();
108    let mut i = 0usize;
109    loop {
110        if buf.len() < i + 4 {
111            return Err(ProtoError::Auth("av_pair list truncated"));
112        }
113        let id = u16::from_le_bytes([buf[i], buf[i + 1]]);
114        let len = u16::from_le_bytes([buf[i + 2], buf[i + 3]]) as usize;
115        i += 4;
116        if id == AvId::Eol as u16 {
117            // EOL must have len=0; tolerate stray bytes.
118            break;
119        }
120        if buf.len() < i + len {
121            return Err(ProtoError::Auth("av_pair value truncated"));
122        }
123        out.push(AvPair {
124            id,
125            value: buf[i..i + len].to_vec(),
126        });
127        i += len;
128    }
129    Ok(out)
130}
131
132// --- Helpers ---------------------------------------------------------------
133
134/// UTF-8 → UTF-16LE bytes (no BOM).
135pub fn utf16le(s: &str) -> Vec<u8> {
136    let mut out = Vec::with_capacity(s.len() * 2);
137    for unit in s.encode_utf16() {
138        out.extend_from_slice(&unit.to_le_bytes());
139    }
140    out
141}
142
143/// Decode UTF-16LE bytes into a `String` (lossy on bad surrogates).
144fn utf16le_to_string(bytes: &[u8]) -> String {
145    let units: Vec<u16> = bytes
146        .chunks_exact(2)
147        .map(|c| u16::from_le_bytes([c[0], c[1]]))
148        .collect();
149    String::from_utf16_lossy(&units)
150}
151
152/// MD4 of UTF-16LE password — the "NT hash".
153pub fn nt_hash(password: &str) -> [u8; 16] {
154    let mut h = Md4::new();
155    h.update(utf16le(password));
156    let out = h.finalize();
157    let mut o = [0u8; 16];
158    o.copy_from_slice(&out);
159    o
160}
161
162/// `NTOWFv2(password, user, domain) = HMAC_MD5(NT_hash(password), UTF-16LE(UPPER(user) || domain))`.
163///
164/// The user name is uppercased; the domain is **not** (per MS-NLMP §3.4 NTOWFv2).
165pub fn ntowf_v2(nt_hash_bytes: &[u8; 16], user: &str, domain: &str) -> [u8; 16] {
166    let mut mac = HmacMd5::new_from_slice(nt_hash_bytes).expect("HMAC accepts any key length");
167    mac.update(&utf16le(&user.to_uppercase()));
168    mac.update(&utf16le(domain));
169    let res = mac.finalize().into_bytes();
170    let mut out = [0u8; 16];
171    out.copy_from_slice(&res);
172    out
173}
174
175/// Constant-time 16-byte comparison.
176fn ct_eq_16(a: &[u8], b: &[u8]) -> bool {
177    if a.len() != b.len() {
178        return false;
179    }
180    let mut diff = 0u8;
181    for (x, y) in a.iter().zip(b.iter()) {
182        diff |= x ^ y;
183    }
184    diff == 0
185}
186
187// --- Read helpers for NTLMSSP fields -----------------------------------------
188
189/// A `(len, max_len, offset)` field descriptor as used throughout NTLMSSP messages.
190/// The parser keeps the fields used to slice payloads; `max_len` is ignored.
191#[derive(Debug, Clone, Copy)]
192struct Field {
193    len: u16,
194    offset: u32,
195}
196
197fn read_field(buf: &[u8], at: usize) -> ProtoResult<Field> {
198    if buf.len() < at + 8 {
199        return Err(ProtoError::Auth("field descriptor truncated"));
200    }
201    let _max_len = u16::from_le_bytes([buf[at + 2], buf[at + 3]]);
202    Ok(Field {
203        len: u16::from_le_bytes([buf[at], buf[at + 1]]),
204        offset: u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]),
205    })
206}
207
208fn slice_field(buf: &[u8], f: Field) -> ProtoResult<&[u8]> {
209    let start = f.offset as usize;
210    let end = start.saturating_add(f.len as usize);
211    if end > buf.len() {
212        return Err(ProtoError::Auth("field slice out of range"));
213    }
214    Ok(&buf[start..end])
215}
216
217fn check_signature(buf: &[u8], expected_msg: u32) -> ProtoResult<()> {
218    if buf.len() < 12 {
219        return Err(ProtoError::Auth("ntlmssp message too short"));
220    }
221    if &buf[..8] != NTLMSSP_SIGNATURE {
222        return Err(ProtoError::Auth("ntlmssp signature mismatch"));
223    }
224    let msg = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]);
225    if msg != expected_msg {
226        return Err(ProtoError::Auth("unexpected ntlmssp message type"));
227    }
228    Ok(())
229}
230
231// --- NEGOTIATE_MESSAGE (Type 1) ---------------------------------------------
232
233#[derive(Debug, Clone, Default)]
234pub struct NtlmNegotiate {
235    pub flags: u32,
236    pub domain: Vec<u8>,
237    pub workstation: Vec<u8>,
238    /// Raw bytes of the original message — needed for MIC computation later.
239    pub raw: Vec<u8>,
240}
241
242impl NtlmNegotiate {
243    /// Parse a Type 1 NEGOTIATE_MESSAGE.
244    ///
245    /// Layout (MS-NLMP §2.2.1.1):
246    /// ```text
247    /// 0  : "NTLMSSP\0"
248    /// 8  : MessageType = 0x01 (u32 LE)
249    /// 12 : NegotiateFlags (u32 LE)
250    /// 16 : DomainNameFields (8 bytes: len, maxlen, offset)
251    /// 24 : WorkstationFields (8 bytes)
252    /// 32 : Version (8 bytes, optional — only if NTLMSSP_NEGOTIATE_VERSION set)
253    /// ```
254    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
255        check_signature(buf, MSG_NEGOTIATE)?;
256        if buf.len() < 32 {
257            return Err(ProtoError::Auth("NEGOTIATE_MESSAGE too short"));
258        }
259        let flags = u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]);
260        let domain_field = read_field(buf, 16)?;
261        let ws_field = read_field(buf, 24)?;
262
263        // Fields may be empty (offset/len = 0) when supplied flags don't set them.
264        let domain = if domain_field.len == 0 {
265            Vec::new()
266        } else {
267            slice_field(buf, domain_field)?.to_vec()
268        };
269        let workstation = if ws_field.len == 0 {
270            Vec::new()
271        } else {
272            slice_field(buf, ws_field)?.to_vec()
273        };
274
275        Ok(Self {
276            flags,
277            domain,
278            workstation,
279            raw: buf.to_vec(),
280        })
281    }
282}
283
284// --- CHALLENGE_MESSAGE (Type 2) ---------------------------------------------
285
286/// Server-side construction parameters for the CHALLENGE_MESSAGE.
287#[derive(Debug, Clone)]
288pub struct ChallengeParams<'a> {
289    pub server_challenge: [u8; 8],
290    pub target_name: &'a str,
291    pub nb_domain_name: &'a str,
292    pub nb_computer_name: &'a str,
293    pub dns_domain_name: &'a str,
294    pub dns_computer_name: &'a str,
295    /// Windows FILETIME (100-ns intervals since 1601-01-01) — caller-provided
296    /// so this module stays clock-free.
297    pub timestamp: u64,
298    /// Negotiated flags (already AND-ed with server policy).
299    pub flags: u32,
300}
301
302/// Build a Type 2 CHALLENGE_MESSAGE.
303///
304/// Layout (MS-NLMP §2.2.1.2):
305/// ```text
306/// 0  : "NTLMSSP\0"
307/// 8  : MessageType = 0x02
308/// 12 : TargetNameFields (8 bytes)
309/// 20 : NegotiateFlags (4 bytes)
310/// 24 : ServerChallenge (8 bytes)
311/// 32 : Reserved (8 bytes, zeroed)
312/// 40 : TargetInfoFields (8 bytes)
313/// 48 : Version (8 bytes)
314/// 56 : Payload...
315/// ```
316pub fn build_challenge(p: &ChallengeParams<'_>) -> Vec<u8> {
317    let target_name_utf16 = utf16le(p.target_name);
318    let av_pairs = vec![
319        AvPair::new(AvId::NbDomainName, utf16le(p.nb_domain_name)),
320        AvPair::new(AvId::NbComputerName, utf16le(p.nb_computer_name)),
321        AvPair::new(AvId::DnsDomainName, utf16le(p.dns_domain_name)),
322        AvPair::new(AvId::DnsComputerName, utf16le(p.dns_computer_name)),
323        AvPair::new(AvId::Timestamp, p.timestamp.to_le_bytes().to_vec()),
324    ];
325    let target_info = encode_av_pairs(&av_pairs);
326
327    let header_len: u32 = 56;
328    let target_name_offset = header_len;
329    let target_info_offset = target_name_offset + target_name_utf16.len() as u32;
330
331    let mut out =
332        Vec::with_capacity(header_len as usize + target_name_utf16.len() + target_info.len());
333    // 0..8: signature
334    out.extend_from_slice(NTLMSSP_SIGNATURE);
335    // 8..12: message type
336    out.extend_from_slice(&MSG_CHALLENGE.to_le_bytes());
337    // 12..20: TargetNameFields
338    let tn_len = target_name_utf16.len() as u16;
339    out.extend_from_slice(&tn_len.to_le_bytes());
340    out.extend_from_slice(&tn_len.to_le_bytes());
341    out.extend_from_slice(&target_name_offset.to_le_bytes());
342    // 20..24: NegotiateFlags
343    out.extend_from_slice(&p.flags.to_le_bytes());
344    // 24..32: ServerChallenge
345    out.extend_from_slice(&p.server_challenge);
346    // 32..40: Reserved
347    out.extend_from_slice(&[0u8; 8]);
348    // 40..48: TargetInfoFields
349    let ti_len = target_info.len() as u16;
350    out.extend_from_slice(&ti_len.to_le_bytes());
351    out.extend_from_slice(&ti_len.to_le_bytes());
352    out.extend_from_slice(&target_info_offset.to_le_bytes());
353    // 48..56: Version (we report 6.1.7600 / NTLMSSP rev 0x0F as a stable choice).
354    // Per spec, only meaningful if NTLMSSP_NEGOTIATE_VERSION is set; harmless otherwise.
355    out.extend_from_slice(&[6, 1, 0, 0x1D, 0, 0, 0, 0x0F]);
356    // payload
357    out.extend_from_slice(&target_name_utf16);
358    out.extend_from_slice(&target_info);
359    out
360}
361
362// --- AUTHENTICATE_MESSAGE (Type 3) ------------------------------------------
363
364#[derive(Debug, Clone)]
365pub struct NtlmAuthenticate {
366    pub flags: u32,
367    #[allow(dead_code)]
368    pub lm_response: Vec<u8>,
369    pub nt_response: Vec<u8>,
370    pub domain: String,
371    pub user: String,
372    #[allow(dead_code)]
373    pub workstation: String,
374    pub encrypted_random_session_key: Vec<u8>,
375    /// Optional MIC (16 bytes, zeroed in source bytes during the MIC HMAC).
376    pub mic: Option<[u8; 16]>,
377    /// Offset of the MIC field within `raw`, if present (for re-zero during validation).
378    pub mic_offset: Option<usize>,
379    /// Raw bytes of the original message — needed for MIC computation.
380    pub raw: Vec<u8>,
381}
382
383impl NtlmAuthenticate {
384    /// Parse a Type 3 AUTHENTICATE_MESSAGE.
385    ///
386    /// Layout (MS-NLMP §2.2.1.3):
387    /// ```text
388    /// 0  : "NTLMSSP\0"
389    /// 8  : MessageType = 0x03
390    /// 12 : LmChallengeResponseFields
391    /// 20 : NtChallengeResponseFields
392    /// 28 : DomainNameFields
393    /// 36 : UserNameFields
394    /// 44 : WorkstationFields
395    /// 52 : EncryptedRandomSessionKeyFields
396    /// 60 : NegotiateFlags (4 bytes)
397    /// 64 : Version (8 bytes)
398    /// 72 : MIC (16 bytes — present only in some versions)
399    /// 88 : Payload...
400    /// ```
401    /// The MIC is present only when an `MsvAvFlags` AV_PAIR with bit 0x2 was
402    /// echoed by the client. We detect "MIC present" heuristically by checking
403    /// whether the smallest field-payload offset ≥ 88; if it is ≥ 88, bytes
404    /// 72..88 are interpreted as the MIC. Otherwise no MIC.
405    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
406        check_signature(buf, MSG_AUTHENTICATE)?;
407        if buf.len() < 64 {
408            return Err(ProtoError::Auth("AUTHENTICATE_MESSAGE too short"));
409        }
410        let lm_field = read_field(buf, 12)?;
411        let nt_field = read_field(buf, 20)?;
412        let domain_field = read_field(buf, 28)?;
413        let user_field = read_field(buf, 36)?;
414        let ws_field = read_field(buf, 44)?;
415        let key_field = read_field(buf, 52)?;
416        let flags = u32::from_le_bytes([buf[60], buf[61], buf[62], buf[63]]);
417
418        // Determine where the payload starts to know whether the MIC field is present.
419        // The smallest non-zero offset among the fields tells us.
420        let mut min_off: u32 = u32::MAX;
421        for f in [
422            lm_field,
423            nt_field,
424            domain_field,
425            user_field,
426            ws_field,
427            key_field,
428        ] {
429            if f.len > 0 && f.offset > 0 && f.offset < min_off {
430                min_off = f.offset;
431            }
432        }
433
434        let (mic, mic_offset) = if min_off != u32::MAX && min_off as usize >= 88 && buf.len() >= 88
435        {
436            let mut mic = [0u8; 16];
437            mic.copy_from_slice(&buf[72..88]);
438            (Some(mic), Some(72usize))
439        } else {
440            (None, None)
441        };
442
443        let lm_response = if lm_field.len == 0 {
444            Vec::new()
445        } else {
446            slice_field(buf, lm_field)?.to_vec()
447        };
448        let nt_response = if nt_field.len == 0 {
449            Vec::new()
450        } else {
451            slice_field(buf, nt_field)?.to_vec()
452        };
453        let domain_bytes = if domain_field.len == 0 {
454            Vec::new()
455        } else {
456            slice_field(buf, domain_field)?.to_vec()
457        };
458        let user_bytes = if user_field.len == 0 {
459            Vec::new()
460        } else {
461            slice_field(buf, user_field)?.to_vec()
462        };
463        let ws_bytes = if ws_field.len == 0 {
464            Vec::new()
465        } else {
466            slice_field(buf, ws_field)?.to_vec()
467        };
468        let encrypted_random_session_key = if key_field.len == 0 {
469            Vec::new()
470        } else {
471            slice_field(buf, key_field)?.to_vec()
472        };
473
474        // Per NTLMSSP_NEGOTIATE_UNICODE flag, names are UTF-16LE; otherwise OEM.
475        // We require Unicode — we only advertise it. Decode UTF-16LE.
476        let domain = utf16le_to_string(&domain_bytes);
477        let user = utf16le_to_string(&user_bytes);
478        let workstation = utf16le_to_string(&ws_bytes);
479
480        Ok(Self {
481            flags,
482            lm_response,
483            nt_response,
484            domain,
485            user,
486            workstation,
487            encrypted_random_session_key,
488            mic,
489            mic_offset,
490            raw: buf.to_vec(),
491        })
492    }
493}
494
495// --- Public state machine ---------------------------------------------------
496
497/// Identity recovered from a successful (or anonymous) authentication.
498#[derive(Debug, Clone, PartialEq, Eq)]
499pub enum Identity {
500    Anonymous,
501    User { user: String, domain: String },
502}
503
504/// Successful authentication outcome: identity + 16-byte session key.
505#[derive(Debug, Clone)]
506pub struct AuthOutcome {
507    pub identity: Identity,
508    pub session_key: [u8; 16],
509}
510
511/// Caller-supplied user record. We store only the precomputed NT hash —
512/// callers should derive it from the password at builder time and discard
513/// the plaintext.
514#[derive(Debug, Clone)]
515pub struct UserCreds {
516    pub nt_hash: [u8; 16],
517}
518
519impl UserCreds {
520    /// Derive the NT hash from a plaintext password (UTF-16LE then MD4).
521    pub fn from_password(password: &str) -> Self {
522        Self {
523            nt_hash: nt_hash(password),
524        }
525    }
526
527    /// Construct from a precomputed NT hash.
528    pub fn from_nt_hash(nt_hash: [u8; 16]) -> Self {
529        Self { nt_hash }
530    }
531}
532
533#[derive(Debug, Clone)]
534pub struct NtlmTargetInfo {
535    pub target_name: String,
536    pub nb_domain: String,
537    pub nb_computer: String,
538    pub dns_domain: String,
539    pub dns_computer: String,
540}
541
542impl NtlmTargetInfo {
543    pub fn new(
544        target_name: impl Into<String>,
545        nb_domain: impl Into<String>,
546        nb_computer: impl Into<String>,
547        dns_domain: impl Into<String>,
548        dns_computer: impl Into<String>,
549    ) -> Self {
550        Self {
551            target_name: target_name.into(),
552            nb_domain: nb_domain.into(),
553            nb_computer: nb_computer.into(),
554            dns_domain: dns_domain.into(),
555            dns_computer: dns_computer.into(),
556        }
557    }
558}
559
560/// Server-side state machine driving SESSION_SETUP for a single connection.
561///
562/// Lifecycle:
563/// 1. `NtlmServer::new(...)`
564/// 2. `step1_negotiate(blob)` — record the client's NEGOTIATE bytes (for MIC).
565/// 3. `challenge()` — produce CHALLENGE_MESSAGE bytes; record them too.
566/// 4. `authenticate(blob, lookup)` — validate AUTHENTICATE; return outcome.
567pub struct NtlmServer {
568    server_challenge: [u8; 8],
569    target_name: String,
570    nb_domain: String,
571    nb_computer: String,
572    dns_domain: String,
573    dns_computer: String,
574    timestamp: u64,
575    /// Flags we will advertise in the CHALLENGE.
576    server_flags: u32,
577    /// Negotiated flags after considering the client's NEGOTIATE.
578    negotiated_flags: u32,
579
580    /// Bytes of the client NEGOTIATE_MESSAGE (for MIC HMAC over N||C||A).
581    negotiate_bytes: Vec<u8>,
582    /// Bytes of the server CHALLENGE_MESSAGE (for MIC HMAC).
583    challenge_bytes: Vec<u8>,
584}
585
586impl NtlmServer {
587    /// Create a new server-side acceptor.
588    pub fn new(server_challenge: [u8; 8], target: NtlmTargetInfo, timestamp: u64) -> Self {
589        // Default server flag set — what we are willing to support.
590        let server_flags = flags::NTLMSSP_NEGOTIATE_UNICODE
591            | flags::NTLMSSP_REQUEST_TARGET
592            | flags::NTLMSSP_NEGOTIATE_NTLM
593            | flags::NTLMSSP_NEGOTIATE_SIGN
594            | flags::NTLMSSP_NEGOTIATE_ALWAYS_SIGN
595            | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
596            | flags::NTLMSSP_TARGET_TYPE_SERVER
597            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
598            | flags::NTLMSSP_NEGOTIATE_VERSION
599            | flags::NTLMSSP_NEGOTIATE_128
600            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
601            | flags::NTLMSSP_NEGOTIATE_56;
602
603        Self {
604            server_challenge,
605            target_name: target.target_name,
606            nb_domain: target.nb_domain,
607            nb_computer: target.nb_computer,
608            dns_domain: target.dns_domain,
609            dns_computer: target.dns_computer,
610            timestamp,
611            server_flags,
612            negotiated_flags: server_flags,
613            negotiate_bytes: Vec::new(),
614            challenge_bytes: Vec::new(),
615        }
616    }
617
618    /// Record the client's NEGOTIATE_MESSAGE bytes and intersect flags.
619    /// This must be called before `challenge()` if a MIC will be validated.
620    pub fn step1_negotiate(&mut self, blob: &[u8]) -> ProtoResult<NtlmNegotiate> {
621        let n = NtlmNegotiate::parse(blob)?;
622        // Negotiate down: only keep flags both sides set, then keep our must-have ones.
623        self.negotiated_flags = (self.server_flags & n.flags)
624            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
625            | flags::NTLMSSP_TARGET_TYPE_SERVER
626            | flags::NTLMSSP_NEGOTIATE_UNICODE;
627        self.negotiate_bytes = n.raw.clone();
628        Ok(n)
629    }
630
631    /// Build the CHALLENGE_MESSAGE blob. Stores the bytes for later MIC use.
632    pub fn challenge(&mut self) -> Vec<u8> {
633        let blob = build_challenge(&ChallengeParams {
634            server_challenge: self.server_challenge,
635            target_name: &self.target_name,
636            nb_domain_name: &self.nb_domain,
637            nb_computer_name: &self.nb_computer,
638            dns_domain_name: &self.dns_domain,
639            dns_computer_name: &self.dns_computer,
640            timestamp: self.timestamp,
641            flags: self.negotiated_flags,
642        });
643        self.challenge_bytes = blob.clone();
644        blob
645    }
646
647    /// Validate the AUTHENTICATE_MESSAGE.
648    ///
649    /// `lookup` is the application's user-database hook: given the user/domain
650    /// from the wire, return `Some(UserCreds)` if known, `None` otherwise.
651    ///
652    /// Returns `AuthOutcome::session_key` to be plugged into SMB2 KDF.
653    /// Anonymous logon (empty user + empty NT response) returns a zeroed key
654    /// and `Identity::Anonymous`.
655    pub fn authenticate<F>(&self, blob: &[u8], lookup: F) -> ProtoResult<AuthOutcome>
656    where
657        F: Fn(&str, &str) -> Option<UserCreds>,
658    {
659        let auth = NtlmAuthenticate::parse(blob)?;
660
661        // ---- Anonymous fast path. MS-NLMP §3.2.5.1.2: empty user + empty NT
662        // response (or single-zero-byte LM response) means anonymous logon.
663        if auth.user.is_empty() && auth.nt_response.is_empty() {
664            return Ok(AuthOutcome {
665                identity: Identity::Anonymous,
666                session_key: [0u8; 16],
667            });
668        }
669
670        // ---- Locate creds.
671        let creds = lookup(&auth.user, &auth.domain).ok_or(ProtoError::Auth("unknown user"))?;
672
673        // ---- NTOWFv2 = HMAC_MD5(NT_hash, UTF-16LE(UPPER(user) || domain))
674        let response_key_nt = ntowf_v2(&creds.nt_hash, &auth.user, &auth.domain);
675
676        // ---- NTLMv2 response layout (MS-NLMP §2.2.2.8):
677        //   16 bytes NTProofStr || NTLMv2_CLIENT_CHALLENGE blob
678        if auth.nt_response.len() < 16 {
679            return Err(ProtoError::Auth("NT response too short"));
680        }
681        let (nt_proof_supplied, client_challenge) = auth.nt_response.split_at(16);
682
683        // ---- NTProofStr = HMAC_MD5(response_key_nt, ServerChallenge || ClientChallenge)
684        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
685        mac.update(&self.server_challenge);
686        mac.update(client_challenge);
687        let nt_proof_computed = mac.finalize().into_bytes();
688
689        if !ct_eq_16(nt_proof_supplied, &nt_proof_computed) {
690            return Err(ProtoError::Auth("NT proof mismatch"));
691        }
692
693        // ---- SessionBaseKey = HMAC_MD5(response_key_nt, NTProofStr)
694        // (MS-NLMP §3.4 — for NTLMv2, KeyExchangeKey = SessionBaseKey.)
695        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
696        mac.update(&nt_proof_computed);
697        let session_base_key_bytes = mac.finalize().into_bytes();
698        let mut key_exchange_key = [0u8; 16];
699        key_exchange_key.copy_from_slice(&session_base_key_bytes);
700
701        // ---- Optional RC4-wrapped random session key.
702        let session_key = if (auth.flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH) != 0
703            && !auth.encrypted_random_session_key.is_empty()
704        {
705            if auth.encrypted_random_session_key.len() != 16 {
706                return Err(ProtoError::Auth("encrypted session key not 16 bytes"));
707            }
708            let mut buf = [0u8; 16];
709            buf.copy_from_slice(&auth.encrypted_random_session_key);
710            // RC4(KeyExchangeKey) over the encrypted session key.
711            let mut rc4 = Rc4::new_from_slice(&key_exchange_key)
712                .map_err(|_| ProtoError::Auth("rc4 key length"))?;
713            rc4.apply_keystream(&mut buf);
714            buf
715        } else {
716            key_exchange_key
717        };
718
719        // ---- MIC validation: HMAC_MD5(SessionKey, NEGOTIATE || CHALLENGE || AUTHENTICATE-with-MIC-zeroed).
720        // We only validate if the client supplied a MIC (i.e. presence
721        // detected during parse) AND we actually have the negotiate/challenge
722        // bytes. If absent, treat as not supplied. This v1 server does not
723        // enforce MsvAvFlags bit 0x2 from the challenge target-info.
724        if let (Some(mic_off), true) = (auth.mic_offset, !self.negotiate_bytes.is_empty())
725            && let Some(supplied) = auth.mic
726        {
727            let mut auth_zeroed = auth.raw.clone();
728            if auth_zeroed.len() < mic_off + 16 {
729                return Err(ProtoError::Auth("MIC offset out of range"));
730            }
731            for b in &mut auth_zeroed[mic_off..mic_off + 16] {
732                *b = 0;
733            }
734            let mut mac = HmacMd5::new_from_slice(&session_key).expect("hmac key");
735            mac.update(&self.negotiate_bytes);
736            mac.update(&self.challenge_bytes);
737            mac.update(&auth_zeroed);
738            let computed = mac.finalize().into_bytes();
739            if !ct_eq_16(&supplied, &computed) {
740                return Err(ProtoError::Auth("MIC mismatch"));
741            }
742        }
743
744        Ok(AuthOutcome {
745            identity: Identity::User {
746                user: auth.user.clone(),
747                domain: auth.domain.clone(),
748            },
749            session_key,
750        })
751    }
752}
753
754// ===========================================================================
755// Tests
756// ===========================================================================
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761
762    #[test]
763    fn av_pair_round_trip() {
764        let pairs = vec![
765            AvPair::new(AvId::NbDomainName, utf16le("DOMAIN")),
766            AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
767            AvPair::new(
768                AvId::Timestamp,
769                0x1234_5678_9abc_def0u64.to_le_bytes().to_vec(),
770            ),
771        ];
772        let bytes = encode_av_pairs(&pairs);
773        let decoded = decode_av_pairs(&bytes).unwrap();
774        assert_eq!(decoded, pairs);
775    }
776
777    #[test]
778    fn negotiate_round_trip() {
779        // Build a minimal Type 1 by hand and parse it.
780        let mut buf = Vec::new();
781        buf.extend_from_slice(NTLMSSP_SIGNATURE);
782        buf.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
783        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
784            | flags::NTLMSSP_NEGOTIATE_NTLM
785            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO;
786        buf.extend_from_slice(&flags.to_le_bytes());
787        // Domain + workstation fields: empty.
788        buf.extend_from_slice(&[0u8; 8]);
789        buf.extend_from_slice(&[0u8; 8]);
790        // Version (8 bytes).
791        buf.extend_from_slice(&[0u8; 8]);
792
793        let n = NtlmNegotiate::parse(&buf).unwrap();
794        assert_eq!(n.flags, flags);
795        assert!(n.domain.is_empty());
796        assert!(n.workstation.is_empty());
797    }
798
799    #[test]
800    fn challenge_round_trip_structure() {
801        let blob = build_challenge(&ChallengeParams {
802            server_challenge: [1, 2, 3, 4, 5, 6, 7, 8],
803            target_name: "SERVER",
804            nb_domain_name: "DOMAIN",
805            nb_computer_name: "SERVER",
806            dns_domain_name: "domain.local",
807            dns_computer_name: "server.domain.local",
808            timestamp: 0,
809            flags: flags::NTLMSSP_NEGOTIATE_UNICODE
810                | flags::NTLMSSP_NEGOTIATE_NTLM
811                | flags::NTLMSSP_NEGOTIATE_TARGET_INFO,
812        });
813        // Signature + message type.
814        assert_eq!(&blob[..8], NTLMSSP_SIGNATURE);
815        assert_eq!(
816            u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]),
817            MSG_CHALLENGE
818        );
819        // Server challenge at offset 24.
820        assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
821        // Decode AV_PAIRs from the target-info section.
822        let ti_off = u32::from_le_bytes([blob[44], blob[45], blob[46], blob[47]]) as usize;
823        let ti_len = u16::from_le_bytes([blob[40], blob[41]]) as usize;
824        let av = decode_av_pairs(&blob[ti_off..ti_off + ti_len]).unwrap();
825        assert!(av.iter().any(|p| p.id == AvId::NbDomainName as u16));
826        assert!(av.iter().any(|p| p.id == AvId::Timestamp as u16));
827    }
828
829    /// MS-NLMP §4.2.4 known-answer test for NTLMv2:
830    ///     User="User", Domain="Domain", Password="Password"
831    ///     ServerChallenge = 01 23 45 67 89 ab cd ef
832    ///     ClientChallenge AV-pair blob = 01 01 00 00 00 00 00 00
833    ///                                    00 00 00 00 00 00 00 00
834    ///                                    aa aa aa aa aa aa aa aa
835    ///                                    00 00 00 00 02 00 0c 00
836    ///                                    44 00 6f 00 6d 00 61 00
837    ///                                    69 00 6e 00 01 00 0c 00
838    ///                                    53 00 65 00 72 00 76 00
839    ///                                    65 00 72 00 00 00 00 00
840    ///                                    00 00 00 00
841    /// Expected NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
842    /// (Note: there are several editions of MS-NLMP with subtly different
843    /// vectors; this matches the §4.2.4.1.3 vector that includes the trailing
844    /// 4 zero bytes, common across recent revisions.)
845    #[test]
846    fn ntlmv2_known_answer() {
847        let nt = nt_hash("Password");
848        // NT hash of "Password" — MS-NLMP §4.2.2.1.4: a4 f4 9c 40 65 10 bd ca b6 82 4e e7 c3 0f d8 52
849        assert_eq!(
850            nt,
851            [
852                0xa4, 0xf4, 0x9c, 0x40, 0x65, 0x10, 0xbd, 0xca, 0xb6, 0x82, 0x4e, 0xe7, 0xc3, 0x0f,
853                0xd8, 0x52
854            ]
855        );
856
857        // NTOWFv2("Password","User","Domain")
858        // MS-NLMP §4.2.4.1.1: 0c 86 8a 40 3b fd 7a 93 a3 00 1e f2 2e f0 2e 3f
859        let key_nt = ntowf_v2(&nt, "User", "Domain");
860        assert_eq!(
861            key_nt,
862            [
863                0x0c, 0x86, 0x8a, 0x40, 0x3b, 0xfd, 0x7a, 0x93, 0xa3, 0x00, 0x1e, 0xf2, 0x2e, 0xf0,
864                0x2e, 0x3f
865            ]
866        );
867
868        let server_challenge: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
869        // NTLMv2_CLIENT_CHALLENGE blob from §4.2.4.1.3
870        let client_challenge_blob: &[u8] = &[
871            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // RespType, HiRespType, Reserved
872            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TimeStamp
873            0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, // ChallengeFromClient
874            0x00, 0x00, 0x00, 0x00, // Reserved
875            // AV pairs
876            0x02, 0x00, 0x0c, 0x00, // MsvAvNbDomainName, len=12
877            0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e,
878            0x00, // "Domain"
879            0x01, 0x00, 0x0c, 0x00, // MsvAvNbComputerName, len=12
880            0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
881            0x00, // "Server"
882            0x00, 0x00, 0x00, 0x00, // EOL
883            0x00, 0x00, 0x00, 0x00, // trailing 4 zero bytes (padding seen in spec)
884        ];
885
886        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
887        mac.update(&server_challenge);
888        mac.update(client_challenge_blob);
889        let nt_proof = mac.finalize().into_bytes();
890
891        // MS-NLMP §4.2.4.2.2:
892        //   NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
893        assert_eq!(
894            nt_proof.as_slice(),
895            [
896                0x68, 0xcd, 0x0a, 0xb8, 0x51, 0xe5, 0x1c, 0x96, 0xaa, 0xbc, 0x92, 0x7b, 0xeb, 0xef,
897                0x6a, 0x1c
898            ]
899        );
900    }
901
902    #[test]
903    fn server_round_trip_authenticates_user() {
904        // End-to-end: build a fake AUTHENTICATE_MESSAGE with a known proof and
905        // make sure NtlmServer accepts it.
906        let mut srv = NtlmServer::new(
907            [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
908            NtlmTargetInfo::new(
909                "SERVER",
910                "DOMAIN",
911                "SERVER",
912                "domain.local",
913                "server.domain.local",
914            ),
915            0,
916        );
917        // Skip step1_negotiate — MIC will be absent.
918        let _challenge = srv.challenge();
919
920        // Compute NTProofStr the same way the client would.
921        let nt = nt_hash("Password");
922        let key_nt = ntowf_v2(&nt, "User", "Domain");
923        let client_challenge_blob: Vec<u8> = vec![
924            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
925            0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
926            // Empty AV pair list (EOL only)
927            0x00, 0x00, 0x00, 0x00,
928        ];
929        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
930        mac.update(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
931        mac.update(&client_challenge_blob);
932        let nt_proof = mac.finalize().into_bytes();
933
934        let mut nt_response = Vec::new();
935        nt_response.extend_from_slice(&nt_proof);
936        nt_response.extend_from_slice(&client_challenge_blob);
937
938        // Build AUTHENTICATE_MESSAGE.
939        let user_u16 = utf16le("User");
940        let dom_u16 = utf16le("Domain");
941        let ws_u16 = utf16le("CLIENT");
942        let lm_response: Vec<u8> = vec![0u8; 24];
943
944        // Layout: header is 72 bytes when no MIC is present
945        // (signature 8 + msgtype 4 + 6×8-byte fields + flags 4 + version 8 = 72).
946        // With MIC, it would be 88.
947        let header_len: u32 = 72;
948        let mut payload = Vec::new();
949        let lm_off = header_len;
950        payload.extend_from_slice(&lm_response);
951        let nt_off = header_len + payload.len() as u32;
952        payload.extend_from_slice(&nt_response);
953        let dom_off = header_len + payload.len() as u32;
954        payload.extend_from_slice(&dom_u16);
955        let user_off = header_len + payload.len() as u32;
956        payload.extend_from_slice(&user_u16);
957        let ws_off = header_len + payload.len() as u32;
958        payload.extend_from_slice(&ws_u16);
959        let key_off = header_len + payload.len() as u32;
960        // No encrypted session key.
961
962        let mut buf = Vec::new();
963        buf.extend_from_slice(NTLMSSP_SIGNATURE);
964        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
965        // Lm
966        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
967        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
968        buf.extend_from_slice(&lm_off.to_le_bytes());
969        // Nt
970        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
971        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
972        buf.extend_from_slice(&nt_off.to_le_bytes());
973        // Domain
974        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
975        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
976        buf.extend_from_slice(&dom_off.to_le_bytes());
977        // User
978        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
979        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
980        buf.extend_from_slice(&user_off.to_le_bytes());
981        // Workstation
982        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
983        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
984        buf.extend_from_slice(&ws_off.to_le_bytes());
985        // EncryptedRandomSessionKey
986        buf.extend_from_slice(&0u16.to_le_bytes());
987        buf.extend_from_slice(&0u16.to_le_bytes());
988        buf.extend_from_slice(&key_off.to_le_bytes());
989        // Flags
990        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
991        // Version (8 bytes)
992        buf.extend_from_slice(&[0u8; 8]);
993        // No MIC — header is 64 bytes flat.
994        assert_eq!(buf.len() as u32, header_len);
995        buf.extend_from_slice(&payload);
996
997        let creds = UserCreds::from_password("Password");
998        let outcome = srv
999            .authenticate(&buf, |u, d| {
1000                if u == "User" && d == "Domain" {
1001                    Some(creds.clone())
1002                } else {
1003                    None
1004                }
1005            })
1006            .expect("auth should succeed");
1007
1008        assert_eq!(
1009            outcome.identity,
1010            Identity::User {
1011                user: "User".to_string(),
1012                domain: "Domain".to_string()
1013            }
1014        );
1015
1016        // Wrong password should fail with constant-time mismatch.
1017        let bad = UserCreds::from_password("WrongPassword");
1018        let err = srv
1019            .authenticate(&buf, |_u, _d| Some(bad.clone()))
1020            .unwrap_err();
1021        assert!(matches!(err, ProtoError::Auth(_)));
1022    }
1023
1024    #[test]
1025    fn anonymous_logon() {
1026        let mut srv = NtlmServer::new(
1027            [0u8; 8],
1028            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1029            0,
1030        );
1031        let _ = srv.challenge();
1032
1033        // Build an AUTHENTICATE_MESSAGE with empty user + empty NT response.
1034        let header_len: u32 = 72;
1035        let mut buf = Vec::new();
1036        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1037        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1038        for _ in 0..6 {
1039            // 6 empty fields (Lm, Nt, Domain, User, Workstation, Key)
1040            buf.extend_from_slice(&0u16.to_le_bytes());
1041            buf.extend_from_slice(&0u16.to_le_bytes());
1042            buf.extend_from_slice(&header_len.to_le_bytes());
1043        }
1044        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_ANONYMOUS.to_le_bytes());
1045        buf.extend_from_slice(&[0u8; 8]); // version
1046
1047        let outcome = srv
1048            .authenticate(&buf, |_u, _d| None)
1049            .expect("anonymous should succeed");
1050        assert_eq!(outcome.identity, Identity::Anonymous);
1051        assert_eq!(outcome.session_key, [0u8; 16]);
1052    }
1053}