ms-pkca 0.1.0-dev

PKINIT (RFC 4556) client — PA-PK-AS-REQ / PA-PK-AS-REP with X.509 cert + UnPAC-the-hash (pre-alpha)
Documentation
//! PAC_CREDENTIAL_INFO parsing — the "UnPAC-the-hash" primitive.
//!
//! [MS-PAC] §2.6 defines PAC_CREDENTIAL_INFO as:
//!
//!   ULONG   Version                   (must be 0)
//!   ULONG   EncryptionType            (Kerberos etype of SerializedData)
//!   BYTE    SerializedData[]          (encrypted NDR marshalling of
//!                                      PAC_CREDENTIAL_DATA)
//!
//! `PAC_CREDENTIAL_DATA` is a `KERB_VALIDATION_INFO`-adjacent NDR structure
//! carrying `SECPKG_SUPPLEMENTAL_CRED[]`, from which we pluck the NTLM
//! supplemental package's `NTOWFv1` (16-byte NT hash) — that's the value the
//! UnPAC-the-hash technique exfiltrates when the KDC returns credentials in
//! the PAC because the client authenticated over PKINIT.
//!
//! **STATUS 0.1.0-dev**:
//!   * Parses the fixed 8-byte PAC_CREDENTIAL_INFO prefix.
//!   * Extracts a NT hash from a **decrypted, NDR-marshalled**
//!     PAC_CREDENTIAL_DATA — using a *heuristic search* for the
//!     `NTLM_SUPPLEMENTAL_CREDENTIAL` structure rather than a full NDR
//!     unmarshaller.  This is enough for real UnPAC-the-hash payloads
//!     observed in the wild (Windows always emits the same layout for
//!     `SECPKG_SUPPLEMENTAL_CRED_ARRAY` with a single NTLM entry) but
//!     will need a proper NDR parser in 0.2.
//!
//! Decryption is delegated to the caller — the AS-REP session key + etype
//! come from the outer Kerberos stack and are outside this crate's scope
//! for 0.1.0-dev.

use crate::error::{Error, Result};

/// Parsed PAC_CREDENTIAL_INFO header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PacCredentialInfo<'a> {
    pub version: u32,
    pub etype: u32,
    /// Encrypted PAC_CREDENTIAL_DATA blob — hand this to the Kerberos crypto
    /// layer with the AS-REP session key to obtain the plaintext.
    pub encrypted: &'a [u8],
}

impl<'a> PacCredentialInfo<'a> {
    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
        if bytes.len() < 8 {
            return Err(Error::PacParse("PAC_CREDENTIAL_INFO < 8 bytes".into()));
        }
        let version = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
        let etype = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
        if version != 0 {
            return Err(Error::PacParse(format!(
                "PAC_CREDENTIAL_INFO version = {} (expected 0)",
                version
            )));
        }
        Ok(Self {
            version,
            etype,
            encrypted: &bytes[8..],
        })
    }
}

