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_ALWAYS_SIGN
708            | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
709            | flags::NTLMSSP_TARGET_TYPE_SERVER
710            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
711            | flags::NTLMSSP_NEGOTIATE_VERSION
712            | flags::NTLMSSP_NEGOTIATE_128
713            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
714            | flags::NTLMSSP_NEGOTIATE_56;
715
716        Self {
717            server_challenge,
718            target_name: target.target_name,
719            nb_domain: target.nb_domain,
720            nb_computer: target.nb_computer,
721            dns_domain: target.dns_domain,
722            dns_computer: target.dns_computer,
723            timestamp,
724            server_flags,
725            negotiated_flags: server_flags,
726            negotiate_bytes: Vec::new(),
727            challenge_bytes: Vec::new(),
728            mech_list: None,
729            mech_list_mic_required: false,
730        }
731    }
732
733    /// True once the client's NEGOTIATE_MESSAGE has been processed.
734    pub fn has_negotiate(&self) -> bool {
735        !self.negotiate_bytes.is_empty()
736    }
737
738    /// Record the client's NEGOTIATE_MESSAGE bytes and intersect flags.
739    /// This must be called before `challenge()` if a MIC will be validated.
740    pub fn step1_negotiate(&mut self, blob: &[u8]) -> ProtoResult<NtlmNegotiate> {
741        let n = NtlmNegotiate::parse(blob)?;
742        // Negotiate down: only keep flags both sides set, then keep our must-have ones.
743        self.negotiated_flags = (self.server_flags & n.flags)
744            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
745            | flags::NTLMSSP_TARGET_TYPE_SERVER
746            | flags::NTLMSSP_NEGOTIATE_UNICODE;
747        self.negotiate_bytes = n.raw.clone();
748        Ok(n)
749    }
750
751    /// Build the CHALLENGE_MESSAGE blob. Stores the bytes for later MIC use.
752    pub fn challenge(&mut self) -> Vec<u8> {
753        let blob = build_challenge(&ChallengeParams {
754            server_challenge: self.server_challenge,
755            target_name: &self.target_name,
756            nb_domain_name: &self.nb_domain,
757            nb_computer_name: &self.nb_computer,
758            dns_domain_name: &self.dns_domain,
759            dns_computer_name: &self.dns_computer,
760            timestamp: self.timestamp,
761            flags: self.negotiated_flags,
762        });
763        self.challenge_bytes = blob.clone();
764        blob
765    }
766
767    /// Validate the AUTHENTICATE_MESSAGE.
768    ///
769    /// `lookup` is the application's user-database hook: given the user/domain
770    /// from the wire, return `Some(UserCreds)` if known, `None` otherwise. An
771    /// unknown user goes through the same computation as a wrong password.
772    ///
773    /// Returns `AuthOutcome::session_key` to be plugged into SMB2 KDF.
774    /// Anonymous logon (empty user, empty NT response, and an empty or
775    /// single zero byte LM response) returns a zeroed key and
776    /// `Identity::Anonymous`.
777    pub fn authenticate<F>(&self, blob: &[u8], lookup: F) -> ProtoResult<AuthOutcome>
778    where
779        F: Fn(&str, &str) -> Option<UserCreds>,
780    {
781        let auth = NtlmAuthenticate::parse(blob)?;
782
783        // ---- Anonymous (MS-NLMP 3.2.5.1.2 NullSession).
784        if auth.user.is_empty()
785            && auth.nt_response.is_empty()
786            && (auth.lm_response.is_empty() || auth.lm_response == [0])
787        {
788            return Ok(AuthOutcome {
789                identity: Identity::Anonymous,
790                session_key: [0u8; 16],
791                flags: auth.flags,
792                mic_present: false,
793            });
794        }
795
796        // ---- Locate creds. An unknown user is checked against a fixed hash
797        // so that it takes as long as a wrong password.
798        let creds = lookup(&auth.user, &auth.domain);
799        let known_user = creds.is_some();
800        let nt_hash = creds.map_or([0u8; 16], |c| c.nt_hash);
801
802        // ---- NTOWFv2 = HMAC_MD5(NT_hash, UTF-16LE(UPPER(user) || domain))
803        let response_key_nt = ntowf_v2(&nt_hash, &auth.user, &auth.domain);
804
805        // ---- NTLMv2 response layout (MS-NLMP §2.2.2.8):
806        //   16 bytes NTProofStr || NTLMv2_CLIENT_CHALLENGE blob
807        if auth.nt_response.len() < 16 {
808            return Err(ProtoError::Auth("NT response too short"));
809        }
810        let (nt_proof_supplied, client_challenge) = auth.nt_response.split_at(16);
811
812        // ---- NTProofStr = HMAC_MD5(response_key_nt, ServerChallenge || ClientChallenge)
813        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
814        mac.update(&self.server_challenge);
815        mac.update(client_challenge);
816        let nt_proof_computed = mac.finalize().into_bytes();
817
818        let proof_ok = ct_eq_16(nt_proof_supplied, &nt_proof_computed);
819        if !(proof_ok && known_user) {
820            return Err(ProtoError::Auth("NT proof mismatch"));
821        }
822
823        // ---- SessionBaseKey = HMAC_MD5(response_key_nt, NTProofStr)
824        // (MS-NLMP §3.4 - for NTLMv2, KeyExchangeKey = SessionBaseKey.)
825        let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
826        mac.update(&nt_proof_computed);
827        let session_base_key_bytes = mac.finalize().into_bytes();
828        let mut key_exchange_key = [0u8; 16];
829        key_exchange_key.copy_from_slice(&session_base_key_bytes);
830
831        // ---- ExportedSessionKey. KEY_EXCH requires a 16-byte
832        // EncryptedRandomSessionKey; it is RC4-unwrapped only when signing
833        // or sealing is negotiated too.
834        let session_key = if auth.flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH != 0 {
835            let encrypted: [u8; 16] = auth
836                .encrypted_random_session_key
837                .as_slice()
838                .try_into()
839                .map_err(|_| ProtoError::Auth("encrypted session key not 16 bytes"))?;
840            if auth.flags & (flags::NTLMSSP_NEGOTIATE_SIGN | flags::NTLMSSP_NEGOTIATE_SEAL) != 0 {
841                rc4k(&key_exchange_key, &encrypted)
842            } else {
843                key_exchange_key
844            }
845        } else {
846            key_exchange_key
847        };
848
849        // ---- MIC: HMAC_MD5(ExportedSessionKey, NEGOTIATE || CHALLENGE ||
850        // AUTHENTICATE with the MIC zeroed), required when MsvAvFlags says
851        // the message carries one.
852        if let (Some(mic_off), Some(supplied)) = (auth.mic_offset, auth.mic) {
853            let mut auth_zeroed = auth.raw.clone();
854            auth_zeroed[mic_off..mic_off + 16].fill(0);
855            let mut mac = HmacMd5::new_from_slice(&session_key).expect("hmac key");
856            mac.update(&self.negotiate_bytes);
857            mac.update(&self.challenge_bytes);
858            mac.update(&auth_zeroed);
859            let computed = mac.finalize().into_bytes();
860            if !ct_eq_16(&supplied, &computed) {
861                return Err(ProtoError::Auth("MIC mismatch"));
862            }
863        }
864
865        Ok(AuthOutcome {
866            identity: Identity::User {
867                user: auth.user.clone(),
868                domain: auth.domain.clone(),
869            },
870            session_key,
871            flags: auth.flags,
872            mic_present: auth.mic.is_some(),
873        })
874    }
875}
876
877// ===========================================================================
878// Tests
879// ===========================================================================
880
881/// Hand-built NTLM AUTHENTICATE_MESSAGEs for tests.
882#[cfg(test)]
883pub(crate) mod testing {
884    use super::*;
885
886    pub(crate) const CHALLENGE: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
887
888    pub(crate) fn hmac_md5(key: &[u8], parts: &[&[u8]]) -> [u8; 16] {
889        let mut mac = HmacMd5::new_from_slice(key).unwrap();
890        for part in parts {
891            mac.update(part);
892        }
893        mac.finalize().into_bytes().into()
894    }
895
896    /// Fields of a hand-built AUTHENTICATE_MESSAGE.
897    pub(crate) struct AuthMsg<'a> {
898        pub(crate) user: &'a str,
899        pub(crate) password: &'a str,
900        pub(crate) flags: u32,
901        /// `MsvAvFlags` value to put in the NTLMv2 response.
902        pub(crate) av_flags: Option<u32>,
903        /// Leave room for a MIC at offset 72.
904        pub(crate) mic_field: bool,
905        pub(crate) lm: &'a [u8],
906        pub(crate) nt: Option<&'a [u8]>,
907        pub(crate) encrypted_key: &'a [u8],
908        /// ServerChallenge the response answers.
909        pub(crate) challenge: [u8; 8],
910    }
911
912    impl Default for AuthMsg<'_> {
913        fn default() -> Self {
914            Self {
915                user: "User",
916                password: "Password",
917                flags: flags::NTLMSSP_NEGOTIATE_UNICODE,
918                av_flags: None,
919                mic_field: false,
920                lm: &[],
921                nt: None,
922                encrypted_key: &[],
923                challenge: CHALLENGE,
924            }
925        }
926    }
927
928    /// The message and the KeyExchangeKey the server derives from it.
929    pub(crate) fn build_auth(m: &AuthMsg<'_>) -> (Vec<u8>, [u8; 16]) {
930        let key_nt = ntowf_v2(&nt_hash(m.password), m.user, "");
931        let mut blob = vec![1, 1, 0, 0, 0, 0, 0, 0];
932        blob.extend_from_slice(&[0; 8]);
933        blob.extend_from_slice(&[0xAA; 8]);
934        blob.extend_from_slice(&[0; 4]);
935        if let Some(av) = m.av_flags {
936            blob.extend_from_slice(&encode_av_pairs(&[AvPair::new(
937                AvId::Flags,
938                av.to_le_bytes().to_vec(),
939            )]));
940        } else {
941            blob.extend_from_slice(&encode_av_pairs(&[]));
942        }
943        let proof = hmac_md5(&key_nt, &[&m.challenge, &blob]);
944        let key_exchange_key = hmac_md5(&key_nt, &[&proof]);
945        let nt =
946            m.nt.map_or_else(|| [&proof[..], &blob].concat(), <[u8]>::to_vec);
947
948        let user = utf16le(m.user);
949        let fields: [&[u8]; 6] = [m.lm, &nt, &[], &user, &[], m.encrypted_key];
950        let header_len = if m.mic_field { 88u32 } else { 72 };
951        let mut msg = NTLMSSP_SIGNATURE.to_vec();
952        msg.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
953        let mut payload = Vec::new();
954        for field in fields {
955            let offset = header_len + payload.len() as u32;
956            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
957            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
958            msg.extend_from_slice(&offset.to_le_bytes());
959            payload.extend_from_slice(field);
960        }
961        msg.extend_from_slice(&m.flags.to_le_bytes());
962        msg.extend_from_slice(&[0u8; 8]);
963        if m.mic_field {
964            msg.extend_from_slice(&[0u8; 16]);
965        }
966        msg.extend_from_slice(&payload);
967        (msg, key_exchange_key)
968    }
969}
970
971#[cfg(test)]
972mod tests {
973    use super::testing::*;
974    use super::*;
975
976    #[test]
977    fn av_pair_round_trip() {
978        let pairs = vec![
979            AvPair::new(AvId::NbDomainName, utf16le("DOMAIN")),
980            AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
981            AvPair::new(
982                AvId::Timestamp,
983                0x1234_5678_9abc_def0u64.to_le_bytes().to_vec(),
984            ),
985        ];
986        let bytes = encode_av_pairs(&pairs);
987        let decoded = decode_av_pairs(&bytes).unwrap();
988        assert_eq!(decoded, pairs);
989    }
990
991    #[test]
992    fn negotiate_round_trip() {
993        // Build a minimal Type 1 by hand and parse it.
994        let mut buf = Vec::new();
995        buf.extend_from_slice(NTLMSSP_SIGNATURE);
996        buf.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
997        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
998            | flags::NTLMSSP_NEGOTIATE_NTLM
999            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO;
1000        buf.extend_from_slice(&flags.to_le_bytes());
1001        // Domain + workstation fields: empty.
1002        buf.extend_from_slice(&[0u8; 8]);
1003        buf.extend_from_slice(&[0u8; 8]);
1004        // Version (8 bytes).
1005        buf.extend_from_slice(&[0u8; 8]);
1006
1007        let n = NtlmNegotiate::parse(&buf).unwrap();
1008        assert_eq!(n.flags, flags);
1009    }
1010
1011    #[test]
1012    fn challenge_round_trip_structure() {
1013        let blob = build_challenge(&ChallengeParams {
1014            server_challenge: [1, 2, 3, 4, 5, 6, 7, 8],
1015            target_name: "SERVER",
1016            nb_domain_name: "DOMAIN",
1017            nb_computer_name: "SERVER",
1018            dns_domain_name: "domain.local",
1019            dns_computer_name: "server.domain.local",
1020            timestamp: 0,
1021            flags: flags::NTLMSSP_NEGOTIATE_UNICODE
1022                | flags::NTLMSSP_NEGOTIATE_NTLM
1023                | flags::NTLMSSP_NEGOTIATE_TARGET_INFO,
1024        });
1025        // Signature + message type.
1026        assert_eq!(&blob[..8], NTLMSSP_SIGNATURE);
1027        assert_eq!(
1028            u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]),
1029            MSG_CHALLENGE
1030        );
1031        // Server challenge at offset 24.
1032        assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
1033        // Decode AV_PAIRs from the target-info section.
1034        let ti_off = u32::from_le_bytes([blob[44], blob[45], blob[46], blob[47]]) as usize;
1035        let ti_len = u16::from_le_bytes([blob[40], blob[41]]) as usize;
1036        let av = decode_av_pairs(&blob[ti_off..ti_off + ti_len]).unwrap();
1037        assert!(av.iter().any(|p| p.id == AvId::NbDomainName as u16));
1038        assert!(av.iter().any(|p| p.id == AvId::Timestamp as u16));
1039    }
1040
1041    /// MS-NLMP §4.2.4 known-answer test for NTLMv2:
1042    ///     User="User", Domain="Domain", Password="Password"
1043    ///     ServerChallenge = 01 23 45 67 89 ab cd ef
1044    ///     ClientChallenge AV-pair blob = 01 01 00 00 00 00 00 00
1045    ///                                    00 00 00 00 00 00 00 00
1046    ///                                    aa aa aa aa aa aa aa aa
1047    ///                                    00 00 00 00 02 00 0c 00
1048    ///                                    44 00 6f 00 6d 00 61 00
1049    ///                                    69 00 6e 00 01 00 0c 00
1050    ///                                    53 00 65 00 72 00 76 00
1051    ///                                    65 00 72 00 00 00 00 00
1052    ///                                    00 00 00 00
1053    /// Expected NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1054    #[test]
1055    fn ntlmv2_known_answer() {
1056        let nt = nt_hash("Password");
1057        // 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
1058        assert_eq!(
1059            nt,
1060            [
1061                0xa4, 0xf4, 0x9c, 0x40, 0x65, 0x10, 0xbd, 0xca, 0xb6, 0x82, 0x4e, 0xe7, 0xc3, 0x0f,
1062                0xd8, 0x52
1063            ]
1064        );
1065
1066        // NTOWFv2("Password","User","Domain")
1067        // MS-NLMP §4.2.4.1.1: 0c 86 8a 40 3b fd 7a 93 a3 00 1e f2 2e f0 2e 3f
1068        let key_nt = ntowf_v2(&nt, "User", "Domain");
1069        assert_eq!(
1070            key_nt,
1071            [
1072                0x0c, 0x86, 0x8a, 0x40, 0x3b, 0xfd, 0x7a, 0x93, 0xa3, 0x00, 0x1e, 0xf2, 0x2e, 0xf0,
1073                0x2e, 0x3f
1074            ]
1075        );
1076
1077        let server_challenge: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
1078        // NTLMv2_CLIENT_CHALLENGE blob from §4.2.4.1.3
1079        let client_challenge_blob: &[u8] = &[
1080            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // RespType, HiRespType, Reserved
1081            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TimeStamp
1082            0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, // ChallengeFromClient
1083            0x00, 0x00, 0x00, 0x00, // Reserved
1084            // AV pairs
1085            0x02, 0x00, 0x0c, 0x00, // MsvAvNbDomainName, len=12
1086            0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e,
1087            0x00, // "Domain"
1088            0x01, 0x00, 0x0c, 0x00, // MsvAvNbComputerName, len=12
1089            0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
1090            0x00, // "Server"
1091            0x00, 0x00, 0x00, 0x00, // EOL
1092            0x00, 0x00, 0x00, 0x00, // trailing 4 zero bytes (padding seen in spec)
1093        ];
1094
1095        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1096        mac.update(&server_challenge);
1097        mac.update(client_challenge_blob);
1098        let nt_proof = mac.finalize().into_bytes();
1099
1100        // MS-NLMP §4.2.4.2.2:
1101        //   NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1102        assert_eq!(
1103            nt_proof.as_slice(),
1104            [
1105                0x68, 0xcd, 0x0a, 0xb8, 0x51, 0xe5, 0x1c, 0x96, 0xaa, 0xbc, 0x92, 0x7b, 0xeb, 0xef,
1106                0x6a, 0x1c
1107            ]
1108        );
1109    }
1110
1111    #[test]
1112    fn server_round_trip_authenticates_user() {
1113        // End-to-end: build a fake AUTHENTICATE_MESSAGE with a known proof and
1114        // make sure NtlmServer accepts it.
1115        let mut srv = NtlmServer::new(
1116            [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
1117            NtlmTargetInfo::new(
1118                "SERVER",
1119                "DOMAIN",
1120                "SERVER",
1121                "domain.local",
1122                "server.domain.local",
1123            ),
1124            0,
1125        );
1126        // Skip step1_negotiate - MIC will be absent.
1127        let _challenge = srv.challenge();
1128
1129        // Compute NTProofStr the same way the client would.
1130        let nt = nt_hash("Password");
1131        let key_nt = ntowf_v2(&nt, "User", "Domain");
1132        let client_challenge_blob: Vec<u8> = vec![
1133            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1134            0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
1135            // Empty AV pair list (EOL only)
1136            0x00, 0x00, 0x00, 0x00,
1137        ];
1138        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1139        mac.update(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
1140        mac.update(&client_challenge_blob);
1141        let nt_proof = mac.finalize().into_bytes();
1142
1143        let mut nt_response = Vec::new();
1144        nt_response.extend_from_slice(&nt_proof);
1145        nt_response.extend_from_slice(&client_challenge_blob);
1146
1147        // Build AUTHENTICATE_MESSAGE.
1148        let user_u16 = utf16le("User");
1149        let dom_u16 = utf16le("Domain");
1150        let ws_u16 = utf16le("CLIENT");
1151        let lm_response: Vec<u8> = vec![0u8; 24];
1152
1153        // Layout: header is 72 bytes when no MIC is present
1154        // (signature 8 + msgtype 4 + 6x8-byte fields + flags 4 + version 8 = 72).
1155        // With MIC, it would be 88.
1156        let header_len: u32 = 72;
1157        let mut payload = Vec::new();
1158        let lm_off = header_len;
1159        payload.extend_from_slice(&lm_response);
1160        let nt_off = header_len + payload.len() as u32;
1161        payload.extend_from_slice(&nt_response);
1162        let dom_off = header_len + payload.len() as u32;
1163        payload.extend_from_slice(&dom_u16);
1164        let user_off = header_len + payload.len() as u32;
1165        payload.extend_from_slice(&user_u16);
1166        let ws_off = header_len + payload.len() as u32;
1167        payload.extend_from_slice(&ws_u16);
1168        let key_off = header_len + payload.len() as u32;
1169        // No encrypted session key.
1170
1171        let mut buf = Vec::new();
1172        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1173        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1174        // Lm
1175        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1176        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1177        buf.extend_from_slice(&lm_off.to_le_bytes());
1178        // Nt
1179        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1180        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1181        buf.extend_from_slice(&nt_off.to_le_bytes());
1182        // Domain
1183        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1184        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1185        buf.extend_from_slice(&dom_off.to_le_bytes());
1186        // User
1187        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1188        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1189        buf.extend_from_slice(&user_off.to_le_bytes());
1190        // Workstation
1191        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1192        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1193        buf.extend_from_slice(&ws_off.to_le_bytes());
1194        // EncryptedRandomSessionKey
1195        buf.extend_from_slice(&0u16.to_le_bytes());
1196        buf.extend_from_slice(&0u16.to_le_bytes());
1197        buf.extend_from_slice(&key_off.to_le_bytes());
1198        // Flags
1199        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
1200        // Version (8 bytes)
1201        buf.extend_from_slice(&[0u8; 8]);
1202        // No MIC: header is 72 bytes.
1203        assert_eq!(buf.len() as u32, header_len);
1204        buf.extend_from_slice(&payload);
1205
1206        let creds = UserCreds::from_password("Password");
1207        let outcome = srv
1208            .authenticate(&buf, |u, d| {
1209                if u == "User" && d == "Domain" {
1210                    Some(creds.clone())
1211                } else {
1212                    None
1213                }
1214            })
1215            .expect("auth should succeed");
1216
1217        assert_eq!(
1218            outcome.identity,
1219            Identity::User {
1220                user: "User".to_string(),
1221                domain: "Domain".to_string()
1222            }
1223        );
1224
1225        // Wrong password fails.
1226        let bad = UserCreds::from_password("WrongPassword");
1227        let err = srv
1228            .authenticate(&buf, |_u, _d| Some(bad.clone()))
1229            .unwrap_err();
1230        assert!(matches!(err, ProtoError::Auth(_)));
1231    }
1232
1233    #[test]
1234    fn debug_output_hides_keys() {
1235        let creds = UserCreds {
1236            nt_hash: [0xAB; 16],
1237        };
1238        assert_eq!(format!("{creds:?}"), "UserCreds { .. }");
1239        let outcome = AuthOutcome {
1240            identity: Identity::Anonymous,
1241            session_key: [0xCD; 16],
1242            flags: 0,
1243            mic_present: false,
1244        };
1245        let shown = format!("{outcome:?}");
1246        assert_eq!(shown, "AuthOutcome { identity: Anonymous, .. }");
1247    }
1248
1249    #[test]
1250    fn anonymous_logon() {
1251        let mut srv = NtlmServer::new(
1252            [0u8; 8],
1253            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1254            0,
1255        );
1256        let _ = srv.challenge();
1257
1258        // Build an AUTHENTICATE_MESSAGE with empty user + empty NT response.
1259        let header_len: u32 = 72;
1260        let mut buf = Vec::new();
1261        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1262        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1263        for _ in 0..6 {
1264            // 6 empty fields (Lm, Nt, Domain, User, Workstation, Key)
1265            buf.extend_from_slice(&0u16.to_le_bytes());
1266            buf.extend_from_slice(&0u16.to_le_bytes());
1267            buf.extend_from_slice(&header_len.to_le_bytes());
1268        }
1269        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_ANONYMOUS.to_le_bytes());
1270        buf.extend_from_slice(&[0u8; 8]); // version
1271
1272        let outcome = srv
1273            .authenticate(&buf, |_u, _d| None)
1274            .expect("anonymous should succeed");
1275        assert_eq!(outcome.identity, Identity::Anonymous);
1276        assert_eq!(outcome.session_key, [0u8; 16]);
1277    }
1278
1279    fn server() -> NtlmServer {
1280        let mut srv = NtlmServer::new(
1281            CHALLENGE,
1282            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1283            0,
1284        );
1285        let mut negotiate = NTLMSSP_SIGNATURE.to_vec();
1286        negotiate.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
1287        negotiate.extend_from_slice(&0xE288_8235u32.to_le_bytes());
1288        negotiate.extend_from_slice(&[0u8; 16]);
1289        srv.step1_negotiate(&negotiate).unwrap();
1290        srv.challenge();
1291        srv
1292    }
1293
1294    fn sign_mic(srv: &NtlmServer, msg: &mut [u8], key: &[u8; 16]) {
1295        let mic = hmac_md5(key, &[&srv.negotiate_bytes, &srv.challenge_bytes, msg]);
1296        msg[72..88].copy_from_slice(&mic);
1297    }
1298
1299    fn user_creds(u: &str, _d: &str) -> Option<UserCreds> {
1300        (u == "User").then(|| UserCreds::from_password("Password"))
1301    }
1302
1303    #[test]
1304    fn mic_is_checked_when_msv_av_flags_announces_it() {
1305        let srv = server();
1306        let m = AuthMsg {
1307            av_flags: Some(MSV_AV_FLAG_MIC),
1308            mic_field: true,
1309            ..AuthMsg::default()
1310        };
1311        let (mut msg, key) = build_auth(&m);
1312        sign_mic(&srv, &mut msg, &key);
1313        let outcome = srv.authenticate(&msg, user_creds).expect("valid MIC");
1314        assert!(outcome.mic_present);
1315
1316        msg[80] ^= 1;
1317        assert!(srv.authenticate(&msg, user_creds).is_err(), "bad MIC");
1318
1319        // MsvAvFlags announces a MIC, but the header has no room for one.
1320        let m = AuthMsg {
1321            av_flags: Some(MSV_AV_FLAG_MIC),
1322            ..AuthMsg::default()
1323        };
1324        let (msg, _) = build_auth(&m);
1325        assert!(srv.authenticate(&msg, user_creds).is_err(), "stripped MIC");
1326    }
1327
1328    #[test]
1329    fn padding_without_msv_av_flags_is_not_a_mic() {
1330        let srv = server();
1331        let m = AuthMsg {
1332            mic_field: true,
1333            ..AuthMsg::default()
1334        };
1335        let (msg, _) = build_auth(&m);
1336        let outcome = srv.authenticate(&msg, user_creds).expect("no MIC");
1337        assert!(!outcome.mic_present);
1338    }
1339
1340    #[test]
1341    fn key_exch_needs_a_16_byte_session_key() {
1342        let srv = server();
1343        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
1344            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
1345            | flags::NTLMSSP_NEGOTIATE_SIGN;
1346        let m = AuthMsg {
1347            flags,
1348            ..AuthMsg::default()
1349        };
1350        let (msg, _) = build_auth(&m);
1351        assert!(srv.authenticate(&msg, user_creds).is_err(), "empty key");
1352
1353        let random = [0x55u8; 16];
1354        let (_, kxkey) = build_auth(&m);
1355        let encrypted = rc4k(&kxkey, &random);
1356        let m = AuthMsg {
1357            flags,
1358            encrypted_key: &encrypted,
1359            ..AuthMsg::default()
1360        };
1361        let (msg, _) = build_auth(&m);
1362        let outcome = srv.authenticate(&msg, user_creds).expect("16-byte key");
1363        assert_eq!(outcome.session_key, random);
1364
1365        // Without SIGN or SEAL the key is checked but not unwrapped.
1366        let m = AuthMsg {
1367            flags: flags::NTLMSSP_NEGOTIATE_UNICODE | flags::NTLMSSP_NEGOTIATE_KEY_EXCH,
1368            encrypted_key: &encrypted,
1369            ..AuthMsg::default()
1370        };
1371        let (msg, kxkey) = build_auth(&m);
1372        let outcome = srv.authenticate(&msg, user_creds).expect("no signing");
1373        assert_eq!(outcome.session_key, kxkey);
1374    }
1375
1376    #[test]
1377    fn anonymous_needs_an_empty_or_zero_lm_response() {
1378        let srv = server();
1379        for lm in [&[][..], &[0u8][..]] {
1380            let m = AuthMsg {
1381                user: "",
1382                nt: Some(&[]),
1383                lm,
1384                ..AuthMsg::default()
1385            };
1386            let (msg, _) = build_auth(&m);
1387            let outcome = srv.authenticate(&msg, |_, _| None).expect("anonymous");
1388            assert_eq!(outcome.identity, Identity::Anonymous);
1389        }
1390        let m = AuthMsg {
1391            user: "",
1392            nt: Some(&[]),
1393            lm: &[0x11; 24],
1394            ..AuthMsg::default()
1395        };
1396        let (msg, _) = build_auth(&m);
1397        assert!(srv.authenticate(&msg, |_, _| None).is_err());
1398    }
1399
1400    #[test]
1401    fn unknown_user_fails() {
1402        let srv = server();
1403        let m = AuthMsg {
1404            user: "Nobody",
1405            ..AuthMsg::default()
1406        };
1407        let (msg, _) = build_auth(&m);
1408        assert!(srv.authenticate(&msg, user_creds).is_err());
1409        // Even when the response was computed against the fixed hash.
1410        let m = AuthMsg {
1411            user: "Nobody",
1412            password: "",
1413            ..AuthMsg::default()
1414        };
1415        let (mut msg, _) = build_auth(&m);
1416        let key_nt = ntowf_v2(&[0u8; 16], "Nobody", "");
1417        let nt_off = u32::from_le_bytes(msg[24..28].try_into().unwrap()) as usize;
1418        let nt_len = u16::from_le_bytes(msg[20..22].try_into().unwrap()) as usize;
1419        let client_blob = msg[nt_off + 16..nt_off + nt_len].to_vec();
1420        let proof = hmac_md5(&key_nt, &[&CHALLENGE, &client_blob]);
1421        msg[nt_off..nt_off + 16].copy_from_slice(&proof);
1422        assert!(srv.authenticate(&msg, user_creds).is_err());
1423    }
1424
1425    /// MS-NLMP 4.2.4.2.3: RC4(SessionBaseKey, RandomSessionKey).
1426    #[test]
1427    fn encrypted_session_key_known_answer() {
1428        let session_base_key = [
1429            0x8d, 0xe4, 0x0c, 0xca, 0xdb, 0xc1, 0x4a, 0x82, 0xf1, 0x5c, 0xb0, 0xad, 0x0d, 0xe9,
1430            0x5c, 0xa3,
1431        ];
1432        let encrypted = [
1433            0xc5, 0xda, 0xd2, 0x54, 0x4f, 0xc9, 0x79, 0x90, 0x94, 0xce, 0x1c, 0xe9, 0x0b, 0xc9,
1434            0xd0, 0x3e,
1435        ];
1436        assert_eq!(rc4k(&session_base_key, &encrypted), [0x55; 16]);
1437    }
1438
1439    /// MS-NLMP 4.2.4.4: client sealing and signing keys, and the signature
1440    /// of "Plaintext" sealed and signed at sequence number 0.
1441    #[test]
1442    fn gss_wrap_ex_known_answer() {
1443        let flags = 0xE28A_8233;
1444        let mut mac = NtlmMac::new(flags, &[0x55; 16], Direction::ClientToServer).unwrap();
1445        assert_eq!(
1446            mac.signing_key,
1447            [
1448                0x47, 0x88, 0xdc, 0x86, 0x1b, 0x47, 0x82, 0xf3, 0x5d, 0x43, 0xfd, 0x98, 0xfe, 0x1a,
1449                0x2d, 0x39
1450            ]
1451        );
1452        let plaintext = utf16le("Plaintext");
1453        let mut sealed = plaintext.clone();
1454        mac.handle.as_mut().unwrap().apply_keystream(&mut sealed);
1455        assert_eq!(
1456            sealed,
1457            [
1458                0x54, 0xe5, 0x01, 0x65, 0xbf, 0x19, 0x36, 0xdc, 0x99, 0x60, 0x20, 0xc1, 0x81, 0x1b,
1459                0x0f, 0x06, 0xfb, 0x5f
1460            ]
1461        );
1462        assert_eq!(
1463            mac.mac(&plaintext),
1464            [
1465                0x01, 0x00, 0x00, 0x00, 0x7f, 0xb3, 0x8e, 0xc5, 0xc5, 0x5d, 0x49, 0x76, 0x00, 0x00,
1466                0x00, 0x00
1467            ]
1468        );
1469        assert_eq!(mac.seq, 1);
1470    }
1471
1472    #[test]
1473    fn mac_needs_extended_session_security_and_signing() {
1474        let key = [0x55; 16];
1475        let ess = flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY;
1476        let sign = flags::NTLMSSP_NEGOTIATE_SIGN;
1477        assert!(NtlmMac::new(sign, &key, Direction::ServerToClient).is_none());
1478        assert!(NtlmMac::new(ess, &key, Direction::ServerToClient).is_none());
1479        let mut mac = NtlmMac::new(ess | sign, &key, Direction::ServerToClient).unwrap();
1480        assert!(mac.handle.is_none());
1481        let sig = mac.mac(b"message");
1482        let expected = hmac_md5(
1483            &md5_concat(
1484                &key,
1485                b"session key to server-to-client signing key magic constant\0",
1486            ),
1487            &[&0u32.to_le_bytes(), b"message"],
1488        );
1489        assert_eq!(sig[4..12], expected[..8]);
1490    }
1491}