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 mut unwrapped = None;
836        let mut session_key = if auth.flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH != 0 {
837            let encrypted: [u8; 16] = auth
838                .encrypted_random_session_key
839                .as_slice()
840                .try_into()
841                .map_err(|_| ProtoError::Auth("encrypted session key not 16 bytes"))?;
842            if auth.flags & (flags::NTLMSSP_NEGOTIATE_SIGN | flags::NTLMSSP_NEGOTIATE_SEAL) != 0 {
843                rc4k(&key_exchange_key, &encrypted)
844            } else {
845                unwrapped = Some(rc4k(&key_exchange_key, &encrypted));
846                key_exchange_key
847            }
848        } else {
849            key_exchange_key
850        };
851
852        // ---- MIC: HMAC_MD5(ExportedSessionKey, NEGOTIATE || CHALLENGE ||
853        // AUTHENTICATE with the MIC zeroed), required when MsvAvFlags says
854        // the message carries one.
855        if let (Some(mic_off), Some(supplied)) = (auth.mic_offset, auth.mic) {
856            let mut auth_zeroed = auth.raw.clone();
857            auth_zeroed[mic_off..mic_off + 16].fill(0);
858            let mic_ok = |key: &[u8; 16]| {
859                let mut mac = HmacMd5::new_from_slice(key).expect("hmac key");
860                mac.update(&self.negotiate_bytes);
861                mac.update(&self.challenge_bytes);
862                mac.update(&auth_zeroed);
863                ct_eq_16(&supplied, &mac.finalize().into_bytes())
864            };
865            if !mic_ok(&session_key) {
866                // MS-NLMP 3.2.5.1.2 keeps KeyExchangeKey as the
867                // ExportedSessionKey under KEY_EXCH without SIGN or SEAL.
868                // The macOS client, with SIGN and SEAL clear in all three
869                // messages, unwraps the random session key anyway and keys
870                // its MIC with it. A MIC that verifies under that key makes
871                // it the ExportedSessionKey.
872                match unwrapped.filter(|key| mic_ok(key)) {
873                    Some(key) => session_key = key,
874                    None => return Err(ProtoError::Auth("MIC mismatch")),
875                }
876            }
877        }
878
879        Ok(AuthOutcome {
880            identity: Identity::User {
881                user: auth.user.clone(),
882                domain: auth.domain.clone(),
883            },
884            session_key,
885            flags: auth.flags,
886            mic_present: auth.mic.is_some(),
887        })
888    }
889}
890
891// ===========================================================================
892// Tests
893// ===========================================================================
894
895/// Hand-built NTLM AUTHENTICATE_MESSAGEs for tests.
896#[cfg(test)]
897pub(crate) mod testing {
898    use super::*;
899
900    pub(crate) const CHALLENGE: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
901
902    pub(crate) fn hmac_md5(key: &[u8], parts: &[&[u8]]) -> [u8; 16] {
903        let mut mac = HmacMd5::new_from_slice(key).unwrap();
904        for part in parts {
905            mac.update(part);
906        }
907        mac.finalize().into_bytes().into()
908    }
909
910    /// Fields of a hand-built AUTHENTICATE_MESSAGE.
911    pub(crate) struct AuthMsg<'a> {
912        pub(crate) user: &'a str,
913        pub(crate) password: &'a str,
914        pub(crate) flags: u32,
915        /// `MsvAvFlags` value to put in the NTLMv2 response.
916        pub(crate) av_flags: Option<u32>,
917        /// AV_PAIRs after `MsvAvFlags`.
918        pub(crate) av_pairs: &'a [AvPair],
919        pub(crate) workstation: &'a str,
920        /// Leave room for a MIC at offset 72.
921        pub(crate) mic_field: bool,
922        pub(crate) lm: &'a [u8],
923        pub(crate) nt: Option<&'a [u8]>,
924        pub(crate) encrypted_key: &'a [u8],
925        /// ServerChallenge the response answers.
926        pub(crate) challenge: [u8; 8],
927    }
928
929    impl Default for AuthMsg<'_> {
930        fn default() -> Self {
931            Self {
932                user: "User",
933                password: "Password",
934                flags: flags::NTLMSSP_NEGOTIATE_UNICODE,
935                av_flags: None,
936                av_pairs: &[],
937                workstation: "",
938                mic_field: false,
939                lm: &[],
940                nt: None,
941                encrypted_key: &[],
942                challenge: CHALLENGE,
943            }
944        }
945    }
946
947    /// The message and the KeyExchangeKey the server derives from it.
948    pub(crate) fn build_auth(m: &AuthMsg<'_>) -> (Vec<u8>, [u8; 16]) {
949        let key_nt = ntowf_v2(&nt_hash(m.password), m.user, "");
950        let mut blob = vec![1, 1, 0, 0, 0, 0, 0, 0];
951        blob.extend_from_slice(&[0; 8]);
952        blob.extend_from_slice(&[0xAA; 8]);
953        blob.extend_from_slice(&[0; 4]);
954        let mut pairs: Vec<AvPair> = m
955            .av_flags
956            .map(|av| AvPair::new(AvId::Flags, av.to_le_bytes().to_vec()))
957            .into_iter()
958            .collect();
959        pairs.extend_from_slice(m.av_pairs);
960        blob.extend_from_slice(&encode_av_pairs(&pairs));
961        let proof = hmac_md5(&key_nt, &[&m.challenge, &blob]);
962        let key_exchange_key = hmac_md5(&key_nt, &[&proof]);
963        let nt =
964            m.nt.map_or_else(|| [&proof[..], &blob].concat(), <[u8]>::to_vec);
965
966        let user = utf16le(m.user);
967        let workstation = utf16le(m.workstation);
968        let fields: [&[u8]; 6] = [m.lm, &nt, &[], &user, &workstation, m.encrypted_key];
969        let header_len = if m.mic_field { 88u32 } else { 72 };
970        let mut msg = NTLMSSP_SIGNATURE.to_vec();
971        msg.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
972        let mut payload = Vec::new();
973        for field in fields {
974            let offset = header_len + payload.len() as u32;
975            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
976            msg.extend_from_slice(&(field.len() as u16).to_le_bytes());
977            msg.extend_from_slice(&offset.to_le_bytes());
978            payload.extend_from_slice(field);
979        }
980        msg.extend_from_slice(&m.flags.to_le_bytes());
981        msg.extend_from_slice(&[0u8; 8]);
982        if m.mic_field {
983            msg.extend_from_slice(&[0u8; 16]);
984        }
985        msg.extend_from_slice(&payload);
986        (msg, key_exchange_key)
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::testing::*;
993    use super::*;
994
995    #[test]
996    fn av_pair_round_trip() {
997        let pairs = vec![
998            AvPair::new(AvId::NbDomainName, utf16le("DOMAIN")),
999            AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
1000            AvPair::new(
1001                AvId::Timestamp,
1002                0x1234_5678_9abc_def0u64.to_le_bytes().to_vec(),
1003            ),
1004        ];
1005        let bytes = encode_av_pairs(&pairs);
1006        let decoded = decode_av_pairs(&bytes).unwrap();
1007        assert_eq!(decoded, pairs);
1008    }
1009
1010    #[test]
1011    fn negotiate_round_trip() {
1012        // Build a minimal Type 1 by hand and parse it.
1013        let mut buf = Vec::new();
1014        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1015        buf.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
1016        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
1017            | flags::NTLMSSP_NEGOTIATE_NTLM
1018            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO;
1019        buf.extend_from_slice(&flags.to_le_bytes());
1020        // Domain + workstation fields: empty.
1021        buf.extend_from_slice(&[0u8; 8]);
1022        buf.extend_from_slice(&[0u8; 8]);
1023        // Version (8 bytes).
1024        buf.extend_from_slice(&[0u8; 8]);
1025
1026        let n = NtlmNegotiate::parse(&buf).unwrap();
1027        assert_eq!(n.flags, flags);
1028    }
1029
1030    #[test]
1031    fn challenge_round_trip_structure() {
1032        let blob = build_challenge(&ChallengeParams {
1033            server_challenge: [1, 2, 3, 4, 5, 6, 7, 8],
1034            target_name: "SERVER",
1035            nb_domain_name: "DOMAIN",
1036            nb_computer_name: "SERVER",
1037            dns_domain_name: "domain.local",
1038            dns_computer_name: "server.domain.local",
1039            timestamp: 0,
1040            flags: flags::NTLMSSP_NEGOTIATE_UNICODE
1041                | flags::NTLMSSP_NEGOTIATE_NTLM
1042                | flags::NTLMSSP_NEGOTIATE_TARGET_INFO,
1043        });
1044        // Signature + message type.
1045        assert_eq!(&blob[..8], NTLMSSP_SIGNATURE);
1046        assert_eq!(
1047            u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]),
1048            MSG_CHALLENGE
1049        );
1050        // Server challenge at offset 24.
1051        assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
1052        // Decode AV_PAIRs from the target-info section.
1053        let ti_off = u32::from_le_bytes([blob[44], blob[45], blob[46], blob[47]]) as usize;
1054        let ti_len = u16::from_le_bytes([blob[40], blob[41]]) as usize;
1055        let av = decode_av_pairs(&blob[ti_off..ti_off + ti_len]).unwrap();
1056        assert!(av.iter().any(|p| p.id == AvId::NbDomainName as u16));
1057        assert!(av.iter().any(|p| p.id == AvId::Timestamp as u16));
1058    }
1059
1060    /// MS-NLMP §4.2.4 known-answer test for NTLMv2:
1061    ///     User="User", Domain="Domain", Password="Password"
1062    ///     ServerChallenge = 01 23 45 67 89 ab cd ef
1063    ///     ClientChallenge AV-pair blob = 01 01 00 00 00 00 00 00
1064    ///                                    00 00 00 00 00 00 00 00
1065    ///                                    aa aa aa aa aa aa aa aa
1066    ///                                    00 00 00 00 02 00 0c 00
1067    ///                                    44 00 6f 00 6d 00 61 00
1068    ///                                    69 00 6e 00 01 00 0c 00
1069    ///                                    53 00 65 00 72 00 76 00
1070    ///                                    65 00 72 00 00 00 00 00
1071    ///                                    00 00 00 00
1072    /// Expected NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1073    #[test]
1074    fn ntlmv2_known_answer() {
1075        let nt = nt_hash("Password");
1076        // 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
1077        assert_eq!(
1078            nt,
1079            [
1080                0xa4, 0xf4, 0x9c, 0x40, 0x65, 0x10, 0xbd, 0xca, 0xb6, 0x82, 0x4e, 0xe7, 0xc3, 0x0f,
1081                0xd8, 0x52
1082            ]
1083        );
1084
1085        // NTOWFv2("Password","User","Domain")
1086        // MS-NLMP §4.2.4.1.1: 0c 86 8a 40 3b fd 7a 93 a3 00 1e f2 2e f0 2e 3f
1087        let key_nt = ntowf_v2(&nt, "User", "Domain");
1088        assert_eq!(
1089            key_nt,
1090            [
1091                0x0c, 0x86, 0x8a, 0x40, 0x3b, 0xfd, 0x7a, 0x93, 0xa3, 0x00, 0x1e, 0xf2, 0x2e, 0xf0,
1092                0x2e, 0x3f
1093            ]
1094        );
1095
1096        let server_challenge: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
1097        // NTLMv2_CLIENT_CHALLENGE blob from §4.2.4.1.3
1098        let client_challenge_blob: &[u8] = &[
1099            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // RespType, HiRespType, Reserved
1100            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TimeStamp
1101            0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, // ChallengeFromClient
1102            0x00, 0x00, 0x00, 0x00, // Reserved
1103            // AV pairs
1104            0x02, 0x00, 0x0c, 0x00, // MsvAvNbDomainName, len=12
1105            0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e,
1106            0x00, // "Domain"
1107            0x01, 0x00, 0x0c, 0x00, // MsvAvNbComputerName, len=12
1108            0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
1109            0x00, // "Server"
1110            0x00, 0x00, 0x00, 0x00, // EOL
1111            0x00, 0x00, 0x00, 0x00, // trailing 4 zero bytes (padding seen in spec)
1112        ];
1113
1114        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1115        mac.update(&server_challenge);
1116        mac.update(client_challenge_blob);
1117        let nt_proof = mac.finalize().into_bytes();
1118
1119        // MS-NLMP §4.2.4.2.2:
1120        //   NTProofStr = 68 cd 0a b8 51 e5 1c 96 aa bc 92 7b eb ef 6a 1c
1121        assert_eq!(
1122            nt_proof.as_slice(),
1123            [
1124                0x68, 0xcd, 0x0a, 0xb8, 0x51, 0xe5, 0x1c, 0x96, 0xaa, 0xbc, 0x92, 0x7b, 0xeb, 0xef,
1125                0x6a, 0x1c
1126            ]
1127        );
1128    }
1129
1130    #[test]
1131    fn server_round_trip_authenticates_user() {
1132        // End-to-end: build a fake AUTHENTICATE_MESSAGE with a known proof and
1133        // make sure NtlmServer accepts it.
1134        let mut srv = NtlmServer::new(
1135            [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
1136            NtlmTargetInfo::new(
1137                "SERVER",
1138                "DOMAIN",
1139                "SERVER",
1140                "domain.local",
1141                "server.domain.local",
1142            ),
1143            0,
1144        );
1145        // Skip step1_negotiate - MIC will be absent.
1146        let _challenge = srv.challenge();
1147
1148        // Compute NTProofStr the same way the client would.
1149        let nt = nt_hash("Password");
1150        let key_nt = ntowf_v2(&nt, "User", "Domain");
1151        let client_challenge_blob: Vec<u8> = vec![
1152            0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1153            0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
1154            // Empty AV pair list (EOL only)
1155            0x00, 0x00, 0x00, 0x00,
1156        ];
1157        let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
1158        mac.update(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
1159        mac.update(&client_challenge_blob);
1160        let nt_proof = mac.finalize().into_bytes();
1161
1162        let mut nt_response = Vec::new();
1163        nt_response.extend_from_slice(&nt_proof);
1164        nt_response.extend_from_slice(&client_challenge_blob);
1165
1166        // Build AUTHENTICATE_MESSAGE.
1167        let user_u16 = utf16le("User");
1168        let dom_u16 = utf16le("Domain");
1169        let ws_u16 = utf16le("CLIENT");
1170        let lm_response: Vec<u8> = vec![0u8; 24];
1171
1172        // Layout: header is 72 bytes when no MIC is present
1173        // (signature 8 + msgtype 4 + 6x8-byte fields + flags 4 + version 8 = 72).
1174        // With MIC, it would be 88.
1175        let header_len: u32 = 72;
1176        let mut payload = Vec::new();
1177        let lm_off = header_len;
1178        payload.extend_from_slice(&lm_response);
1179        let nt_off = header_len + payload.len() as u32;
1180        payload.extend_from_slice(&nt_response);
1181        let dom_off = header_len + payload.len() as u32;
1182        payload.extend_from_slice(&dom_u16);
1183        let user_off = header_len + payload.len() as u32;
1184        payload.extend_from_slice(&user_u16);
1185        let ws_off = header_len + payload.len() as u32;
1186        payload.extend_from_slice(&ws_u16);
1187        let key_off = header_len + payload.len() as u32;
1188        // No encrypted session key.
1189
1190        let mut buf = Vec::new();
1191        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1192        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1193        // Lm
1194        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1195        buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
1196        buf.extend_from_slice(&lm_off.to_le_bytes());
1197        // Nt
1198        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1199        buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
1200        buf.extend_from_slice(&nt_off.to_le_bytes());
1201        // Domain
1202        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1203        buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
1204        buf.extend_from_slice(&dom_off.to_le_bytes());
1205        // User
1206        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1207        buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
1208        buf.extend_from_slice(&user_off.to_le_bytes());
1209        // Workstation
1210        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1211        buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
1212        buf.extend_from_slice(&ws_off.to_le_bytes());
1213        // EncryptedRandomSessionKey
1214        buf.extend_from_slice(&0u16.to_le_bytes());
1215        buf.extend_from_slice(&0u16.to_le_bytes());
1216        buf.extend_from_slice(&key_off.to_le_bytes());
1217        // Flags
1218        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
1219        // Version (8 bytes)
1220        buf.extend_from_slice(&[0u8; 8]);
1221        // No MIC: header is 72 bytes.
1222        assert_eq!(buf.len() as u32, header_len);
1223        buf.extend_from_slice(&payload);
1224
1225        let creds = UserCreds::from_password("Password");
1226        let outcome = srv
1227            .authenticate(&buf, |u, d| {
1228                if u == "User" && d == "Domain" {
1229                    Some(creds.clone())
1230                } else {
1231                    None
1232                }
1233            })
1234            .expect("auth should succeed");
1235
1236        assert_eq!(
1237            outcome.identity,
1238            Identity::User {
1239                user: "User".to_string(),
1240                domain: "Domain".to_string()
1241            }
1242        );
1243
1244        // Wrong password fails.
1245        let bad = UserCreds::from_password("WrongPassword");
1246        let err = srv
1247            .authenticate(&buf, |_u, _d| Some(bad.clone()))
1248            .unwrap_err();
1249        assert!(matches!(err, ProtoError::Auth(_)));
1250    }
1251
1252    #[test]
1253    fn debug_output_hides_keys() {
1254        let creds = UserCreds {
1255            nt_hash: [0xAB; 16],
1256        };
1257        assert_eq!(format!("{creds:?}"), "UserCreds { .. }");
1258        let outcome = AuthOutcome {
1259            identity: Identity::Anonymous,
1260            session_key: [0xCD; 16],
1261            flags: 0,
1262            mic_present: false,
1263        };
1264        let shown = format!("{outcome:?}");
1265        assert_eq!(shown, "AuthOutcome { identity: Anonymous, .. }");
1266    }
1267
1268    #[test]
1269    fn anonymous_logon() {
1270        let mut srv = NtlmServer::new(
1271            [0u8; 8],
1272            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1273            0,
1274        );
1275        let _ = srv.challenge();
1276
1277        // Build an AUTHENTICATE_MESSAGE with empty user + empty NT response.
1278        let header_len: u32 = 72;
1279        let mut buf = Vec::new();
1280        buf.extend_from_slice(NTLMSSP_SIGNATURE);
1281        buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1282        for _ in 0..6 {
1283            // 6 empty fields (Lm, Nt, Domain, User, Workstation, Key)
1284            buf.extend_from_slice(&0u16.to_le_bytes());
1285            buf.extend_from_slice(&0u16.to_le_bytes());
1286            buf.extend_from_slice(&header_len.to_le_bytes());
1287        }
1288        buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_ANONYMOUS.to_le_bytes());
1289        buf.extend_from_slice(&[0u8; 8]); // version
1290
1291        let outcome = srv
1292            .authenticate(&buf, |_u, _d| None)
1293            .expect("anonymous should succeed");
1294        assert_eq!(outcome.identity, Identity::Anonymous);
1295        assert_eq!(outcome.session_key, [0u8; 16]);
1296    }
1297
1298    fn server() -> NtlmServer {
1299        let mut srv = NtlmServer::new(
1300            CHALLENGE,
1301            NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1302            0,
1303        );
1304        let mut negotiate = NTLMSSP_SIGNATURE.to_vec();
1305        negotiate.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
1306        negotiate.extend_from_slice(&0xE288_8235u32.to_le_bytes());
1307        negotiate.extend_from_slice(&[0u8; 16]);
1308        srv.step1_negotiate(&negotiate).unwrap();
1309        srv.challenge();
1310        srv
1311    }
1312
1313    fn sign_mic(srv: &NtlmServer, msg: &mut [u8], key: &[u8; 16]) {
1314        let mic = hmac_md5(key, &[&srv.negotiate_bytes, &srv.challenge_bytes, msg]);
1315        msg[72..88].copy_from_slice(&mic);
1316    }
1317
1318    fn user_creds(u: &str, _d: &str) -> Option<UserCreds> {
1319        (u == "User").then(|| UserCreds::from_password("Password"))
1320    }
1321
1322    #[test]
1323    fn mic_is_checked_when_msv_av_flags_announces_it() {
1324        let srv = server();
1325        let m = AuthMsg {
1326            av_flags: Some(MSV_AV_FLAG_MIC),
1327            mic_field: true,
1328            ..AuthMsg::default()
1329        };
1330        let (mut msg, key) = build_auth(&m);
1331        sign_mic(&srv, &mut msg, &key);
1332        let outcome = srv.authenticate(&msg, user_creds).expect("valid MIC");
1333        assert!(outcome.mic_present);
1334
1335        msg[80] ^= 1;
1336        assert!(srv.authenticate(&msg, user_creds).is_err(), "bad MIC");
1337
1338        // MsvAvFlags announces a MIC, but the header has no room for one.
1339        let m = AuthMsg {
1340            av_flags: Some(MSV_AV_FLAG_MIC),
1341            ..AuthMsg::default()
1342        };
1343        let (msg, _) = build_auth(&m);
1344        assert!(srv.authenticate(&msg, user_creds).is_err(), "stripped MIC");
1345    }
1346
1347    #[test]
1348    fn padding_without_msv_av_flags_is_not_a_mic() {
1349        let srv = server();
1350        let m = AuthMsg {
1351            mic_field: true,
1352            ..AuthMsg::default()
1353        };
1354        let (msg, _) = build_auth(&m);
1355        let outcome = srv.authenticate(&msg, user_creds).expect("no MIC");
1356        assert!(!outcome.mic_present);
1357    }
1358
1359    #[test]
1360    fn key_exch_needs_a_16_byte_session_key() {
1361        let srv = server();
1362        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
1363            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
1364            | flags::NTLMSSP_NEGOTIATE_SIGN;
1365        let m = AuthMsg {
1366            flags,
1367            ..AuthMsg::default()
1368        };
1369        let (msg, _) = build_auth(&m);
1370        assert!(srv.authenticate(&msg, user_creds).is_err(), "empty key");
1371
1372        let random = [0x55u8; 16];
1373        let (_, kxkey) = build_auth(&m);
1374        let encrypted = rc4k(&kxkey, &random);
1375        let m = AuthMsg {
1376            flags,
1377            encrypted_key: &encrypted,
1378            ..AuthMsg::default()
1379        };
1380        let (msg, _) = build_auth(&m);
1381        let outcome = srv.authenticate(&msg, user_creds).expect("16-byte key");
1382        assert_eq!(outcome.session_key, random);
1383
1384        // Without SIGN or SEAL the key is checked but not unwrapped.
1385        let m = AuthMsg {
1386            flags: flags::NTLMSSP_NEGOTIATE_UNICODE | flags::NTLMSSP_NEGOTIATE_KEY_EXCH,
1387            encrypted_key: &encrypted,
1388            ..AuthMsg::default()
1389        };
1390        let (msg, kxkey) = build_auth(&m);
1391        let outcome = srv.authenticate(&msg, user_creds).expect("no signing");
1392        assert_eq!(outcome.session_key, kxkey);
1393    }
1394
1395    /// With KEY_EXCH but neither SIGN nor SEAL, the MIC may be keyed with
1396    /// KeyExchangeKey or with the unwrapped random session key; the session
1397    /// takes the key that verified it.
1398    #[test]
1399    fn key_exch_without_signing_takes_the_key_the_mic_verifies() {
1400        let srv = server();
1401        let random = [0x55u8; 16];
1402        let m = AuthMsg {
1403            flags: flags::NTLMSSP_NEGOTIATE_UNICODE
1404                | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
1405                | flags::NTLMSSP_NEGOTIATE_KEY_EXCH,
1406            av_flags: Some(MSV_AV_FLAG_MIC),
1407            mic_field: true,
1408            ..AuthMsg::default()
1409        };
1410        let (_, kxkey) = build_auth(&m);
1411        let encrypted = rc4k(&kxkey, &random);
1412        let m = AuthMsg {
1413            encrypted_key: &encrypted,
1414            ..m
1415        };
1416        for key in [random, kxkey] {
1417            let (mut msg, _) = build_auth(&m);
1418            sign_mic(&srv, &mut msg, &key);
1419            let outcome = srv.authenticate(&msg, user_creds).expect("MIC");
1420            assert_eq!(outcome.session_key, key);
1421        }
1422        let (mut msg, _) = build_auth(&m);
1423        sign_mic(&srv, &mut msg, &[0x66; 16]);
1424        assert!(srv.authenticate(&msg, user_creds).is_err());
1425
1426        // With SIGN the random session key is the only one.
1427        let m = AuthMsg {
1428            flags: m.flags | flags::NTLMSSP_NEGOTIATE_SIGN,
1429            ..m
1430        };
1431        let (mut msg, _) = build_auth(&m);
1432        sign_mic(&srv, &mut msg, &kxkey);
1433        assert!(
1434            srv.authenticate(&msg, user_creds).is_err(),
1435            "KeyExchangeKey"
1436        );
1437        let (mut msg, _) = build_auth(&m);
1438        sign_mic(&srv, &mut msg, &random);
1439        let outcome = srv.authenticate(&msg, user_creds).expect("random key");
1440        assert_eq!(outcome.session_key, random);
1441    }
1442
1443    #[test]
1444    fn anonymous_needs_an_empty_or_zero_lm_response() {
1445        let srv = server();
1446        for lm in [&[][..], &[0u8][..]] {
1447            let m = AuthMsg {
1448                user: "",
1449                nt: Some(&[]),
1450                lm,
1451                ..AuthMsg::default()
1452            };
1453            let (msg, _) = build_auth(&m);
1454            let outcome = srv.authenticate(&msg, |_, _| None).expect("anonymous");
1455            assert_eq!(outcome.identity, Identity::Anonymous);
1456        }
1457        let m = AuthMsg {
1458            user: "",
1459            nt: Some(&[]),
1460            lm: &[0x11; 24],
1461            ..AuthMsg::default()
1462        };
1463        let (msg, _) = build_auth(&m);
1464        assert!(srv.authenticate(&msg, |_, _| None).is_err());
1465    }
1466
1467    #[test]
1468    fn unknown_user_fails() {
1469        let srv = server();
1470        let m = AuthMsg {
1471            user: "Nobody",
1472            ..AuthMsg::default()
1473        };
1474        let (msg, _) = build_auth(&m);
1475        assert!(srv.authenticate(&msg, user_creds).is_err());
1476        // Even when the response was computed against the fixed hash.
1477        let m = AuthMsg {
1478            user: "Nobody",
1479            password: "",
1480            ..AuthMsg::default()
1481        };
1482        let (mut msg, _) = build_auth(&m);
1483        let key_nt = ntowf_v2(&[0u8; 16], "Nobody", "");
1484        let nt_off = u32::from_le_bytes(msg[24..28].try_into().unwrap()) as usize;
1485        let nt_len = u16::from_le_bytes(msg[20..22].try_into().unwrap()) as usize;
1486        let client_blob = msg[nt_off + 16..nt_off + nt_len].to_vec();
1487        let proof = hmac_md5(&key_nt, &[&CHALLENGE, &client_blob]);
1488        msg[nt_off..nt_off + 16].copy_from_slice(&proof);
1489        assert!(srv.authenticate(&msg, user_creds).is_err());
1490    }
1491
1492    fn empty_password(user: &str, _domain: &str) -> Option<UserCreds> {
1493        (user == "GUEST").then(|| UserCreds::from_password(""))
1494    }
1495
1496    /// A guest logon as the macOS client sends it: user `GUEST`, no domain,
1497    /// a zeroed 24-byte LM response, and an NTLMv2 response with a MIC,
1498    /// channel bindings and a target name, with key exchange but without
1499    /// signing or sealing, and the MIC keyed with the random session key.
1500    #[test]
1501    fn guest_logon_proves_an_empty_password() {
1502        let srv = server();
1503        let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
1504            | flags::NTLMSSP_REQUEST_TARGET
1505            | flags::NTLMSSP_NEGOTIATE_NTLM
1506            | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
1507            | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
1508            | flags::NTLMSSP_NEGOTIATE_VERSION
1509            | flags::NTLMSSP_NEGOTIATE_128
1510            | flags::NTLMSSP_NEGOTIATE_KEY_EXCH;
1511        let av_pairs = [
1512            AvPair::new(AvId::NbDomainName, utf16le("SERVER")),
1513            AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
1514            AvPair::new(AvId::DnsDomainName, Vec::new()),
1515            AvPair::new(AvId::DnsComputerName, Vec::new()),
1516            AvPair::new(
1517                AvId::Timestamp,
1518                0x01DC_4A00_0000_0000u64.to_le_bytes().to_vec(),
1519            ),
1520            AvPair::new(AvId::ChannelBindings, vec![0; 16]),
1521            AvPair::new(AvId::TargetName, utf16le("cifs/server.example")),
1522        ];
1523        let guest = |password: &str| {
1524            let m = AuthMsg {
1525                user: "GUEST",
1526                password,
1527                flags,
1528                av_flags: Some(MSV_AV_FLAG_MIC),
1529                av_pairs: &av_pairs,
1530                workstation: "CLIENT",
1531                mic_field: true,
1532                lm: &[0; 24],
1533                encrypted_key: &[0x5A; 16],
1534                ..AuthMsg::default()
1535            };
1536            let (mut msg, kxkey) = build_auth(&m);
1537            sign_mic(&srv, &mut msg, &rc4k(&kxkey, &[0x5A; 16]));
1538            msg
1539        };
1540
1541        let outcome = srv
1542            .authenticate(&guest(""), empty_password)
1543            .expect("empty password");
1544        assert_eq!(
1545            outcome.identity,
1546            Identity::User {
1547                user: "GUEST".to_string(),
1548                domain: String::new()
1549            }
1550        );
1551        assert!(outcome.mic_present);
1552
1553        assert!(srv.authenticate(&guest("secret"), empty_password).is_err());
1554        let secret = |_: &str, _: &str| Some(UserCreds::from_password("secret"));
1555        assert!(srv.authenticate(&guest(""), secret).is_err());
1556    }
1557
1558    /// DESL(K, D) from MS-NLMP 6: `data` encrypted with DES under each
1559    /// seven-byte slice of `key` padded to 21 bytes.
1560    fn desl(key: &[u8; 16], data: &[u8; 8]) -> [u8; 24] {
1561        use des::cipher::{BlockCipherEncrypt, KeyInit};
1562        let mut padded = [0u8; 21];
1563        padded[..16].copy_from_slice(key);
1564        let mut out = [0u8; 24];
1565        for (i, k) in padded.chunks_exact(7).enumerate() {
1566            let mut bits = [0u8; 8];
1567            bits[1..].copy_from_slice(k);
1568            let bits = u64::from_be_bytes(bits);
1569            // 56 key bits, seven to a byte, above each parity bit.
1570            let key8: [u8; 8] =
1571                std::array::from_fn(|j| (((bits >> (49 - 7 * j)) & 0x7F) as u8) << 1);
1572            let cipher = des::Des::new_from_slice(&key8).unwrap();
1573            let mut block = des::cipher::Block::<des::Des>::from(*data);
1574            cipher.encrypt_block(&mut block);
1575            out[8 * i..8 * i + 8].copy_from_slice(&block);
1576        }
1577        out
1578    }
1579
1580    /// MS-NLMP 4.2.2.2.1: the NTLMv1 response for "Password".
1581    #[test]
1582    fn desl_known_answer() {
1583        assert_eq!(
1584            desl(&nt_hash("Password"), &CHALLENGE),
1585            [
1586                0x67, 0xc4, 0x30, 0x11, 0xf3, 0x02, 0x98, 0xa2, 0xad, 0x35, 0xec, 0xe6, 0x4f, 0x16,
1587                0x33, 0x1c, 0x44, 0xbd, 0xbe, 0xd9, 0x27, 0x84, 0x1f, 0x94
1588            ]
1589        );
1590    }
1591
1592    /// Only NTLMv2 proves a password: the NTLMv1 response for the empty
1593    /// password fails, and so does the same response as an LM response
1594    /// alone.
1595    #[test]
1596    fn guest_logon_needs_an_ntlmv2_response() {
1597        let srv = server();
1598        let v1 = desl(&nt_hash(""), &CHALLENGE);
1599        for nt in [&v1[..], &[][..]] {
1600            let m = AuthMsg {
1601                user: "GUEST",
1602                password: "",
1603                lm: &v1,
1604                nt: Some(nt),
1605                ..AuthMsg::default()
1606            };
1607            let (msg, _) = build_auth(&m);
1608            assert!(srv.authenticate(&msg, empty_password).is_err());
1609        }
1610    }
1611
1612    /// MS-NLMP 4.2.4.2.3: RC4(SessionBaseKey, RandomSessionKey).
1613    #[test]
1614    fn encrypted_session_key_known_answer() {
1615        let session_base_key = [
1616            0x8d, 0xe4, 0x0c, 0xca, 0xdb, 0xc1, 0x4a, 0x82, 0xf1, 0x5c, 0xb0, 0xad, 0x0d, 0xe9,
1617            0x5c, 0xa3,
1618        ];
1619        let encrypted = [
1620            0xc5, 0xda, 0xd2, 0x54, 0x4f, 0xc9, 0x79, 0x90, 0x94, 0xce, 0x1c, 0xe9, 0x0b, 0xc9,
1621            0xd0, 0x3e,
1622        ];
1623        assert_eq!(rc4k(&session_base_key, &encrypted), [0x55; 16]);
1624    }
1625
1626    /// MS-NLMP 4.2.4.4: client sealing and signing keys, and the signature
1627    /// of "Plaintext" sealed and signed at sequence number 0.
1628    #[test]
1629    fn gss_wrap_ex_known_answer() {
1630        let flags = 0xE28A_8233;
1631        let mut mac = NtlmMac::new(flags, &[0x55; 16], Direction::ClientToServer).unwrap();
1632        assert_eq!(
1633            mac.signing_key,
1634            [
1635                0x47, 0x88, 0xdc, 0x86, 0x1b, 0x47, 0x82, 0xf3, 0x5d, 0x43, 0xfd, 0x98, 0xfe, 0x1a,
1636                0x2d, 0x39
1637            ]
1638        );
1639        let plaintext = utf16le("Plaintext");
1640        let mut sealed = plaintext.clone();
1641        mac.handle.as_mut().unwrap().apply_keystream(&mut sealed);
1642        assert_eq!(
1643            sealed,
1644            [
1645                0x54, 0xe5, 0x01, 0x65, 0xbf, 0x19, 0x36, 0xdc, 0x99, 0x60, 0x20, 0xc1, 0x81, 0x1b,
1646                0x0f, 0x06, 0xfb, 0x5f
1647            ]
1648        );
1649        assert_eq!(
1650            mac.mac(&plaintext),
1651            [
1652                0x01, 0x00, 0x00, 0x00, 0x7f, 0xb3, 0x8e, 0xc5, 0xc5, 0x5d, 0x49, 0x76, 0x00, 0x00,
1653                0x00, 0x00
1654            ]
1655        );
1656        assert_eq!(mac.seq, 1);
1657    }
1658
1659    #[test]
1660    fn mac_needs_extended_session_security_and_signing() {
1661        let key = [0x55; 16];
1662        let ess = flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY;
1663        let sign = flags::NTLMSSP_NEGOTIATE_SIGN;
1664        assert!(NtlmMac::new(sign, &key, Direction::ServerToClient).is_none());
1665        assert!(NtlmMac::new(ess, &key, Direction::ServerToClient).is_none());
1666        let mut mac = NtlmMac::new(ess | sign, &key, Direction::ServerToClient).unwrap();
1667        assert!(mac.handle.is_none());
1668        let sig = mac.mac(b"message");
1669        let expected = hmac_md5(
1670            &md5_concat(
1671                &key,
1672                b"session key to server-to-client signing key magic constant\0",
1673            ),
1674            &[&0u32.to_le_bytes(), b"message"],
1675        );
1676        assert_eq!(sig[4..12], expected[..8]);
1677    }
1678}