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_SEAL: u32 = 0x0000_0020;
42    pub const NTLMSSP_NEGOTIATE_NTLM: u32 = 0x0000_0200;
43    #[cfg(test)]
44    pub const NTLMSSP_NEGOTIATE_ANONYMOUS: u32 = 0x0000_0800;
45    pub const NTLMSSP_NEGOTIATE_ALWAYS_SIGN: u32 = 0x0000_8000;
46    pub const NTLMSSP_TARGET_TYPE_SERVER: u32 = 0x0002_0000;
47    pub const NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: u32 = 0x0008_0000;
48    pub const NTLMSSP_NEGOTIATE_TARGET_INFO: u32 = 0x0080_0000;
49    pub const NTLMSSP_NEGOTIATE_VERSION: u32 = 0x0200_0000;
50    pub const NTLMSSP_NEGOTIATE_128: u32 = 0x2000_0000;
51    pub const NTLMSSP_NEGOTIATE_KEY_EXCH: u32 = 0x4000_0000;
52    pub const NTLMSSP_NEGOTIATE_56: u32 = 0x8000_0000;
53}
54
55// --- AV_PAIR types (MS-NLMP §2.2.2.1) ---------------------------------------
56
57#[allow(dead_code)]
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[repr(u16)]
60pub enum AvId {
61    Eol = 0x0000,
62    NbComputerName = 0x0001,
63    NbDomainName = 0x0002,
64    DnsComputerName = 0x0003,
65    DnsDomainName = 0x0004,
66    DnsTreeName = 0x0005,
67    Flags = 0x0006,
68    Timestamp = 0x0007,
69    SingleHost = 0x0008,
70    TargetName = 0x0009,
71    ChannelBindings = 0x000A,
72}
73
74/// One AV_PAIR (attribute-value pair) from a target-info / authenticate-target-info list.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct AvPair {
77    pub id: u16,
78    pub value: Vec<u8>,
79}
80
81impl AvPair {
82    pub fn new(id: AvId, value: Vec<u8>) -> Self {
83        Self {
84            id: id as u16,
85            value,
86        }
87    }
88}
89
90/// Encode a list of AV_PAIRs in wire format (each: 2-byte LE id, 2-byte LE
91/// length, value bytes), terminated by an `MsvAvEOL` (id=0, len=0) entry.
92pub fn encode_av_pairs(pairs: &[AvPair]) -> Vec<u8> {
93    let mut out = Vec::new();
94    for p in pairs {
95        out.extend_from_slice(&p.id.to_le_bytes());
96        out.extend_from_slice(&(p.value.len() as u16).to_le_bytes());
97        out.extend_from_slice(&p.value);
98    }
99    // Terminator
100    out.extend_from_slice(&(AvId::Eol as u16).to_le_bytes());
101    out.extend_from_slice(&0u16.to_le_bytes());
102    out
103}
104
105/// Decode AV_PAIRs from a byte slice; stops at (and consumes) the EOL entry.
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    let d = at
199        .checked_add(8)
200        .and_then(|end| buf.get(at..end))
201        .ok_or(ProtoError::Auth("field descriptor truncated"))?;
202    Ok(Field {
203        len: u16::from_le_bytes([d[0], d[1]]),
204        offset: u32::from_le_bytes([d[4], d[5], d[6], d[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    /// Raw bytes of the original message - needed for MIC computation later.
237    pub raw: Vec<u8>,
238}
239
240impl NtlmNegotiate {
241    /// Parse a Type 1 NEGOTIATE_MESSAGE.
242    ///
243    /// Layout (MS-NLMP §2.2.1.1):
244    /// ```text
245    /// 0  : "NTLMSSP\0"
246    /// 8  : MessageType = 0x01 (u32 LE)
247    /// 12 : NegotiateFlags (u32 LE)
248    /// 16 : DomainNameFields (8 bytes: len, maxlen, offset)
249    /// 24 : WorkstationFields (8 bytes)
250    /// 32 : Version (8 bytes, optional - only if NTLMSSP_NEGOTIATE_VERSION set)
251    /// ```
252    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
253        check_signature(buf, MSG_NEGOTIATE)?;
254        if buf.len() < 32 {
255            return Err(ProtoError::Auth("NEGOTIATE_MESSAGE too short"));
256        }
257        let flags = u32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]);
258        let domain_field = read_field(buf, 16)?;
259        let ws_field = read_field(buf, 24)?;
260
261        // Fields may be empty (offset/len = 0) when supplied flags don't set
262        // them. Non-empty ones must lie inside the message.
263        for field in [domain_field, ws_field] {
264            if field.len != 0 {
265                slice_field(buf, field)?;
266            }
267        }
268
269        Ok(Self {
270            flags,
271            raw: buf.to_vec(),
272        })
273    }
274}
275
276// --- CHALLENGE_MESSAGE (Type 2) ---------------------------------------------
277
278/// Server-side construction parameters for the CHALLENGE_MESSAGE.
279#[derive(Debug, Clone)]
280pub struct ChallengeParams<'a> {
281    pub server_challenge: [u8; 8],
282    pub target_name: &'a str,
283    pub nb_domain_name: &'a str,
284    pub nb_computer_name: &'a str,
285    pub dns_domain_name: &'a str,
286    pub dns_computer_name: &'a str,
287    /// Windows FILETIME (100-ns intervals since 1601-01-01), supplied by the
288    /// caller.
289    pub timestamp: u64,
290    /// Negotiated flags (already AND-ed with server policy).
291    pub flags: u32,
292}
293
294/// Build a Type 2 CHALLENGE_MESSAGE.
295///
296/// Layout (MS-NLMP §2.2.1.2):
297/// ```text
298/// 0  : "NTLMSSP\0"
299/// 8  : MessageType = 0x02
300/// 12 : TargetNameFields (8 bytes)
301/// 20 : NegotiateFlags (4 bytes)
302/// 24 : ServerChallenge (8 bytes)
303/// 32 : Reserved (8 bytes, zeroed)
304/// 40 : TargetInfoFields (8 bytes)
305/// 48 : Version (8 bytes)
306/// 56 : Payload...
307/// ```
308pub fn build_challenge(p: &ChallengeParams<'_>) -> Vec<u8> {
309    let target_name_utf16 = utf16le(p.target_name);
310    let av_pairs = vec![
311        AvPair::new(AvId::NbDomainName, utf16le(p.nb_domain_name)),
312        AvPair::new(AvId::NbComputerName, utf16le(p.nb_computer_name)),
313        AvPair::new(AvId::DnsDomainName, utf16le(p.dns_domain_name)),
314        AvPair::new(AvId::DnsComputerName, utf16le(p.dns_computer_name)),
315        AvPair::new(AvId::Timestamp, p.timestamp.to_le_bytes().to_vec()),
316    ];
317    let target_info = encode_av_pairs(&av_pairs);
318
319    let header_len: u32 = 56;
320    let target_name_offset = header_len;
321    let target_info_offset = target_name_offset + target_name_utf16.len() as u32;
322
323    let mut out =
324        Vec::with_capacity(header_len as usize + target_name_utf16.len() + target_info.len());
325    // 0..8: signature
326    out.extend_from_slice(NTLMSSP_SIGNATURE);
327    // 8..12: message type
328    out.extend_from_slice(&MSG_CHALLENGE.to_le_bytes());
329    // 12..20: TargetNameFields
330    let tn_len = target_name_utf16.len() as u16;
331    out.extend_from_slice(&tn_len.to_le_bytes());
332    out.extend_from_slice(&tn_len.to_le_bytes());
333    out.extend_from_slice(&target_name_offset.to_le_bytes());
334    // 20..24: NegotiateFlags
335    out.extend_from_slice(&p.flags.to_le_bytes());
336    // 24..32: ServerChallenge
337    out.extend_from_slice(&p.server_challenge);
338    // 32..40: Reserved
339    out.extend_from_slice(&[0u8; 8]);
340    // 40..48: TargetInfoFields
341    let ti_len = target_info.len() as u16;
342    out.extend_from_slice(&ti_len.to_le_bytes());
343    out.extend_from_slice(&ti_len.to_le_bytes());
344    out.extend_from_slice(&target_info_offset.to_le_bytes());
345    // 48..56: Version 6.1 build 7424, NTLMSSP revision 15. MS-NLMP only reads
346    // it when NTLMSSP_NEGOTIATE_VERSION is set.
347    out.extend_from_slice(&[6, 1, 0, 0x1D, 0, 0, 0, 0x0F]);
348    // payload
349    out.extend_from_slice(&target_name_utf16);
350    out.extend_from_slice(&target_info);
351    out
352}
353
354// --- AUTHENTICATE_MESSAGE (Type 3) ------------------------------------------
355
356#[derive(Debug, Clone)]
357pub struct NtlmAuthenticate {
358    pub flags: u32,
359    pub lm_response: Vec<u8>,
360    pub nt_response: Vec<u8>,
361    pub domain: String,
362    pub user: String,
363    #[allow(dead_code)]
364    pub workstation: String,
365    pub encrypted_random_session_key: Vec<u8>,
366    /// Optional MIC (16 bytes, zeroed in source bytes during the MIC HMAC).
367    pub mic: Option<[u8; 16]>,
368    /// Offset of the MIC field within `raw`, if present (for re-zero during validation).
369    pub mic_offset: Option<usize>,
370    /// Raw bytes of the original message - needed for MIC computation.
371    pub raw: Vec<u8>,
372}
373
374impl NtlmAuthenticate {
375    /// Parse a Type 3 AUTHENTICATE_MESSAGE.
376    ///
377    /// Layout (MS-NLMP §2.2.1.3):
378    /// ```text
379    /// 0  : "NTLMSSP\0"
380    /// 8  : MessageType = 0x03
381    /// 12 : LmChallengeResponseFields
382    /// 20 : NtChallengeResponseFields
383    /// 28 : DomainNameFields
384    /// 36 : UserNameFields
385    /// 44 : WorkstationFields
386    /// 52 : EncryptedRandomSessionKeyFields
387    /// 60 : NegotiateFlags (4 bytes)
388    /// 64 : Version (8 bytes)
389    /// 72 : MIC (16 bytes - present only in some versions)
390    /// 88 : Payload...
391    /// ```
392    /// The MIC is present when the AV_PAIR list of the NTLMv2 response has
393    /// an `MsvAvFlags` entry with bit 0x2 set (MS-NLMP 3.2.5.1.2); bytes
394    /// 72..88 are then read as the MIC.
395    pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
396        check_signature(buf, MSG_AUTHENTICATE)?;
397        if buf.len() < 64 {
398            return Err(ProtoError::Auth("AUTHENTICATE_MESSAGE too short"));
399        }
400        let lm_field = read_field(buf, 12)?;
401        let nt_field = read_field(buf, 20)?;
402        let domain_field = read_field(buf, 28)?;
403        let user_field = read_field(buf, 36)?;
404        let ws_field = read_field(buf, 44)?;
405        let key_field = read_field(buf, 52)?;
406        let flags = u32::from_le_bytes([buf[60], buf[61], buf[62], buf[63]]);
407
408        let lm_response = if lm_field.len == 0 {
409            Vec::new()
410        } else {
411            slice_field(buf, lm_field)?.to_vec()
412        };
413        let nt_response = if nt_field.len == 0 {
414            Vec::new()
415        } else {
416            slice_field(buf, nt_field)?.to_vec()
417        };
418        let domain_bytes = if domain_field.len == 0 {
419            Vec::new()
420        } else {
421            slice_field(buf, domain_field)?.to_vec()
422        };
423        let user_bytes = if user_field.len == 0 {
424            Vec::new()
425        } else {
426            slice_field(buf, user_field)?.to_vec()
427        };
428        let (mic, mic_offset) = if ntlmv2_av_flags(&nt_response) & MSV_AV_FLAG_MIC != 0 {
429            let field = buf
430                .get(MIC_OFFSET..MIC_OFFSET + 16)
431                .ok_or(ProtoError::Auth("MIC field missing"))?;
432            let mut mic = [0u8; 16];
433            mic.copy_from_slice(field);
434            (Some(mic), Some(MIC_OFFSET))
435        } else {
436            (None, None)
437        };
438        let ws_bytes = if ws_field.len == 0 {
439            Vec::new()
440        } else {
441            slice_field(buf, ws_field)?.to_vec()
442        };
443        let encrypted_random_session_key = if key_field.len == 0 {
444            Vec::new()
445        } else {
446            slice_field(buf, key_field)?.to_vec()
447        };
448
449        // The server advertises only NTLMSSP_NEGOTIATE_UNICODE, so names are UTF-16LE.
450        let domain = utf16le_to_string(&domain_bytes);
451        let user = utf16le_to_string(&user_bytes);
452        let workstation = utf16le_to_string(&ws_bytes);
453
454        Ok(Self {
455            flags,
456            lm_response,
457            nt_response,
458            domain,
459            user,
460            workstation,
461            encrypted_random_session_key,
462            mic,
463            mic_offset,
464            raw: buf.to_vec(),
465        })
466    }
467}
468
469/// Offset of the MIC field in an AUTHENTICATE_MESSAGE.
470const MIC_OFFSET: usize = 72;
471
472/// `MsvAvFlags` bit 0x2: the AUTHENTICATE_MESSAGE carries a MIC.
473const MSV_AV_FLAG_MIC: u32 = 0x0000_0002;
474
475/// Offset of the AV_PAIR list in an NTLMv2 response: NTProofStr (16) and
476/// the NTLMv2_CLIENT_CHALLENGE header up to AvPairs (28).
477const NTLMV2_AV_PAIRS_OFFSET: usize = 44;
478
479/// `MsvAvFlags` from the AV_PAIR list of an NTLMv2 response, or 0 when the
480/// response has no such entry or no parseable list.
481fn ntlmv2_av_flags(nt_response: &[u8]) -> u32 {
482    let Some(list) = nt_response.get(NTLMV2_AV_PAIRS_OFFSET..) else {
483        return 0;
484    };
485    let Ok(pairs) = decode_av_pairs(list) else {
486        return 0;
487    };
488    pairs
489        .iter()
490        .find(|p| p.id == AvId::Flags as u16)
491        .and_then(|p| p.value.get(..4))
492        .map_or(0, |v| u32::from_le_bytes([v[0], v[1], v[2], v[3]]))
493}
494
495/// RC4K(key, data) from MS-NLMP 6.
496fn rc4k(key: &[u8; 16], data: &[u8; 16]) -> [u8; 16] {
497    let mut out = *data;
498    Rc4::new_from_slice(key)
499        .expect("RC4 accepts a 16-byte key")
500        .apply_keystream(&mut out);
501    out
502}
503
504fn md5_concat(key: &[u8], constant: &[u8]) -> [u8; 16] {
505    let mut h = Md5::new();
506    h.update(key);
507    h.update(constant);
508    h.finalize().into()
509}
510
511/// Which side's keys an [`NtlmMac`] uses.
512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
513pub enum Direction {
514    ClientToServer,
515    ServerToClient,
516}
517
518/// NTLM message integrity for one direction, with extended session security
519/// (MS-NLMP 3.4.4.2). Keys come from SIGNKEY and SEALKEY (3.4.5.2, 3.4.5.3).
520pub struct NtlmMac {
521    signing_key: [u8; 16],
522    /// RC4 state over the sealing key. The checksum is encrypted with it
523    /// when NTLMSSP_NEGOTIATE_KEY_EXCH is negotiated.
524    handle: Option<Rc4>,
525    seq: u32,
526}
527
528impl NtlmMac {
529    /// Integrity state for `direction`, or `None` when the flags do not
530    /// negotiate both extended session security and signing or sealing.
531    pub fn new(flags: u32, exported_session_key: &[u8; 16], direction: Direction) -> Option<Self> {
532        if flags & flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY == 0
533            || flags & (flags::NTLMSSP_NEGOTIATE_SIGN | flags::NTLMSSP_NEGOTIATE_SEAL) == 0
534        {
535            return None;
536        }
537        let (sign_magic, seal_magic): (&[u8], &[u8]) = match direction {
538            Direction::ClientToServer => (
539                b"session key to client-to-server signing key magic constant\0",
540                b"session key to client-to-server sealing key magic constant\0",
541            ),
542            Direction::ServerToClient => (
543                b"session key to server-to-client signing key magic constant\0",
544                b"session key to server-to-client sealing key magic constant\0",
545            ),
546        };
547        let seal_len = if flags & flags::NTLMSSP_NEGOTIATE_128 != 0 {
548            16
549        } else if flags & flags::NTLMSSP_NEGOTIATE_56 != 0 {
550            7
551        } else {
552            5
553        };
554        let sealing_key = md5_concat(&exported_session_key[..seal_len], seal_magic);
555        let handle = (flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH != 0)
556            .then(|| Rc4::new_from_slice(&sealing_key).expect("RC4 accepts a 16-byte key"));
557        Some(Self {
558            signing_key: md5_concat(exported_session_key, sign_magic),
559            handle,
560            seq: 0,
561        })
562    }
563
564    /// NTLMSSP_MESSAGE_SIGNATURE of `message` at the next sequence number.
565    pub fn mac(&mut self, message: &[u8]) -> [u8; 16] {
566        let mut hmac = HmacMd5::new_from_slice(&self.signing_key).expect("hmac key");
567        hmac.update(&self.seq.to_le_bytes());
568        hmac.update(message);
569        let digest = hmac.finalize().into_bytes();
570        let mut checksum = [0u8; 8];
571        checksum.copy_from_slice(&digest[..8]);
572        if let Some(handle) = self.handle.as_mut() {
573            handle.apply_keystream(&mut checksum);
574        }
575        let mut out = [0u8; 16];
576        out[..4].copy_from_slice(&1u32.to_le_bytes());
577        out[4..12].copy_from_slice(&checksum);
578        out[12..].copy_from_slice(&self.seq.to_le_bytes());
579        self.seq = self.seq.wrapping_add(1);
580        out
581    }
582
583    /// Checks `signature` against the MAC of `message`, in constant time.
584    pub fn verify(&mut self, message: &[u8], signature: &[u8]) -> bool {
585        ct_eq_16(&self.mac(message), signature)
586    }
587}
588
589// --- Public state machine ---------------------------------------------------
590
591/// Identity recovered from a successful (or anonymous) authentication.
592#[derive(Debug, Clone, PartialEq, Eq)]
593pub enum Identity {
594    Anonymous,
595    User { user: String, domain: String },
596}
597
598/// Successful authentication outcome: identity + 16-byte session key.
599#[derive(Clone)]
600pub struct AuthOutcome {
601    pub identity: Identity,
602    /// ExportedSessionKey (MS-NLMP 3.2.5.1.2).
603    pub session_key: [u8; 16],
604    /// NegotiateFlags of the AUTHENTICATE_MESSAGE.
605    pub flags: u32,
606    /// The AUTHENTICATE_MESSAGE carried a MIC that matched.
607    pub mic_present: bool,
608}
609
610impl std::fmt::Debug for AuthOutcome {
611    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
612        f.debug_struct("AuthOutcome")
613            .field("identity", &self.identity)
614            .finish_non_exhaustive()
615    }
616}
617
618/// User record holding only the NT hash.
619#[derive(Clone)]
620pub struct UserCreds {
621    pub nt_hash: [u8; 16],
622}
623
624impl std::fmt::Debug for UserCreds {
625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626        f.debug_struct("UserCreds").finish_non_exhaustive()
627    }
628}
629
630impl UserCreds {
631    /// Derive the NT hash from a plaintext password (UTF-16LE then MD4).
632    pub fn from_password(password: &str) -> Self {
633        Self {
634            nt_hash: nt_hash(password),
635        }
636    }
637}
638
639#[derive(Debug, Clone)]
640pub struct NtlmTargetInfo {
641    pub target_name: String,
642    pub nb_domain: String,
643    pub nb_computer: String,
644    pub dns_domain: String,
645    pub dns_computer: String,
646}
647
648impl NtlmTargetInfo {
649    pub fn new(
650        target_name: impl Into<String>,
651        nb_domain: impl Into<String>,
652        nb_computer: impl Into<String>,
653        dns_domain: impl Into<String>,
654        dns_computer: impl Into<String>,
655    ) -> Self {
656        Self {
657            target_name: target_name.into(),
658            nb_domain: nb_domain.into(),
659            nb_computer: nb_computer.into(),
660            dns_domain: dns_domain.into(),
661            dns_computer: dns_computer.into(),
662        }
663    }
664}
665
666/// Server-side state machine driving SESSION_SETUP for a single connection.
667///
668/// Lifecycle:
669/// 1. `NtlmServer::new(...)`
670/// 2. `step1_negotiate(blob)` - record the client's NEGOTIATE bytes (for MIC).
671/// 3. `challenge()` - produce CHALLENGE_MESSAGE bytes; record them too.
672/// 4. `authenticate(blob, lookup)` - validate AUTHENTICATE; return outcome.
673pub struct NtlmServer {
674    server_challenge: [u8; 8],
675    target_name: String,
676    nb_domain: String,
677    nb_computer: String,
678    dns_domain: String,
679    dns_computer: String,
680    timestamp: u64,
681    /// Flags we will advertise in the CHALLENGE.
682    server_flags: u32,
683    /// Negotiated flags after considering the client's NEGOTIATE.
684    negotiated_flags: u32,
685
686    /// Bytes of the client NEGOTIATE_MESSAGE (for MIC HMAC over N||C||A).
687    negotiate_bytes: Vec<u8>,
688    /// Bytes of the server CHALLENGE_MESSAGE (for MIC HMAC).
689    challenge_bytes: Vec<u8>,
690
691    /// DER MechTypeList of the client's SPNEGO NegTokenInit, which the
692    /// mechListMIC covers. `None` when the client sent raw NTLMSSP.
693    pub mech_list: Option<Vec<u8>>,
694    /// NTLM was not the client's preferred mechanism, so both sides must
695    /// send a mechListMIC (RFC 4178 section 5).
696    pub mech_list_mic_required: bool,
697}
698
699impl NtlmServer {
700    /// Create a new server-side acceptor.
701    pub fn new(server_challenge: [u8; 8], target: NtlmTargetInfo, timestamp: u64) -> Self {
702        // Flags the server offers.
703        let server_flags = flags::NTLMSSP_NEGOTIATE_UNICODE
704            | flags::NTLMSSP_REQUEST_TARGET
705            | flags::NTLMSSP_NEGOTIATE_NTLM
706            | flags::NTLMSSP_NEGOTIATE_SIGN
707            | flags::NTLMSSP_NEGOTIATE_SEAL
708            | flags::NTLMSSP_NEGOTIATE_ALWAYS_SIGN
709            | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
710            | flags::NTLMSSP_TARGET_TYPE_SERVER
711            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
712            | flags::NTLMSSP_NEGOTIATE_VERSION
713            | flags::NTLMSSP_NEGOTIATE_128
714            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
715            | flags::NTLMSSP_NEGOTIATE_56;
716
717        Self {
718            server_challenge,
719            target_name: target.target_name,
720            nb_domain: target.nb_domain,
721            nb_computer: target.nb_computer,
722            dns_domain: target.dns_domain,
723            dns_computer: target.dns_computer,
724            timestamp,
725            server_flags,
726            negotiated_flags: server_flags,
727            negotiate_bytes: Vec::new(),
728            challenge_bytes: Vec::new(),
729            mech_list: None,
730            mech_list_mic_required: false,
731        }
732    }
733
734    /// True once the client's NEGOTIATE_MESSAGE has been processed.
735    pub fn has_negotiate(&self) -> bool {
736        !self.negotiate_bytes.is_empty()
737    }
738
739    /// Record the client's NEGOTIATE_MESSAGE bytes and intersect flags.
740    /// This must be called before `challenge()` if a MIC will be validated.
741    pub fn step1_negotiate(&mut self, blob: &[u8]) -> ProtoResult<NtlmNegotiate> {
742        let n = NtlmNegotiate::parse(blob)?;
743        // Negotiate down: only keep flags both sides set, then keep our must-have ones.
744        self.negotiated_flags = (self.server_flags & n.flags)
745            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
746            | flags::NTLMSSP_TARGET_TYPE_SERVER
747            | flags::NTLMSSP_NEGOTIATE_UNICODE;
748        self.negotiate_bytes = n.raw.clone();
749        Ok(n)
750    }
751
752    /// Build the CHALLENGE_MESSAGE blob. Stores the bytes for later MIC use.
753    pub fn challenge(&mut self) -> Vec<u8> {
754        let blob = build_challenge(&ChallengeParams {
755            server_challenge: self.server_challenge,
756            target_name: &self.target_name,
757            nb_domain_name: &self.nb_domain,
758            nb_computer_name: &self.nb_computer,
759            dns_domain_name: &self.dns_domain,
760            dns_computer_name: &self.dns_computer,
761            timestamp: self.timestamp,
762            flags: self.negotiated_flags,
763        });
764        self.challenge_bytes = blob.clone();
765        blob
766    }
767
768    /// Validate the AUTHENTICATE_MESSAGE.
769    ///
770    /// `lookup` is the application's user-database hook: given the user/domain
771    /// from the wire, return `Some(UserCreds)` if known, `None` otherwise. An
772    /// unknown user goes through the same computation as a wrong password.
773    ///
774    /// Returns `AuthOutcome::session_key` to be plugged into SMB2 KDF.
775    /// Anonymous logon (empty user, empty NT response, and an empty or
776    /// single zero byte LM response) returns a zeroed key and
777    /// `Identity::Anonymous`.
778    pub fn authenticate<F>(&self, blob: &[u8], lookup: F) -> ProtoResult<AuthOutcome>
779    where
780        F: Fn(&str, &str) -> Option<UserCreds>,
781    {
782        let auth = NtlmAuthenticate::parse(blob)?;
783
784        // ---- Anonymous (MS-NLMP 3.2.5.1.2 NullSession).
785        if auth.user.is_empty()
786            && auth.nt_response.is_empty()
787            && (auth.lm_response.is_empty() || auth.lm_response == [0])
788        {
789            return Ok(AuthOutcome {
790                identity: Identity::Anonymous,
791                session_key: [0u8; 16],
792                flags: auth.flags,
793                mic_present: false,
794            });
795        }
796
797        // ---- Locate creds. An unknown user is checked against a fixed hash
798        // so that it takes as long as a wrong password.
799        let creds = lookup(&auth.user, &auth.domain);
800        let known_user = creds.is_some();
801        let nt_hash = creds.map_or([0u8; 16], |c| c.nt_hash);
802
803        // ---- NTOWFv2 = HMAC_MD5(NT_hash, UTF-16LE(UPPER(user) || domain))
804        let response_key_nt = ntowf_v2(&nt_hash, &auth.user, &auth.domain);
805
806        // ---- NTLMv2 response layout (MS-NLMP §2.2.2.8):
807        //   16 bytes NTProofStr || NTLMv2_CLIENT_CHALLENGE blob
808        if auth.nt_response.len() < 16 {
809            return Err(ProtoError::Auth("NT response too short"));
810        }
811        let (nt_proof_supplied, client_challenge) = auth.nt_response.split_at(16);
812
813        // ---- NTProofStr = HMAC_MD5(response_key_nt, ServerChallenge || ClientChallenge)
814        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
815        mac.update(&self.server_challenge);
816        mac.update(client_challenge);
817        let nt_proof_computed = mac.finalize().into_bytes();
818
819        let proof_ok = ct_eq_16(nt_proof_supplied, &nt_proof_computed);
820        if !(proof_ok && known_user) {
821            return Err(ProtoError::Auth("NT proof mismatch"));
822        }
823
824        // ---- SessionBaseKey = HMAC_MD5(response_key_nt, NTProofStr)
825        // (MS-NLMP §3.4 - for NTLMv2, KeyExchangeKey = SessionBaseKey.)
826        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
827        mac.update(&nt_proof_computed);
828        let session_base_key_bytes = mac.finalize().into_bytes();
829        let mut key_exchange_key = [0u8; 16];
830        key_exchange_key.copy_from_slice(&session_base_key_bytes);
831
832        // ---- ExportedSessionKey. KEY_EXCH requires a 16-byte
833        // EncryptedRandomSessionKey; it is RC4-unwrapped only when signing
834        // or sealing is negotiated too.
835        let session_key = if auth.flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH != 0 {
836            let encrypted: [u8; 16] = auth
837                .encrypted_random_session_key
838                .as_slice()
839                .try_into()
840                .map_err(|_| ProtoError::Auth("encrypted session key not 16 bytes"))?;
841            if auth.flags & (flags::NTLMSSP_NEGOTIATE_SIGN | flags::NTLMSSP_NEGOTIATE_SEAL) != 0 {
842                rc4k(&key_exchange_key, &encrypted)
843            } else {
844                key_exchange_key
845            }
846        } else {
847            key_exchange_key
848        };
849
850        // ---- MIC: HMAC_MD5(ExportedSessionKey, NEGOTIATE || CHALLENGE ||
851        // AUTHENTICATE with the MIC zeroed), required when MsvAvFlags says
852        // the message carries one.
853        if let (Some(mic_off), Some(supplied)) = (auth.mic_offset, auth.mic) {
854            let mut auth_zeroed = auth.raw.clone();
855            auth_zeroed[mic_off..mic_off + 16].fill(0);
856            let mut mac = HmacMd5::new_from_slice(&session_key).expect("hmac key");
857            mac.update(&self.negotiate_bytes);
858            mac.update(&self.challenge_bytes);
859            mac.update(&auth_zeroed);
860            let computed = mac.finalize().into_bytes();
861            if !ct_eq_16(&supplied, &computed) {
862                return Err(ProtoError::Auth("MIC mismatch"));
863            }
864        }
865
866        Ok(AuthOutcome {
867            identity: Identity::User {
868                user: auth.user.clone(),
869                domain: auth.domain.clone(),
870            },
871            session_key,
872            flags: auth.flags,
873            mic_present: auth.mic.is_some(),
874        })
875    }
876}
877
878// ===========================================================================
879// Tests
880// ===========================================================================
881
882/// Hand-built NTLM AUTHENTICATE_MESSAGEs for tests.
883#[cfg(test)]
884pub(crate) mod testing {
885    use super::*;
886
887    pub(crate) const CHALLENGE: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
888
889    pub(crate) fn hmac_md5(key: &[u8], parts: &[&[u8]]) -> [u8; 16] {
890        let mut mac = HmacMd5::new_from_slice(key).unwrap();
891        for part in parts {
892            mac.update(part);
893        }
894        mac.finalize().into_bytes().into()
895    }
896
897    /// Fields of a hand-built AUTHENTICATE_MESSAGE.
898    pub(crate) struct AuthMsg<'a> {
899        pub(crate) user: &'a str,
900        pub(crate) password: &'a str,
901        pub(crate) flags: u32,
902        /// `MsvAvFlags` value to put in the NTLMv2 response.
903        pub(crate) av_flags: Option<u32>,
904        /// Leave room for a MIC at offset 72.
905        pub(crate) mic_field: bool,
906        pub(crate) lm: &'a [u8],
907        pub(crate) nt: Option<&'a [u8]>,
908        pub(crate) encrypted_key: &'a [u8],
909        /// ServerChallenge the response answers.
910        pub(crate) challenge: [u8; 8],
911    }
912
913    impl Default for AuthMsg<'_> {
914        fn default() -> Self {
915            Self {
916                user: "User",
917                password: "Password",
918                flags: flags::NTLMSSP_NEGOTIATE_UNICODE,
919                av_flags: None,
920                mic_field: false,
921                lm: &[],
922                nt: None,
923                encrypted_key: &[],
924                challenge: CHALLENGE,
925            }
926        }
927    }
928
929    /// The message and the KeyExchangeKey the server derives from it.
930    pub(crate) fn build_auth(m: &AuthMsg<'_>) -> (Vec<u8>, [u8; 16]) {
931        let key_nt = ntowf_v2(&nt_hash(m.password), m.user, "");
932        let mut blob = vec![1, 1, 0, 0, 0, 0, 0, 0];
933        blob.extend_from_slice(&[0; 8]);
934        blob.extend_from_slice(&[0xAA; 8]);
935        blob.extend_from_slice(&[0; 4]);
936        if let Some(av) = m.av_flags {
937            blob.extend_from_slice(&encode_av_pairs(&[AvPair::new(
938                AvId::Flags,
939                av.to_le_bytes().to_vec(),
940            )]));
941        } else {
942            blob.extend_from_slice(&encode_av_pairs(&[]));
943        }
944        let proof = hmac_md5(&key_nt, &[&m.challenge, &blob]);
945        let key_exchange_key = hmac_md5(&key_nt, &[&proof]);
946        let nt =
947            m.nt.map_or_else(|| [&proof[..], &blob].concat(), <[u8]>::to_vec);
948
949        let user = utf16le(m.user);
950        let fields: [&[u8]; 6] = [m.lm, &nt, &[], &user, &[], m.encrypted_key];
951        let header_len = if m.mic_field { 88u32 } else { 72 };
952        let mut msg = NTLMSSP_SIGNATURE.to_vec();
953        msg.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
954        let mut payload = Vec::new();
955        for field in fields {
956            let offset = header_len + payload.len() as u32;
957            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
958            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
959            msg.extend_from_slice(&offset.to_le_bytes());
960            payload.extend_from_slice(field);
961        }
962        msg.extend_from_slice(&m.flags.to_le_bytes());
963        msg.extend_from_slice(&[0u8; 8]);
964        if m.mic_field {
965            msg.extend_from_slice(&[0u8; 16]);
966        }
967        msg.extend_from_slice(&payload);
968        (msg, key_exchange_key)
969    }
970}
971
972#[cfg(test)]
973mod tests {
974    use super::testing::*;
975    use super::*;
976
977    #[test]
978    fn av_pair_round_trip() {
979        let pairs = vec![
980            AvPair::new(AvId::NbDomainName, utf16le("DOMAIN")),
981            AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
982            AvPair::new(
983                AvId::Timestamp,
984                0x1234_5678_9abc_def0u64.to_le_bytes().to_vec(),
985            ),
986        ];
987        let bytes = encode_av_pairs(&pairs);
988        let decoded = decode_av_pairs(&bytes).unwrap();
989        assert_eq!(decoded, pairs);
990    }
991
992    #[test]
993    fn negotiate_round_trip() {
994        // Build a minimal Type 1 by hand and parse it.
995        let mut buf = Vec::new();
996        buf.extend_from_slice(NTLMSSP_SIGNATURE);
997        buf.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
998        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
999            | flags::NTLMSSP_NEGOTIATE_NTLM
1000            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO;
1001        buf.extend_from_slice(&flags.to_le_bytes());
1002        // Domain + workstation fields: empty.
1003        buf.extend_from_slice(&[0u8; 8]);
1004        buf.extend_from_slice(&[0u8; 8]);
1005        // Version (8 bytes).
1006        buf.extend_from_slice(&[0u8; 8]);
1007
1008        let n = NtlmNegotiate::parse(&buf).unwrap();
1009        assert_eq!(n.flags, flags);
1010    }
1011
1012    #[test]
1013    fn challenge_round_trip_structure() {
1014        let blob = build_challenge(&ChallengeParams {
1015            server_challenge: [1, 2, 3, 4, 5, 6, 7, 8],
1016            target_name: "SERVER",
1017            nb_domain_name: "DOMAIN",
1018            nb_computer_name: "SERVER",
1019            dns_domain_name: "domain.local",
1020            dns_computer_name: "server.domain.local",
1021            timestamp: 0,
1022            flags: flags::NTLMSSP_NEGOTIATE_UNICODE
1023                | flags::NTLMSSP_NEGOTIATE_NTLM
1024                | flags::NTLMSSP_NEGOTIATE_TARGET_INFO,
1025        });
1026        // Signature + message type.
1027        assert_eq!(&blob[..8], NTLMSSP_SIGNATURE);
1028        assert_eq!(
1029            u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]),
1030            MSG_CHALLENGE
1031        );
1032        // Server challenge at offset 24.
1033        assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
1034        // Decode AV_PAIRs from the target-info section.
1035        let ti_off = u32::from_le_bytes([blob[44], blob[45], blob[46], blob[47]]) as usize;
1036        let ti_len = u16::from_le_bytes([blob[40], blob[41]]) as usize;
1037        let av = decode_av_pairs(&blob[ti_off..ti_off + ti_len]).unwrap();
1038        assert!(av.iter().any(|p| p.id == AvId::NbDomainName as u16));
1039        assert!(av.iter().any(|p| p.id == AvId::Timestamp as u16));
1040    }
1041
1042    /// MS-NLMP §4.2.4 known-answer test for NTLMv2:
1043    ///     User="User", Domain="Domain", Password="Password"
1044    ///     ServerChallenge = 01 23 45 67 89 ab cd ef
1045    ///     ClientChallenge AV-pair blob = 01 01 00 00 00 00 00 00
1046    ///                                    00 00 00 00 00 00 00 00
1047    ///                                    aa aa aa aa aa aa aa aa
1048    ///                                    00 00 00 00 02 00 0c 00
1049    ///                                    44 00 6f 00 6d 00 61 00
1050    ///                                    69 00 6e 00 01 00 0c 00
1051    ///                                    53 00 65 00 72 00 76 00
1052    ///                                    65 00 72 00 00 00 00 00
1053    ///                                    00 00 00 00
1054    /// Expected NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1055    #[test]
1056    fn ntlmv2_known_answer() {
1057        let nt = nt_hash("Password");
1058        // 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
1059        assert_eq!(
1060            nt,
1061            [
1062                0xa4, 0xf4, 0x9c, 0x40, 0x65, 0x10, 0xbd, 0xca, 0xb6, 0x82, 0x4e, 0xe7, 0xc3, 0x0f,
1063                0xd8, 0x52
1064            ]
1065        );
1066
1067        // NTOWFv2("Password","User","Domain")
1068        // MS-NLMP §4.2.4.1.1: 0c 86 8a 40 3b fd 7a 93 a3 00 1e f2 2e f0 2e 3f
1069        let key_nt = ntowf_v2(&nt, "User", "Domain");
1070        assert_eq!(
1071            key_nt,
1072            [
1073                0x0c, 0x86, 0x8a, 0x40, 0x3b, 0xfd, 0x7a, 0x93, 0xa3, 0x00, 0x1e, 0xf2, 0x2e, 0xf0,
1074                0x2e, 0x3f
1075            ]
1076        );
1077
1078        let server_challenge: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
1079        // NTLMv2_CLIENT_CHALLENGE blob from §4.2.4.1.3
1080        let client_challenge_blob: &[u8] = &[
1081            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // RespType, HiRespType, Reserved
1082            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TimeStamp
1083            0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, // ChallengeFromClient
1084            0x00, 0x00, 0x00, 0x00, // Reserved
1085            // AV pairs
1086            0x02, 0x00, 0x0c, 0x00, // MsvAvNbDomainName, len=12
1087            0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e,
1088            0x00, // "Domain"
1089            0x01, 0x00, 0x0c, 0x00, // MsvAvNbComputerName, len=12
1090            0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
1091            0x00, // "Server"
1092            0x00, 0x00, 0x00, 0x00, // EOL
1093            0x00, 0x00, 0x00, 0x00, // trailing 4 zero bytes (padding seen in spec)
1094        ];
1095
1096        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1097        mac.update(&server_challenge);
1098        mac.update(client_challenge_blob);
1099        let nt_proof = mac.finalize().into_bytes();
1100
1101        // MS-NLMP §4.2.4.2.2:
1102        //   NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1103        assert_eq!(
1104            nt_proof.as_slice(),
1105            [
1106                0x68, 0xcd, 0x0a, 0xb8, 0x51, 0xe5, 0x1c, 0x96, 0xaa, 0xbc, 0x92, 0x7b, 0xeb, 0xef,
1107                0x6a, 0x1c
1108            ]
1109        );
1110    }
1111
1112    #[test]
1113    fn server_round_trip_authenticates_user() {
1114        // End-to-end: build a fake AUTHENTICATE_MESSAGE with a known proof and
1115        // make sure NtlmServer accepts it.
1116        let mut srv = NtlmServer::new(
1117            [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
1118            NtlmTargetInfo::new(
1119                "SERVER",
1120                "DOMAIN",
1121                "SERVER",
1122                "domain.local",
1123                "server.domain.local",
1124            ),
1125            0,
1126        );
1127        // Skip step1_negotiate - MIC will be absent.
1128        let _challenge = srv.challenge();
1129
1130        // Compute NTProofStr the same way the client would.
1131        let nt = nt_hash("Password");
1132        let key_nt = ntowf_v2(&nt, "User", "Domain");
1133        let client_challenge_blob: Vec<u8> = vec![
1134            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1135            0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
1136            // Empty AV pair list (EOL only)
1137            0x00, 0x00, 0x00, 0x00,
1138        ];
1139        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1140        mac.update(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
1141        mac.update(&client_challenge_blob);
1142        let nt_proof = mac.finalize().into_bytes();
1143
1144        let mut nt_response = Vec::new();
1145        nt_response.extend_from_slice(&nt_proof);
1146        nt_response.extend_from_slice(&client_challenge_blob);
1147
1148        // Build AUTHENTICATE_MESSAGE.
1149        let user_u16 = utf16le("User");
1150        let dom_u16 = utf16le("Domain");
1151        let ws_u16 = utf16le("CLIENT");
1152        let lm_response: Vec<u8> = vec![0u8; 24];
1153
1154        // Layout: header is 72 bytes when no MIC is present
1155        // (signature 8 + msgtype 4 + 6x8-byte fields + flags 4 + version 8 = 72).
1156        // With MIC, it would be 88.
1157        let header_len: u32 = 72;
1158        let mut payload = Vec::new();
1159        let lm_off = header_len;
1160        payload.extend_from_slice(&lm_response);
1161        let nt_off = header_len + payload.len() as u32;
1162        payload.extend_from_slice(&nt_response);
1163        let dom_off = header_len + payload.len() as u32;
1164        payload.extend_from_slice(&dom_u16);
1165        let user_off = header_len + payload.len() as u32;
1166        payload.extend_from_slice(&user_u16);
1167        let ws_off = header_len + payload.len() as u32;
1168        payload.extend_from_slice(&ws_u16);
1169        let key_off = header_len + payload.len() as u32;
1170        // No encrypted session key.
1171
1172        let mut buf = Vec::new();
1173        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1174        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1175        // Lm
1176        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1177        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1178        buf.extend_from_slice(&lm_off.to_le_bytes());
1179        // Nt
1180        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1181        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1182        buf.extend_from_slice(&nt_off.to_le_bytes());
1183        // Domain
1184        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1185        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1186        buf.extend_from_slice(&dom_off.to_le_bytes());
1187        // User
1188        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1189        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1190        buf.extend_from_slice(&user_off.to_le_bytes());
1191        // Workstation
1192        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1193        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1194        buf.extend_from_slice(&ws_off.to_le_bytes());
1195        // EncryptedRandomSessionKey
1196        buf.extend_from_slice(&0u16.to_le_bytes());
1197        buf.extend_from_slice(&0u16.to_le_bytes());
1198        buf.extend_from_slice(&key_off.to_le_bytes());
1199        // Flags
1200        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
1201        // Version (8 bytes)
1202        buf.extend_from_slice(&[0u8; 8]);
1203        // No MIC: header is 72 bytes.
1204        assert_eq!(buf.len() as u32, header_len);
1205        buf.extend_from_slice(&payload);
1206
1207        let creds = UserCreds::from_password("Password");
1208        let outcome = srv
1209            .authenticate(&buf, |u, d| {
1210                if u == "User" && d == "Domain" {
1211                    Some(creds.clone())
1212                } else {
1213                    None
1214                }
1215            })
1216            .expect("auth should succeed");
1217
1218        assert_eq!(
1219            outcome.identity,
1220            Identity::User {
1221                user: "User".to_string(),
1222                domain: "Domain".to_string()
1223            }
1224        );
1225
1226        // Wrong password fails.
1227        let bad = UserCreds::from_password("WrongPassword");
1228        let err = srv
1229            .authenticate(&buf, |_u, _d| Some(bad.clone()))
1230            .unwrap_err();
1231        assert!(matches!(err, ProtoError::Auth(_)));
1232    }
1233
1234    #[test]
1235    fn debug_output_hides_keys() {
1236        let creds = UserCreds {
1237            nt_hash: [0xAB; 16],
1238        };
1239        assert_eq!(format!("{creds:?}"), "UserCreds { .. }");
1240        let outcome = AuthOutcome {
1241            identity: Identity::Anonymous,
1242            session_key: [0xCD; 16],
1243            flags: 0,
1244            mic_present: false,
1245        };
1246        let shown = format!("{outcome:?}");
1247        assert_eq!(shown, "AuthOutcome { identity: Anonymous, .. }");
1248    }
1249
1250    #[test]
1251    fn anonymous_logon() {
1252        let mut srv = NtlmServer::new(
1253            [0u8; 8],
1254            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1255            0,
1256        );
1257        let _ = srv.challenge();
1258
1259        // Build an AUTHENTICATE_MESSAGE with empty user + empty NT response.
1260        let header_len: u32 = 72;
1261        let mut buf = Vec::new();
1262        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1263        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1264        for _ in 0..6 {
1265            // 6 empty fields (Lm, Nt, Domain, User, Workstation, Key)
1266            buf.extend_from_slice(&0u16.to_le_bytes());
1267            buf.extend_from_slice(&0u16.to_le_bytes());
1268            buf.extend_from_slice(&header_len.to_le_bytes());
1269        }
1270        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_ANONYMOUS.to_le_bytes());
1271        buf.extend_from_slice(&[0u8; 8]); // version
1272
1273        let outcome = srv
1274            .authenticate(&buf, |_u, _d| None)
1275            .expect("anonymous should succeed");
1276        assert_eq!(outcome.identity, Identity::Anonymous);
1277        assert_eq!(outcome.session_key, [0u8; 16]);
1278    }
1279
1280    fn server() -> NtlmServer {
1281        let mut srv = NtlmServer::new(
1282            CHALLENGE,
1283            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1284            0,
1285        );
1286        let mut negotiate = NTLMSSP_SIGNATURE.to_vec();
1287        negotiate.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
1288        negotiate.extend_from_slice(&0xE288_8235u32.to_le_bytes());
1289        negotiate.extend_from_slice(&[0u8; 16]);
1290        srv.step1_negotiate(&negotiate).unwrap();
1291        srv.challenge();
1292        srv
1293    }
1294
1295    fn sign_mic(srv: &NtlmServer, msg: &mut [u8], key: &[u8; 16]) {
1296        let mic = hmac_md5(key, &[&srv.negotiate_bytes, &srv.challenge_bytes, msg]);
1297        msg[72..88].copy_from_slice(&mic);
1298    }
1299
1300    fn user_creds(u: &str, _d: &str) -> Option<UserCreds> {
1301        (u == "User").then(|| UserCreds::from_password("Password"))
1302    }
1303
1304    #[test]
1305    fn mic_is_checked_when_msv_av_flags_announces_it() {
1306        let srv = server();
1307        let m = AuthMsg {
1308            av_flags: Some(MSV_AV_FLAG_MIC),
1309            mic_field: true,
1310            ..AuthMsg::default()
1311        };
1312        let (mut msg, key) = build_auth(&m);
1313        sign_mic(&srv, &mut msg, &key);
1314        let outcome = srv.authenticate(&msg, user_creds).expect("valid MIC");
1315        assert!(outcome.mic_present);
1316
1317        msg[80] ^= 1;
1318        assert!(srv.authenticate(&msg, user_creds).is_err(), "bad MIC");
1319
1320        // MsvAvFlags announces a MIC, but the header has no room for one.
1321        let m = AuthMsg {
1322            av_flags: Some(MSV_AV_FLAG_MIC),
1323            ..AuthMsg::default()
1324        };
1325        let (msg, _) = build_auth(&m);
1326        assert!(srv.authenticate(&msg, user_creds).is_err(), "stripped MIC");
1327    }
1328
1329    #[test]
1330    fn padding_without_msv_av_flags_is_not_a_mic() {
1331        let srv = server();
1332        let m = AuthMsg {
1333            mic_field: true,
1334            ..AuthMsg::default()
1335        };
1336        let (msg, _) = build_auth(&m);
1337        let outcome = srv.authenticate(&msg, user_creds).expect("no MIC");
1338        assert!(!outcome.mic_present);
1339    }
1340
1341    #[test]
1342    fn key_exch_needs_a_16_byte_session_key() {
1343        let srv = server();
1344        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
1345            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
1346            | flags::NTLMSSP_NEGOTIATE_SIGN;
1347        let m = AuthMsg {
1348            flags,
1349            ..AuthMsg::default()
1350        };
1351        let (msg, _) = build_auth(&m);
1352        assert!(srv.authenticate(&msg, user_creds).is_err(), "empty key");
1353
1354        let random = [0x55u8; 16];
1355        let (_, kxkey) = build_auth(&m);
1356        let encrypted = rc4k(&kxkey, &random);
1357        let m = AuthMsg {
1358            flags,
1359            encrypted_key: &encrypted,
1360            ..AuthMsg::default()
1361        };
1362        let (msg, _) = build_auth(&m);
1363        let outcome = srv.authenticate(&msg, user_creds).expect("16-byte key");
1364        assert_eq!(outcome.session_key, random);
1365
1366        // Without SIGN or SEAL the key is checked but not unwrapped.
1367        let m = AuthMsg {
1368            flags: flags::NTLMSSP_NEGOTIATE_UNICODE | flags::NTLMSSP_NEGOTIATE_KEY_EXCH,
1369            encrypted_key: &encrypted,
1370            ..AuthMsg::default()
1371        };
1372        let (msg, kxkey) = build_auth(&m);
1373        let outcome = srv.authenticate(&msg, user_creds).expect("no signing");
1374        assert_eq!(outcome.session_key, kxkey);
1375    }
1376
1377    #[test]
1378    fn anonymous_needs_an_empty_or_zero_lm_response() {
1379        let srv = server();
1380        for lm in [&[][..], &[0u8][..]] {
1381            let m = AuthMsg {
1382                user: "",
1383                nt: Some(&[]),
1384                lm,
1385                ..AuthMsg::default()
1386            };
1387            let (msg, _) = build_auth(&m);
1388            let outcome = srv.authenticate(&msg, |_, _| None).expect("anonymous");
1389            assert_eq!(outcome.identity, Identity::Anonymous);
1390        }
1391        let m = AuthMsg {
1392            user: "",
1393            nt: Some(&[]),
1394            lm: &[0x11; 24],
1395            ..AuthMsg::default()
1396        };
1397        let (msg, _) = build_auth(&m);
1398        assert!(srv.authenticate(&msg, |_, _| None).is_err());
1399    }
1400
1401    #[test]
1402    fn unknown_user_fails() {
1403        let srv = server();
1404        let m = AuthMsg {
1405            user: "Nobody",
1406            ..AuthMsg::default()
1407        };
1408        let (msg, _) = build_auth(&m);
1409        assert!(srv.authenticate(&msg, user_creds).is_err());
1410        // Even when the response was computed against the fixed hash.
1411        let m = AuthMsg {
1412            user: "Nobody",
1413            password: "",
1414            ..AuthMsg::default()
1415        };
1416        let (mut msg, _) = build_auth(&m);
1417        let key_nt = ntowf_v2(&[0u8; 16], "Nobody", "");
1418        let nt_off = u32::from_le_bytes(msg[24..28].try_into().unwrap()) as usize;
1419        let nt_len = u16::from_le_bytes(msg[20..22].try_into().unwrap()) as usize;
1420        let client_blob = msg[nt_off + 16..nt_off + nt_len].to_vec();
1421        let proof = hmac_md5(&key_nt, &[&CHALLENGE, &client_blob]);
1422        msg[nt_off..nt_off + 16].copy_from_slice(&proof);
1423        assert!(srv.authenticate(&msg, user_creds).is_err());
1424    }
1425
1426    /// MS-NLMP 4.2.4.2.3: RC4(SessionBaseKey, RandomSessionKey).
1427    #[test]
1428    fn encrypted_session_key_known_answer() {
1429        let session_base_key = [
1430            0x8d, 0xe4, 0x0c, 0xca, 0xdb, 0xc1, 0x4a, 0x82, 0xf1, 0x5c, 0xb0, 0xad, 0x0d, 0xe9,
1431            0x5c, 0xa3,
1432        ];
1433        let encrypted = [
1434            0xc5, 0xda, 0xd2, 0x54, 0x4f, 0xc9, 0x79, 0x90, 0x94, 0xce, 0x1c, 0xe9, 0x0b, 0xc9,
1435            0xd0, 0x3e,
1436        ];
1437        assert_eq!(rc4k(&session_base_key, &encrypted), [0x55; 16]);
1438    }
1439
1440    /// MS-NLMP 4.2.4.4: client sealing and signing keys, and the signature
1441    /// of "Plaintext" sealed and signed at sequence number 0.
1442    #[test]
1443    fn gss_wrap_ex_known_answer() {
1444        let flags = 0xE28A_8233;
1445        let mut mac = NtlmMac::new(flags, &[0x55; 16], Direction::ClientToServer).unwrap();
1446        assert_eq!(
1447            mac.signing_key,
1448            [
1449                0x47, 0x88, 0xdc, 0x86, 0x1b, 0x47, 0x82, 0xf3, 0x5d, 0x43, 0xfd, 0x98, 0xfe, 0x1a,
1450                0x2d, 0x39
1451            ]
1452        );
1453        let plaintext = utf16le("Plaintext");
1454        let mut sealed = plaintext.clone();
1455        mac.handle.as_mut().unwrap().apply_keystream(&mut sealed);
1456        assert_eq!(
1457            sealed,
1458            [
1459                0x54, 0xe5, 0x01, 0x65, 0xbf, 0x19, 0x36, 0xdc, 0x99, 0x60, 0x20, 0xc1, 0x81, 0x1b,
1460                0x0f, 0x06, 0xfb, 0x5f
1461            ]
1462        );
1463        assert_eq!(
1464            mac.mac(&plaintext),
1465            [
1466                0x01, 0x00, 0x00, 0x00, 0x7f, 0xb3, 0x8e, 0xc5, 0xc5, 0x5d, 0x49, 0x76, 0x00, 0x00,
1467                0x00, 0x00
1468            ]
1469        );
1470        assert_eq!(mac.seq, 1);
1471    }
1472
1473    #[test]
1474    fn mac_needs_extended_session_security_and_signing() {
1475        let key = [0x55; 16];
1476        let ess = flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY;
1477        let sign = flags::NTLMSSP_NEGOTIATE_SIGN;
1478        assert!(NtlmMac::new(sign, &key, Direction::ServerToClient).is_none());
1479        assert!(NtlmMac::new(ess, &key, Direction::ServerToClient).is_none());
1480        let mut mac = NtlmMac::new(ess | sign, &key, Direction::ServerToClient).unwrap();
1481        assert!(mac.handle.is_none());
1482        let sig = mac.mac(b"message");
1483        let expected = hmac_md5(
1484            &md5_concat(
1485                &key,
1486                b"session key to server-to-client signing key magic constant\0",
1487            ),
1488            &[&0u32.to_le_bytes(), b"message"],
1489        );
1490        assert_eq!(sig[4..12], expected[..8]);
1491    }
1492}