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> {
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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
497pub enum Identity {
498 Anonymous,
499 User { user: String, domain: String },
500}
501
502#[derive(Debug, Clone)]
504pub struct AuthOutcome {
505 pub identity: Identity,
506 pub session_key: [u8; 16],
507}
508
509#[derive(Debug, Clone)]
511pub struct UserCreds {
512 pub nt_hash: [u8; 16],
513}
514
515impl UserCreds {
516 pub fn from_password(password: &str) -> Self {
518 Self {
519 nt_hash: nt_hash(password),
520 }
521 }
522
523 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
556pub 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 server_flags: u32,
573 negotiated_flags: u32,
575
576 negotiate_bytes: Vec<u8>,
578 challenge_bytes: Vec<u8>,
580}
581
582impl NtlmServer {
583 pub fn new(server_challenge: [u8; 8], target: NtlmTargetInfo, timestamp: u64) -> Self {
585 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 pub fn step1_negotiate(&mut self, blob: &[u8]) -> ProtoResult<NtlmNegotiate> {
617 let n = NtlmNegotiate::parse(blob)?;
618 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 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 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 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 let creds = lookup(&auth.user, &auth.domain).ok_or(ProtoError::Auth("unknown user"))?;
668
669 let response_key_nt = ntowf_v2(&creds.nt_hash, &auth.user, &auth.domain);
671
672 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 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 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 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 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 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#[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 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 buf.extend_from_slice(&[0u8; 8]);
783 buf.extend_from_slice(&[0u8; 8]);
784 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 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 assert_eq!(&blob[24..32], &[1, 2, 3, 4, 5, 6, 7, 8]);
815 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 #[test]
837 fn ntlmv2_known_answer() {
838 let nt = nt_hash("Password");
839 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 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 let client_challenge_blob: &[u8] = &[
862 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,
869 0x00, 0x01, 0x00, 0x0c, 0x00, 0x53, 0x00, 0x65, 0x00, 0x72, 0x00, 0x76, 0x00, 0x65, 0x00, 0x72,
872 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
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 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 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 let _challenge = srv.challenge();
910
911 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 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 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 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 let mut buf = Vec::new();
954 buf.extend_from_slice(NTLMSSP_SIGNATURE);
955 buf.extend_from_slice(&MSG_AUTHENTICATE.to_le_bytes());
956 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 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 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 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 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 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 buf.extend_from_slice(&flags::NTLMSSP_NEGOTIATE_UNICODE.to_le_bytes());
982 buf.extend_from_slice(&[0u8; 8]);
984 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 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 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 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]); 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}