Skip to main content

smb_server/proto/auth/
ntlm.rs

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