/// Extract a 16-byte NT hash (NTOWFv1) from a decrypted PAC_CREDENTIAL_DATA blob.
///
/// The blob is NDR-marshalled `PAC_CREDENTIAL_DATA` → `SECPKG_SUPPLEMENTAL_CRED[]`
/// with (in the wild) a single entry named "NTLM" whose Credentials field is
/// `NTLM_SUPPLEMENTAL_CREDENTIAL { Version=0, Flags, LmPassword[16], NtPassword[16] }`.
///
/// This implementation performs a bounded structural search for the fixed
/// signature of the NTLM package name (UTF-16LE "NTLM") followed by the
/// standard NDR alignment padding and a `Version=0` NTLM_SUPPLEMENTAL_CREDENTIAL
/// header.  It returns the NtPassword field.
///
/// Returns `Error::PacParse` if no NT hash can be located.
pub fn extract_nt_hash_from_credential_data(decrypted: &[u8]) -> Result<[u8; 16]> {
    // NTLM package name in UTF-16LE: N\0T\0L\0M\0
    const NTLM_UTF16: &[u8] = b"N\0T\0L\0M\0";
    let mut pos = 0usize;
    while pos + NTLM_UTF16.len() < decrypted.len() {
        if &decrypted[pos..pos + NTLM_UTF16.len()] == NTLM_UTF16 {
            // After the package-name string there's NDR alignment (up to 8 bytes),
            // then a conformant-array length (4 bytes), then the
            // NTLM_SUPPLEMENTAL_CREDENTIAL:
            //   ULONG Version              (0)
            //   ULONG Flags                (bit0=LM present, bit1=NT present)
            //   BYTE  LmPassword[16]
            //   BYTE  NtPassword[16]
            //
            // Scan forward within a bounded window for a `Version=0`, `Flags`
            // with bit 1 set, then take the following 16 bytes at offset +40.
            let window_end = (pos + 256).min(decrypted.len());
            let mut scan = pos + NTLM_UTF16.len();
            while scan + 40 <= window_end {
                let version = u32::from_le_bytes(decrypted[scan..scan + 4].try_into().unwrap());
                let flags = u32::from_le_bytes(decrypted[scan + 4..scan + 8].try_into().unwrap());
                if version == 0 && (flags & 0x2) != 0 {
                    // NT hash sits at offset +24 (skip Version(4) + Flags(4) + LM(16))
                    let nt_off = scan + 24;
                    if nt_off + 16 <= decrypted.len() {
                        let mut out = [0u8; 16];
                        out.copy_from_slice(&decrypted[nt_off..nt_off + 16]);
                        return Ok(out);
                    }
                }
                scan += 4;
            }
        }
        pos += 1;
    }
    Err(Error::PacParse(
        "no NTLM_SUPPLEMENTAL_CREDENTIAL located in PAC_CREDENTIAL_DATA".into(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_credential_info_header() {
        // Version=0, EType=18 (aes256-cts-hmac-sha1-96), 4 bytes payload.
        let mut blob = Vec::new();
        blob.extend_from_slice(&0u32.to_le_bytes());
        blob.extend_from_slice(&18u32.to_le_bytes());
        blob.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]);
        let info = PacCredentialInfo::parse(&blob).unwrap();
        assert_eq!(info.version, 0);
        assert_eq!(info.etype, 18);
        assert_eq!(info.encrypted, &[0xAA, 0xBB, 0xCC, 0xDD]);
    }

    #[test]
    fn rejects_bad_version() {
        let mut blob = Vec::new();
        blob.extend_from_slice(&1u32.to_le_bytes());
        blob.extend_from_slice(&18u32.to_le_bytes());
        blob.push(0);
        assert!(PacCredentialInfo::parse(&blob).is_err());
    }

    #[test]
    fn extract_nt_hash_from_synthetic_blob() {
        // Simulated: some padding, "NTLM" UTF-16, alignment, then
        // Version=0, Flags=0x3 (LM+NT), LM=00..00, NT=11..22 (interesting bytes).
        let mut blob = vec![0u8; 32]; // arbitrary NDR header noise
        blob.extend_from_slice(b"N\0T\0L\0M\0");
        blob.extend_from_slice(&[0u8; 4]); // alignment / array-length placeholder
        blob.extend_from_slice(&0u32.to_le_bytes()); // Version
        blob.extend_from_slice(&0x3u32.to_le_bytes()); // Flags
        blob.extend_from_slice(&[0u8; 16]); // LmPassword
        let expected: [u8; 16] = [
            0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
            0xff, 0x00,
        ];
        blob.extend_from_slice(&expected);
        blob.extend_from_slice(&[0u8; 8]); // trailing NDR padding

        let got = extract_nt_hash_from_credential_data(&blob).unwrap();
        assert_eq!(got, expected);
    }
}