ms-nrpc 0.1.0-dev

MS-NRPC (Netlogon) secure-channel setup + read-only Zerologon (CVE-2020-1472) detection. Defensive-only: destructive exploit/restore paths are deliberately excluded.
Documentation
//! MS-NRPC secure-channel primitives: interface identity, opnums, NDR encoders
//! for the two calls needed to reach the Zerologon decision point, plus the
//! AES-128-CFB8 credential cipher and HMAC-SHA256 session-key derivation.
//!
//! Everything here is **non-destructive**. The only calls encoded are
//! `NetrServerReqChallenge` (opnum 4) and `NetrServerAuthenticate3`
//! (opnum 26); the password-set opnums are intentionally absent.

use dcerpc::ndr::NdrEncoder;
use dcerpc::Syntax;

/// MS-NRPC interface UUID reachable over `ncacn_ip_tcp` via the endpoint mapper.
pub fn netlogon_syntax() -> Syntax {
    Syntax::new("12345678-1234-abcd-ef00-01234567cffb", 1, 0)
}

/// Netlogon opnums exposed by this crate. Only the two needed for detection
/// are here; password-set opnums are omitted on purpose.
pub mod opnum {
    /// `NetrServerReqChallenge`.
    pub const REQ_CHALLENGE: u16 = 4;
    /// `NetrServerAuthenticate3`.
    pub const AUTHENTICATE3: u16 = 26;
}

/// NT OWF of an empty password (MD4 of ""), useful for callers that need to
/// derive a session key against a machine account whose password is empty.
/// Kept public because it is public knowledge and the derivation math in
/// [`session_key`] is testable against it.
pub const EMPTY_NT_OWF: [u8; 16] = [
    0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0,
];

/// `NETLOGON_SECURE_CHANNEL_TYPE::ServerSecureChannel` — DC-to-DC.
pub const SERVER_SECURE_CHANNEL: u16 = 6;

/// Negotiate flags including the AES support bit (`0x0100_0000`) that selects
/// the AES-CFB8 credential path required for the Zerologon check.
pub const NEG_FLAGS: u32 = 0x212f_ffff;

/// `STATUS_SUCCESS` — a `NetrServerAuthenticate3` reply carrying this trailing
/// NTSTATUS means the DC accepted the credential.
pub const STATUS_SUCCESS: u32 = 0x0000_0000;

/// AES-128-CFB8 encryption with a zero IV (MS-NRPC AES credential + password
/// encryption). Stream-cipher construction: each ciphertext byte is the XOR
/// of the plaintext byte with the top byte of `AES_ENC(key, IV)`, then the IV
/// is shifted left by one byte with the new ciphertext byte appended.
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
}

/// AES Netlogon session key per MS-NRPC 3.1.4.3.1:
/// `HMAC-SHA256(NTOWF, ClientChallenge || ServerChallenge)[..16]`.
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
}

/// Encode `NetrServerReqChallenge(PrimaryName[unique,str], ComputerName[str],
/// ClientChallenge[8])` into an NDR stub.
pub fn encode_req_challenge(netbios: &str, client_challenge: &[u8; 8]) -> Vec<u8> {
    let mut e = NdrEncoder::new();
    e.referent(); // PrimaryName (unique, non-null)
    e.conformant_varying_wstr(netbios);
    e.align(4);
    e.conformant_varying_wstr(netbios); // ComputerName (ref, inline)
    e.align(4);
    e.bytes(client_challenge); // NETLOGON_CREDENTIAL
    e.into_bytes()
}

/// Encode `NetrServerAuthenticate3(PrimaryName[unique,str], AccountName[str],
/// SecureChannelType, ComputerName[str], ClientCredential[8],
/// NegotiateFlags[in,out])` into an NDR stub. `AccountName` is derived as
/// `"{netbios}$"` per Netlogon convention for the machine account.
pub fn encode_authenticate3(netbios: &str, client_cred: &[u8; 8]) -> Vec<u8> {
    let account = format!("{netbios}$");
    let mut e = NdrEncoder::new();
    e.referent(); // PrimaryName (unique)
    e.conformant_varying_wstr(netbios);
    e.align(4);
    e.conformant_varying_wstr(&account); // AccountName (ref)
    e.align(2);
    e.u16(SERVER_SECURE_CHANNEL); // SecureChannelType (enum, 2 bytes)
    e.align(4);
    e.conformant_varying_wstr(netbios); // ComputerName (ref)
    e.align(4);
    e.bytes(client_cred); // ClientCredential
    e.u32(NEG_FLAGS); // NegotiateFlags [in,out]
    e.into_bytes()
}

/// Read the trailing NTSTATUS of a Netlogon reply (last 4 bytes of the stub).
/// Returns `0xFFFF_FFFF` when the stub is shorter than 4 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]);
        // PrimaryName referent (non-null) then the conformant wstr max_count = len("DC01")+1 = 5.
        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);
        // Ends with the 8-byte client challenge.
        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);
    }
}