use dcerpc::ndr::NdrEncoder;
use dcerpc::Syntax;
pub fn netlogon_syntax() -> Syntax {
Syntax::new("12345678-1234-abcd-ef00-01234567cffb", 1, 0)
}
pub mod opnum {
pub const REQ_CHALLENGE: u16 = 4;
pub const AUTHENTICATE3: u16 = 26;
}
pub const EMPTY_NT_OWF: [u8; 16] = [
0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0,
];
pub const SERVER_SECURE_CHANNEL: u16 = 6;
pub const NEG_FLAGS: u32 = 0x212f_ffff;
pub const STATUS_SUCCESS: u32 = 0x0000_0000;
pub fn aes_cfb8_encrypt(key: &[u8; 16], data: &[u8]) -> Vec<u8> {
use aes::cipher::{BlockEncrypt, KeyInit};
let cipher = aes::Aes128::new(aes::cipher::generic_array::GenericArray::from_slice(key));
let mut iv = [0u8; 16];
let mut out = Vec::with_capacity(data.len());
for &b in data {
let mut block = aes::cipher::generic_array::GenericArray::clone_from_slice(&iv);
cipher.encrypt_block(&mut block);
let c = b ^ block[0];
out.push(c);
iv.copy_within(1..16, 0);
iv[15] = c;
}
out
}
pub fn session_key(nt_owf: &[u8; 16], client_ch: &[u8; 8], server_ch: &[u8; 8]) -> [u8; 16] {
use hmac::Mac;
let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(nt_owf).expect("hmac key");
mac.update(client_ch);
mac.update(server_ch);
let r = mac.finalize().into_bytes();
let mut k = [0u8; 16];
k.copy_from_slice(&r[..16]);
k
}
pub fn encode_req_challenge(netbios: &str, client_challenge: &[u8; 8]) -> Vec<u8> {
let mut e = NdrEncoder::new();
e.referent(); e.conformant_varying_wstr(netbios);
e.align(4);
e.conformant_varying_wstr(netbios); e.align(4);
e.bytes(client_challenge); e.into_bytes()
}
pub fn encode_authenticate3(netbios: &str, client_cred: &[u8; 8]) -> Vec<u8> {
let account = format!("{netbios}$");
let mut e = NdrEncoder::new();
e.referent(); e.conformant_varying_wstr(netbios);
e.align(4);
e.conformant_varying_wstr(&account); e.align(2);
e.u16(SERVER_SECURE_CHANNEL); e.align(4);
e.conformant_varying_wstr(netbios); e.align(4);
e.bytes(client_cred); e.u32(NEG_FLAGS); e.into_bytes()
}
pub fn ret_status(stub: &[u8]) -> u32 {
stub.get(stub.len().wrapping_sub(4)..)
.and_then(|b| b.try_into().ok())
.map(u32::from_le_bytes)
.unwrap_or(0xFFFF_FFFF)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn syntax_uuid() {
let s = netlogon_syntax();
assert_eq!(s.ver_major, 1);
}
#[test]
fn req_challenge_layout() {
let b = encode_req_challenge("DC01", &[0u8; 8]);
assert_ne!(u32::from_le_bytes(b[0..4].try_into().unwrap()), 0);
assert_eq!(u32::from_le_bytes(b[4..8].try_into().unwrap()), 5);
assert_eq!(&b[b.len() - 8..], &[0u8; 8]);
}
#[test]
fn authenticate3_ends_with_flags() {
let b = encode_authenticate3("DC01", &[0u8; 8]);
assert_eq!(&b[b.len() - 4..], &NEG_FLAGS.to_le_bytes());
}
#[test]
fn ret_status_reads_tail() {
assert_eq!(ret_status(&[0, 0, 0, 0, 0, 0, 0, 0]), 0);
assert_eq!(ret_status(&0xC000_0022u32.to_le_bytes()), 0xC000_0022);
}
}