1use 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
26pub 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
35pub 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#[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#[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
89pub 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 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#[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 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
132pub 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
143fn 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
152pub 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
162pub 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
175fn 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#[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#[derive(Debug, Clone, Default)]
234pub struct NtlmNegotiate {
235 pub flags: u32,
236 pub domain: Vec<u8>,
237 pub workstation: Vec<u8>,
238 pub raw: Vec<u8>,
240}
241
242impl NtlmNegotiate {
243 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 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#[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 pub timestamp: u64,
298 pub flags: u32,
300}
301
302pub 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 out.extend_from_slice(NTLMSSP_SIGNATURE);
335 out.extend_from_slice(&MSG_CHALLENGE.to_le_bytes());
337 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 out.extend_from_slice(&p.flags.to_le_bytes());
344 out.extend_from_slice(&p.server_challenge);
346 out.extend_from_slice(&[0u8; 8]);
348 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 out.extend_from_slice(&[6, 1, 0, 0x1D, 0, 0, 0, 0x0F]);
356 out.extend_from_slice(&target_name_utf16);
358 out.extend_from_slice(&target_info);
359 out
360}
361
362#[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 pub mic: Option<[u8; 16]>,
377 pub mic_offset: Option<usize>,
379 pub raw: Vec<u8>,
381}
382
383impl NtlmAuthenticate {
384 pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
406 check_signature(buf, MSG_AUTHENTICATE)?;
407 if buf.len() < 64 {
408 return Err(ProtoError::Auth("AUTHENTICATE_MESSAGE too short"));
409 }
410 let lm_field = read_field(buf, 12)?;
411 let nt_field = read_field(buf, 20)?;
412 let domain_field = read_field(buf, 28)?;
413 let user_field = read_field(buf, 36)?;
414 let ws_field = read_field(buf, 44)?;
415 let key_field = read_field(buf, 52)?;
416 let flags = u32::from_le_bytes([buf[60], buf[61], buf[62], buf[63]]);
417
418 let mut min_off: u32 = u32::MAX;
421 for f in [
422 lm_field,
423 nt_field,
424 domain_field,
425 user_field,
426 ws_field,
427 key_field,
428 ] {
429 if f.len > 0 && f.offset > 0 && f.offset < min_off {
430 min_off = f.offset;
431 }
432 }
433
434 let (mic, mic_offset) = if min_off != u32::MAX && min_off as usize >= 88 && buf.len() >= 88
435 {
436 let mut mic = [0u8; 16];
437 mic.copy_from_slice(&buf[72..88]);
438 (Some(mic), Some(72usize))
439 } else {
440 (None, None)
441 };
442
443 let lm_response = if lm_field.len == 0 {
444 Vec::new()
445 } else {
446 slice_field(buf, lm_field)?.to_vec()
447 };
448 let nt_response = if nt_field.len == 0 {
449 Vec::new()
450 } else {
451 slice_field(buf, nt_field)?.to_vec()
452 };
453 let domain_bytes = if domain_field.len == 0 {
454 Vec::new()
455 } else {
456 slice_field(buf, domain_field)?.to_vec()
457 };
458 let user_bytes = if user_field.len == 0 {
459 Vec::new()
460 } else {
461 slice_field(buf, user_field)?.to_vec()
462 };
463 let ws_bytes = if ws_field.len == 0 {
464 Vec::new()
465 } else {
466 slice_field(buf, ws_field)?.to_vec()
467 };
468 let encrypted_random_session_key = if key_field.len == 0 {
469 Vec::new()
470 } else {
471 slice_field(buf, key_field)?.to_vec()
472 };
473
474 let domain = utf16le_to_string(&domain_bytes);
477 let user = utf16le_to_string(&user_bytes);
478 let workstation = utf16le_to_string(&ws_bytes);
479
480 Ok(Self {
481 flags,
482 lm_response,
483 nt_response,
484 domain,
485 user,
486 workstation,
487 encrypted_random_session_key,
488 mic,
489 mic_offset,
490 raw: buf.to_vec(),
491 })
492 }
493}
494
495#[derive(Debug, Clone, PartialEq, Eq)]
499pub enum Identity {
500 Anonymous,
501 User { user: String, domain: String },
502}
503
504#[derive(Debug, Clone)]
506pub struct AuthOutcome {
507 pub identity: Identity,
508 pub session_key: [u8; 16],
509}
510
511#[derive(Debug, Clone)]
515pub struct UserCreds {
516 pub nt_hash: [u8; 16],
517}
518
519impl UserCreds {
520 pub fn from_password(password: &str) -> Self {
522 Self {
523 nt_hash: nt_hash(password),
524 }
525 }
526
527 pub fn from_nt_hash(nt_hash: [u8; 16]) -> Self {
529 Self { nt_hash }
530 }
531}
532
533#[derive(Debug, Clone)]
534pub struct NtlmTargetInfo {
535 pub target_name: String,
536 pub nb_domain: String,
537 pub nb_computer: String,
538 pub dns_domain: String,
539 pub dns_computer: String,
540}
541
542impl NtlmTargetInfo {
543 pub fn new(
544 target_name: impl Into<String>,
545 nb_domain: impl Into<String>,
546 nb_computer: impl Into<String>,
547 dns_domain: impl Into<String>,
548 dns_computer: impl Into<String>,
549 ) -> Self {
550 Self {
551 target_name: target_name.into(),
552 nb_domain: nb_domain.into(),
553 nb_computer: nb_computer.into(),
554 dns_domain: dns_domain.into(),
555 dns_computer: dns_computer.into(),
556 }
557 }
558}
559
560pub struct NtlmServer {
568 server_challenge: [u8; 8],
569 target_name: String,
570 nb_domain: String,
571 nb_computer: String,
572 dns_domain: String,
573 dns_computer: String,
574 timestamp: u64,
575 server_flags: u32,
577 negotiated_flags: u32,
579
580 negotiate_bytes: Vec<u8>,
582 challenge_bytes: Vec<u8>,
584}
585
586impl NtlmServer {
587 pub fn new(server_challenge: [u8; 8], target: NtlmTargetInfo, timestamp: u64) -> Self {
589 let server_flags = flags::NTLMSSP_NEGOTIATE_UNICODE
591 | flags::NTLMSSP_REQUEST_TARGET
592 | flags::NTLMSSP_NEGOTIATE_NTLM
593 | flags::NTLMSSP_NEGOTIATE_SIGN
594 | flags::NTLMSSP_NEGOTIATE_ALWAYS_SIGN
595 | flags::NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
596 | flags::NTLMSSP_TARGET_TYPE_SERVER
597 | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
598 | flags::NTLMSSP_NEGOTIATE_VERSION
599 | flags::NTLMSSP_NEGOTIATE_128
600 | flags::NTLMSSP_NEGOTIATE_KEY_EXCH
601 | flags::NTLMSSP_NEGOTIATE_56;
602
603 Self {
604 server_challenge,
605 target_name: target.target_name,
606 nb_domain: target.nb_domain,
607 nb_computer: target.nb_computer,
608 dns_domain: target.dns_domain,
609 dns_computer: target.dns_computer,
610 timestamp,
611 server_flags,
612 negotiated_flags: server_flags,
613 negotiate_bytes: Vec::new(),
614 challenge_bytes: Vec::new(),
615 }
616 }
617
618 pub fn step1_negotiate(&mut self, blob: &[u8]) -> ProtoResult<NtlmNegotiate> {
621 let n = NtlmNegotiate::parse(blob)?;
622 self.negotiated_flags = (self.server_flags & n.flags)
624 | flags::NTLMSSP_NEGOTIATE_TARGET_INFO
625 | flags::NTLMSSP_TARGET_TYPE_SERVER
626 | flags::NTLMSSP_NEGOTIATE_UNICODE;
627 self.negotiate_bytes = n.raw.clone();
628 Ok(n)
629 }
630
631 pub fn challenge(&mut self) -> Vec<u8> {
633 let blob = build_challenge(&ChallengeParams {
634 server_challenge: self.server_challenge,
635 target_name: &self.target_name,
636 nb_domain_name: &self.nb_domain,
637 nb_computer_name: &self.nb_computer,
638 dns_domain_name: &self.dns_domain,
639 dns_computer_name: &self.dns_computer,
640 timestamp: self.timestamp,
641 flags: self.negotiated_flags,
642 });
643 self.challenge_bytes = blob.clone();
644 blob
645 }
646
647 pub fn authenticate<F>(&self, blob: &[u8], lookup: F) -> ProtoResult<AuthOutcome>
656 where
657 F: Fn(&str, &str) -> Option<UserCreds>,
658 {
659 let auth = NtlmAuthenticate::parse(blob)?;
660
661 if auth.user.is_empty() && auth.nt_response.is_empty() {
664 return Ok(AuthOutcome {
665 identity: Identity::Anonymous,
666 session_key: [0u8; 16],
667 });
668 }
669
670 let creds = lookup(&auth.user, &auth.domain).ok_or(ProtoError::Auth("unknown user"))?;
672
673 let response_key_nt = ntowf_v2(&creds.nt_hash, &auth.user, &auth.domain);
675
676 if auth.nt_response.len() < 16 {
679 return Err(ProtoError::Auth("NT response too short"));
680 }
681 let (nt_proof_supplied, client_challenge) = auth.nt_response.split_at(16);
682
683 let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
685 mac.update(&self.server_challenge);
686 mac.update(client_challenge);
687 let nt_proof_computed = mac.finalize().into_bytes();
688
689 if !ct_eq_16(nt_proof_supplied, &nt_proof_computed) {
690 return Err(ProtoError::Auth("NT proof mismatch"));
691 }
692
693 let mut mac = HmacMd5::new_from_slice(&response_key_nt).expect("hmac key");
696 mac.update(&nt_proof_computed);
697 let session_base_key_bytes = mac.finalize().into_bytes();
698 let mut key_exchange_key = [0u8; 16];
699 key_exchange_key.copy_from_slice(&session_base_key_bytes);
700
701 let session_key = if (auth.flags & flags::NTLMSSP_NEGOTIATE_KEY_EXCH) != 0
703 && !auth.encrypted_random_session_key.is_empty()
704 {
705 if auth.encrypted_random_session_key.len() != 16 {
706 return Err(ProtoError::Auth("encrypted session key not 16 bytes"));
707 }
708 let mut buf = [0u8; 16];
709 buf.copy_from_slice(&auth.encrypted_random_session_key);
710 let mut rc4 = Rc4::new_from_slice(&key_exchange_key)
712 .map_err(|_| ProtoError::Auth("rc4 key length"))?;
713 rc4.apply_keystream(&mut buf);
714 buf
715 } else {
716 key_exchange_key
717 };
718
719 if let (Some(mic_off), true) = (auth.mic_offset, !self.negotiate_bytes.is_empty())
725 && let Some(supplied) = auth.mic
726 {
727 let mut auth_zeroed = auth.raw.clone();
728 if auth_zeroed.len() < mic_off + 16 {
729 return Err(ProtoError::Auth("MIC offset out of range"));
730 }
731 for b in &mut auth_zeroed[mic_off..mic_off + 16] {
732 *b = 0;
733 }
734 let mut mac = HmacMd5::new_from_slice(&session_key).expect("hmac key");
735 mac.update(&self.negotiate_bytes);
736 mac.update(&self.challenge_bytes);
737 mac.update(&auth_zeroed);
738 let computed = mac.finalize().into_bytes();
739 if !ct_eq_16(&supplied, &computed) {
740 return Err(ProtoError::Auth("MIC mismatch"));
741 }
742 }
743
744 Ok(AuthOutcome {
745 identity: Identity::User {
746 user: auth.user.clone(),
747 domain: auth.domain.clone(),
748 },
749 session_key,
750 })
751 }
752}
753
754#[cfg(test)]
759mod tests {
760 use super::*;
761
762 #[test]
763 fn av_pair_round_trip() {
764 let pairs = vec![
765 AvPair::new(AvId::NbDomainName, utf16le("DOMAIN")),
766 AvPair::new(AvId::NbComputerName, utf16le("SERVER")),
767 AvPair::new(
768 AvId::Timestamp,
769 0x1234_5678_9abc_def0u64.to_le_bytes().to_vec(),
770 ),
771 ];
772 let bytes = encode_av_pairs(&pairs);
773 let decoded = decode_av_pairs(&bytes).unwrap();
774 assert_eq!(decoded, pairs);
775 }
776
777 #[test]
778 fn negotiate_round_trip() {
779 let mut buf = Vec::new();
781 buf.extend_from_slice(NTLMSSP_SIGNATURE);
782 buf.extend_from_slice(&MSG_NEGOTIATE.to_le_bytes());
783 let flags = flags::NTLMSSP_NEGOTIATE_UNICODE
784 | flags::NTLMSSP_NEGOTIATE_NTLM
785 | flags::NTLMSSP_NEGOTIATE_TARGET_INFO;
786 buf.extend_from_slice(&flags.to_le_bytes());
787 buf.extend_from_slice(&[0u8; 8]);
789 buf.extend_from_slice(&[0u8; 8]);
790 buf.extend_from_slice(&[0u8; 8]);
792
793 let n = NtlmNegotiate::parse(&buf).unwrap();
794 assert_eq!(n.flags, flags);
795 assert!(n.domain.is_empty());
796 assert!(n.workstation.is_empty());
797 }
798
799 #[test]
800 fn challenge_round_trip_structure() {
801 let blob = build_challenge(&ChallengeParams {
802 server_challenge: [1, 2, 3, 4, 5, 6, 7, 8],
803 target_name: "SERVER",
804 nb_domain_name: "DOMAIN",
805 nb_computer_name: "SERVER",
806 dns_domain_name: "domain.local",
807 dns_computer_name: "server.domain.local",
808 timestamp: 0,
809 flags: flags::NTLMSSP_NEGOTIATE_UNICODE
810 | flags::NTLMSSP_NEGOTIATE_NTLM
811 | flags::NTLMSSP_NEGOTIATE_TARGET_INFO,
812 });
813 assert_eq!(&blob[..8], NTLMSSP_SIGNATURE);
815 assert_eq!(
816 u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]),
817 MSG_CHALLENGE
818 );
819 assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
821 let ti_off = u32::from_le_bytes([blob[44], blob[45], blob[46], blob[47]]) as usize;
823 let ti_len = u16::from_le_bytes([blob[40], blob[41]]) as usize;
824 let av = decode_av_pairs(&blob[ti_off..ti_off + ti_len]).unwrap();
825 assert!(av.iter().any(|p| p.id == AvId::NbDomainName as u16));
826 assert!(av.iter().any(|p| p.id == AvId::Timestamp as u16));
827 }
828
829 #[test]
846 fn ntlmv2_known_answer() {
847 let nt = nt_hash("Password");
848 assert_eq!(
850 nt,
851 [
852 0xa4, 0xf4, 0x9c, 0x40, 0x65, 0x10, 0xbd, 0xca, 0xb6, 0x82, 0x4e, 0xe7, 0xc3, 0x0f,
853 0xd8, 0x52
854 ]
855 );
856
857 let key_nt = ntowf_v2(&nt, "User", "Domain");
860 assert_eq!(
861 key_nt,
862 [
863 0x0c, 0x86, 0x8a, 0x40, 0x3b, 0xfd, 0x7a, 0x93, 0xa3, 0x00, 0x1e, 0xf2, 0x2e, 0xf0,
864 0x2e, 0x3f
865 ]
866 );
867
868 let server_challenge: [u8; 8] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
869 let client_challenge_blob: &[u8] = &[
871 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x0c, 0x00, 0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e,
878 0x00, 0x01, 0x00, 0x0c, 0x00, 0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
881 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
885
886 let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
887 mac.update(&server_challenge);
888 mac.update(client_challenge_blob);
889 let nt_proof = mac.finalize().into_bytes();
890
891 assert_eq!(
894 nt_proof.as_slice(),
895 [
896 0x68, 0xcd, 0x0a, 0xb8, 0x51, 0xe5, 0x1c, 0x96, 0xaa, 0xbc, 0x92, 0x7b, 0xeb, 0xef,
897 0x6a, 0x1c
898 ]
899 );
900 }
901
902 #[test]
903 fn server_round_trip_authenticates_user() {
904 let mut srv = NtlmServer::new(
907 [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
908 NtlmTargetInfo::new(
909 "SERVER",
910 "DOMAIN",
911 "SERVER",
912 "domain.local",
913 "server.domain.local",
914 ),
915 0,
916 );
917 let _challenge = srv.challenge();
919
920 let nt = nt_hash("Password");
922 let key_nt = ntowf_v2(&nt, "User", "Domain");
923 let client_challenge_blob: Vec<u8> = vec![
924 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
925 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00,
926 0x00, 0x00, 0x00, 0x00,
928 ];
929 let mut mac = HmacMd5::new_from_slice(&key_nt).unwrap();
930 mac.update(&[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
931 mac.update(&client_challenge_blob);
932 let nt_proof = mac.finalize().into_bytes();
933
934 let mut nt_response = Vec::new();
935 nt_response.extend_from_slice(&nt_proof);
936 nt_response.extend_from_slice(&client_challenge_blob);
937
938 let user_u16 = utf16le("User");
940 let dom_u16 = utf16le("Domain");
941 let ws_u16 = utf16le("CLIENT");
942 let lm_response: Vec<u8> = vec![0u8; 24];
943
944 let header_len: u32 = 72;
948 let mut payload = Vec::new();
949 let lm_off = header_len;
950 payload.extend_from_slice(&lm_response);
951 let nt_off = header_len + payload.len() as u32;
952 payload.extend_from_slice(&nt_response);
953 let dom_off = header_len + payload.len() as u32;
954 payload.extend_from_slice(&dom_u16);
955 let user_off = header_len + payload.len() as u32;
956 payload.extend_from_slice(&user_u16);
957 let ws_off = header_len + payload.len() as u32;
958 payload.extend_from_slice(&ws_u16);
959 let key_off = header_len + payload.len() as u32;
960 let mut buf = Vec::new();
963 buf.extend_from_slice(NTLMSSP_SIGNATURE);
964 buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
965 buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
967 buf.extend_from_slice(&(lm_response.len() as u16).to_le_bytes());
968 buf.extend_from_slice(&lm_off.to_le_bytes());
969 buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
971 buf.extend_from_slice(&(nt_response.len() as u16).to_le_bytes());
972 buf.extend_from_slice(&nt_off.to_le_bytes());
973 buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
975 buf.extend_from_slice(&(dom_u16.len() as u16).to_le_bytes());
976 buf.extend_from_slice(&dom_off.to_le_bytes());
977 buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
979 buf.extend_from_slice(&(user_u16.len() as u16).to_le_bytes());
980 buf.extend_from_slice(&user_off.to_le_bytes());
981 buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
983 buf.extend_from_slice(&(ws_u16.len() as u16).to_le_bytes());
984 buf.extend_from_slice(&ws_off.to_le_bytes());
985 buf.extend_from_slice(&0u16.to_le_bytes());
987 buf.extend_from_slice(&0u16.to_le_bytes());
988 buf.extend_from_slice(&key_off.to_le_bytes());
989 buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
991 buf.extend_from_slice(&[0u8; 8]);
993 assert_eq!(buf.len() as u32, header_len);
995 buf.extend_from_slice(&payload);
996
997 let creds = UserCreds::from_password("Password");
998 let outcome = srv
999 .authenticate(&buf, |u, d| {
1000 if u == "User" && d == "Domain" {
1001 Some(creds.clone())
1002 } else {
1003 None
1004 }
1005 })
1006 .expect("auth should succeed");
1007
1008 assert_eq!(
1009 outcome.identity,
1010 Identity::User {
1011 user: "User".to_string(),
1012 domain: "Domain".to_string()
1013 }
1014 );
1015
1016 let bad = UserCreds::from_password("WrongPassword");
1018 let err = srv
1019 .authenticate(&buf, |_u, _d| Some(bad.clone()))
1020 .unwrap_err();
1021 assert!(matches!(err, ProtoError::Auth(_)));
1022 }
1023
1024 #[test]
1025 fn anonymous_logon() {
1026 let mut srv = NtlmServer::new(
1027 [0u8; 8],
1028 NtlmTargetInfo::new("SERVER", "DOMAIN", "SERVER", "d.local", "s.d.local"),
1029 0,
1030 );
1031 let _ = srv.challenge();
1032
1033 let header_len: u32 = 72;
1035 let mut buf = Vec::new();
1036 buf.extend_from_slice(NTLMSSP_SIGNATURE);
1037 buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
1038 for _ in 0..6 {
1039 buf.extend_from_slice(&0u16.to_le_bytes());
1041 buf.extend_from_slice(&0u16.to_le_bytes());
1042 buf.extend_from_slice(&header_len.to_le_bytes());
1043 }
1044 buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_ANONYMOUS.to_le_bytes());
1045 buf.extend_from_slice(&[0u8; 8]); let outcome = srv
1048 .authenticate(&buf, |_u, _d| None)
1049 .expect("anonymous should succeed");
1050 assert_eq!(outcome.identity, Identity::Anonymous);
1051 assert_eq!(outcome.session_key, [0u8; 16]);
1052 }
1053}