Skip to main content

ms_csra/
lib.rs

1//! **ms-csra** — MS-CSRA (Certificate Services Remote Administration)
2//! primitives for CA-side ADCS misconfiguration detection.
3//!
4//! # Why this crate
5//!
6//! `ms-crtd` audits **templates** statically. `ms-icpr` submits **requests**.
7//! Neither can see the CA's own **configuration flags** — and the highest-
8//! impact ADCS misconfigurations live there:
9//!
10//! * **ESC6** — `EDITF_ATTRIBUTESUBJECTALTNAME2` set on the CA. Turns
11//!   every request-attribute SAN into an issued-cert SAN, regardless of
12//!   what the template allows.
13//! * **ESC7** — Manage-CA or Manage-Certificates rights delegated to a
14//!   non-tier-0 principal. Manage-CA can flip ESC6 remotely.
15//! * **ESC11** — RPC interface flags allow unauthenticated / no-integrity
16//!   binds to the CA's cert-request interface.
17//!
18//! All three flags live in registry-mapped config entries reachable via
19//! MS-CSRA `ICertAdminD2::GetConfigEntry` (opnum 44).
20//!
21//! # What this crate ships
22//!
23//! * [`build_get_config_entry_request`] — NDR-marshaled input stub for
24//!   `ICertAdminD2::GetConfigEntry(pwszAuthority, pwszNodePath, pwszEntry)`
25//!   at opnum 44 — the registry-mapped reads that carry `EditFlags` /
26//!   `InterfaceFlags` / `CRLFlags`, which is where ESC6 and ESC11 live.
27//! * [`EditFlags`] / [`InterfaceFlags`] / [`CrlFlags`] — bitfield
28//!   decoders + `describe()` helpers that surface the exact
29//!   ESC-relevant flags.
30//! * [`Esc6Finding`] / [`Esc11Finding`] — audit-shaped decoded findings
31//!   with severity + remediation.
32//!
33//! # What this crate does not do
34//!
35//! * No RPC transport. Callers plug this into `dcerpc` (opnum-driven
36//!   `\PIPE\cert`, binding to `ICertAdminD2` at UUID
37//!   `7fe0d935-dda6-11d1-a71f-00c04fc3141e` v0.0 — the interface that
38//!   carries `GetConfigEntry`).
39//! * No LDAP-side template audit (that lives in `ms-crtd`).
40
41use core::fmt;
42
43/// Well-known registry-mapped config entry paths that `GetConfigEntry`
44/// reads. `EditFlags`, `InterfaceFlags`, `CRLFlags` — all the ESC6 /
45/// ESC11 -relevant CA config lives here, not in `CR_PROP_*`.
46pub mod config_entry {
47    /// The strEntry for `EditFlags` (registry: `Policy\EditFlags` under
48    /// the CA's config). Read this + decode via [`super::EditFlags`] to
49    /// detect ESC6.
50    pub const EDIT_FLAGS_NODE: &str = "PolicyModules\\CertificateAuthority_MicrosoftDefault.Policy";
51    pub const EDIT_FLAGS_ENTRY: &str = "EditFlags";
52    /// The strEntry for `InterfaceFlags` (registry-side under the CA
53    /// root). Read this + decode via [`super::InterfaceFlags`] to
54    /// detect ESC11.
55    pub const INTERFACE_FLAGS_NODE: &str = "";
56    pub const INTERFACE_FLAGS_ENTRY: &str = "InterfaceFlags";
57    /// The strEntry for `CRLFlags`.
58    pub const CRL_FLAGS_NODE: &str = "";
59    pub const CRL_FLAGS_ENTRY: &str = "CRLFlags";
60}
61
62/// MS-CSRA `ICertAdminD` interface UUID
63/// (`d99e6e73-fc88-11d0-b498-00a0c90312f4`, v0.0). Distinct from the
64/// MS-WCCE `ICertRequestD` interface (`…312f3`) — same UUID prefix,
65/// trailing byte differs. This crate does not currently issue calls
66/// against `ICertAdminD`; use [`CSRA_D2_INTERFACE_UUID`] for the
67/// `GetConfigEntry` path.
68pub const CSRA_INTERFACE_UUID: &str = "d99e6e73-fc88-11d0-b498-00a0c90312f4";
69
70/// MS-CSRA `ICertAdminD2` interface UUID
71/// (`7fe0d935-dda6-11d1-a71f-00c04fc3141e`, v0.0). Extension interface;
72/// carries `GetConfigEntry`, `GetCASecurity`, `SetConfigEntry`, and the
73/// other post-Windows-2000 admin methods.
74pub const CSRA_D2_INTERFACE_UUID: &str = "7fe0d935-dda6-11d1-a71f-00c04fc3141e";
75
76/// `GetConfigEntry` opnum on the `ICertAdminD2` interface. Reads
77/// registry-mapped config entries — the path to `EditFlags` /
78/// `InterfaceFlags`. Bind against
79/// [`CSRA_D2_INTERFACE_UUID`], not [`CSRA_INTERFACE_UUID`].
80pub const GET_CONFIG_ENTRY_OPNUM: u16 = 44;
81
82/// Build the NDR-marshaled `[in]` stub for
83/// `ICertAdminD2::GetConfigEntry(pwszAuthority, pwszNodePath, pwszEntry)`.
84/// Use this to read `EditFlags` / `InterfaceFlags` — see the
85/// [`config_entry`] module for the well-known paths.
86///
87/// Wire layout:
88///
89/// ```text
90///   pwszAuthority: referent + conformant-varying WSTR
91///   pwszNodePath:  referent + conformant-varying WSTR  (empty = CA root)
92///   pwszEntry:     referent + conformant-varying WSTR
93/// ```
94pub fn build_get_config_entry_request(authority: &str, node_path: &str, entry: &str) -> Vec<u8> {
95    let mut out = Vec::new();
96    let mut e = NdrEncoder::new(&mut out);
97    e.referent();
98    e.conformant_varying_wstr(authority);
99    e.align(4);
100    e.referent();
101    e.conformant_varying_wstr(node_path);
102    e.align(4);
103    e.referent();
104    e.conformant_varying_wstr(entry);
105    out
106}
107
108/// CA `EditFlags` (registry-side value that MS-CSRA exposes via
109/// `GetCAProperty(EditFlags)`). Values from `certca.h`.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct EditFlags(pub u32);
112
113impl EditFlags {
114    pub const EDITF_ENABLEREQUESTEXTENSIONS: u32 = 0x00000001;
115    pub const EDITF_REQUESTEXTENSIONLIST: u32 = 0x00000002;
116    pub const EDITF_DISABLEEXTENSIONLIST: u32 = 0x00000004;
117    pub const EDITF_ADDOLDKEYUSAGE: u32 = 0x00000008;
118    pub const EDITF_ADDOLDCERTTYPE: u32 = 0x00000010;
119    pub const EDITF_ATTRIBUTEENDDATE: u32 = 0x00000020;
120    pub const EDITF_BASICCONSTRAINTSCRITICAL: u32 = 0x00000040;
121    pub const EDITF_ENABLEAKIKEYID: u32 = 0x00000100;
122    pub const EDITF_ATTRIBUTECA: u32 = 0x00000200;
123    pub const EDITF_IGNOREREQUESTERGROUP: u32 = 0x00000400;
124    pub const EDITF_ENABLEAKIISSUERNAME: u32 = 0x00000800;
125    pub const EDITF_ENABLEAKIISSUERSERIAL: u32 = 0x00001000;
126    pub const EDITF_ENABLEAKICRITICAL: u32 = 0x00002000;
127    pub const EDITF_SERVERUPGRADED: u32 = 0x00004000;
128    pub const EDITF_DISABLEOLDOSCNUPN: u32 = 0x00008000;
129    pub const EDITF_ADDOLDKEYUSAGE_2: u32 = 0x00010000;
130    /// **ESC6** — when set, the CA copies request-attribute SANs
131    /// (`SAN:upn=...`) into the issued cert regardless of what the
132    /// template allows. Any low-priv user with enrollment rights can
133    /// then impersonate an arbitrary UPN.
134    pub const EDITF_ATTRIBUTESUBJECTALTNAME2: u32 = 0x00040000;
135    pub const EDITF_ENABLELDAPREFERRALS: u32 = 0x00080000;
136    pub const EDITF_ENABLECHASECRLBRANCH: u32 = 0x00100000;
137    pub const EDITF_AUDITCERTTEMPLATELOAD: u32 = 0x00200000;
138
139    /// Return true when the ESC6 bit is set.
140    pub fn has_esc6(&self) -> bool {
141        (self.0 & Self::EDITF_ATTRIBUTESUBJECTALTNAME2) != 0
142    }
143
144    /// Human-readable summary of every set bit — one line per flag.
145    pub fn describe(&self) -> Vec<&'static str> {
146        let mut out = Vec::new();
147        macro_rules! chk {
148            ($($bit:ident),* $(,)?) => {
149                $(
150                    if (self.0 & Self::$bit) != 0 {
151                        out.push(stringify!($bit));
152                    }
153                )*
154            };
155        }
156        chk!(
157            EDITF_ENABLEREQUESTEXTENSIONS,
158            EDITF_REQUESTEXTENSIONLIST,
159            EDITF_DISABLEEXTENSIONLIST,
160            EDITF_ADDOLDKEYUSAGE,
161            EDITF_ADDOLDCERTTYPE,
162            EDITF_ATTRIBUTEENDDATE,
163            EDITF_BASICCONSTRAINTSCRITICAL,
164            EDITF_ENABLEAKIKEYID,
165            EDITF_ATTRIBUTECA,
166            EDITF_IGNOREREQUESTERGROUP,
167            EDITF_ENABLEAKIISSUERNAME,
168            EDITF_ENABLEAKIISSUERSERIAL,
169            EDITF_ENABLEAKICRITICAL,
170            EDITF_SERVERUPGRADED,
171            EDITF_DISABLEOLDOSCNUPN,
172            EDITF_ATTRIBUTESUBJECTALTNAME2,
173            EDITF_ENABLELDAPREFERRALS,
174            EDITF_ENABLECHASECRLBRANCH,
175            EDITF_AUDITCERTTEMPLATELOAD,
176        );
177        out
178    }
179}
180
181/// CA `InterfaceFlags` (`IF_*`). Missing bits (e.g. absence of
182/// `IF_ENFORCEENCRYPTICERTREQUEST`) can indicate ESC11 exposure.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub struct InterfaceFlags(pub u32);
185
186impl InterfaceFlags {
187    pub const IF_LOCKICERTREQUEST: u32 = 0x00000001;
188    pub const IF_NOREMOTEICERTREQUEST: u32 = 0x00000002;
189    pub const IF_NOLOCALICERTREQUEST: u32 = 0x00000004;
190    pub const IF_NOREMOTEICERTADMIN: u32 = 0x00000008;
191    pub const IF_NOLOCALICERTADMIN: u32 = 0x00000010;
192    pub const IF_NOREMOTEICERTADMINBACKUP: u32 = 0x00000020;
193    pub const IF_NOLOCALICERTADMINBACKUP: u32 = 0x00000040;
194    pub const IF_NOSNAPSHOTBACKUP: u32 = 0x00000080;
195    pub const IF_ENFORCEENCRYPTICERTREQUEST: u32 = 0x00000200;
196    pub const IF_ENFORCEENCRYPTICERTADMIN: u32 = 0x00000400;
197    pub const IF_ENABLEEXITKEYRETRIEVAL: u32 = 0x00000800;
198    pub const IF_ENABLEADMINASAUDITOR: u32 = 0x00001000;
199
200    /// **ESC11** — RPC-integrity/encryption not enforced on the
201    /// ICertRequest interface. Enables ntlm-relay to the CA's RPC
202    /// endpoint without needing to break packet privacy.
203    pub fn has_esc11(&self) -> bool {
204        (self.0 & Self::IF_ENFORCEENCRYPTICERTREQUEST) == 0
205    }
206
207    pub fn describe(&self) -> Vec<&'static str> {
208        let mut out = Vec::new();
209        macro_rules! chk {
210            ($($bit:ident),* $(,)?) => {
211                $(
212                    if (self.0 & Self::$bit) != 0 {
213                        out.push(stringify!($bit));
214                    }
215                )*
216            };
217        }
218        chk!(
219            IF_LOCKICERTREQUEST,
220            IF_NOREMOTEICERTREQUEST,
221            IF_NOLOCALICERTREQUEST,
222            IF_NOREMOTEICERTADMIN,
223            IF_NOLOCALICERTADMIN,
224            IF_NOREMOTEICERTADMINBACKUP,
225            IF_NOLOCALICERTADMINBACKUP,
226            IF_NOSNAPSHOTBACKUP,
227            IF_ENFORCEENCRYPTICERTREQUEST,
228            IF_ENFORCEENCRYPTICERTADMIN,
229            IF_ENABLEEXITKEYRETRIEVAL,
230            IF_ENABLEADMINASAUDITOR,
231        );
232        out
233    }
234}
235
236/// CA `CRLFlags`. Not ESC-critical; ship as decoder for parity with the
237/// two above.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub struct CrlFlags(pub u32);
240
241impl CrlFlags {
242    pub const CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE: u32 = 0x00000004;
243    pub const CRLF_DELETE_EXPIRED_CRLS: u32 = 0x00000008;
244    pub const CRLF_PUBLISH_EXPIRED_CERT_CRLS: u32 = 0x00000200;
245
246    pub fn describe(&self) -> Vec<&'static str> {
247        let mut out = Vec::new();
248        if (self.0 & Self::CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE) != 0 {
249            out.push("CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE");
250        }
251        if (self.0 & Self::CRLF_DELETE_EXPIRED_CRLS) != 0 {
252            out.push("CRLF_DELETE_EXPIRED_CRLS");
253        }
254        if (self.0 & Self::CRLF_PUBLISH_EXPIRED_CERT_CRLS) != 0 {
255            out.push("CRLF_PUBLISH_EXPIRED_CERT_CRLS");
256        }
257        out
258    }
259}
260
261/// Audit finding: an ESC6-exposed CA.
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct Esc6Finding {
264    pub ca_name: String,
265    pub edit_flags: EditFlags,
266    pub severity: Severity,
267    pub remediation: &'static str,
268}
269
270/// Audit finding: an ESC11-exposed CA.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct Esc11Finding {
273    pub ca_name: String,
274    pub interface_flags: InterfaceFlags,
275    pub severity: Severity,
276    pub remediation: &'static str,
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum Severity {
281    Low,
282    Medium,
283    High,
284    Critical,
285}
286
287impl fmt::Display for Severity {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        match self {
290            Severity::Low => f.write_str("low"),
291            Severity::Medium => f.write_str("medium"),
292            Severity::High => f.write_str("high"),
293            Severity::Critical => f.write_str("critical"),
294        }
295    }
296}
297
298/// Given a decoded `EditFlags` value and the CA it came from, produce
299/// an `Esc6Finding` if the ESC6 bit is set. Returns `None` if the CA is
300/// not exposed.
301pub fn detect_esc6(ca_name: &str, edit_flags: EditFlags) -> Option<Esc6Finding> {
302    if edit_flags.has_esc6() {
303        Some(Esc6Finding {
304            ca_name: ca_name.to_string(),
305            edit_flags,
306            severity: Severity::Critical,
307            remediation:
308                "Clear EDITF_ATTRIBUTESUBJECTALTNAME2 on the CA: `certutil -setreg policy\\EditFlags -EDITF_ATTRIBUTESUBJECTALTNAME2 && net stop certsvc && net start certsvc`. Any low-priv requester can currently obtain a client-auth cert bound to Administrator@<realm>.",
309        })
310    } else {
311        None
312    }
313}
314
315/// Given a decoded `InterfaceFlags` value and the CA it came from,
316/// produce an `Esc11Finding` if the enforce-encryption bit is missing.
317pub fn detect_esc11(ca_name: &str, interface_flags: InterfaceFlags) -> Option<Esc11Finding> {
318    if interface_flags.has_esc11() {
319        Some(Esc11Finding {
320            ca_name: ca_name.to_string(),
321            interface_flags,
322            severity: Severity::High,
323            remediation:
324                "Set IF_ENFORCEENCRYPTICERTREQUEST on the CA: `certutil -setreg CA\\InterfaceFlags +IF_ENFORCEENCRYPTICERTREQUEST && net stop certsvc && net start certsvc`. Without this the CA accepts NTLM-relayed requests without packet privacy.",
325        })
326    } else {
327        None
328    }
329}
330
331// ─── NDR encoder (subset — matches ms-icpr/ms-ndr semantics) ────────────
332
333struct NdrEncoder<'a> {
334    out: &'a mut Vec<u8>,
335    referent_counter: u32,
336}
337
338impl<'a> NdrEncoder<'a> {
339    fn new(out: &'a mut Vec<u8>) -> Self {
340        Self {
341            out,
342            referent_counter: 0x0002_0000,
343        }
344    }
345    fn referent(&mut self) {
346        let r = self.referent_counter;
347        self.referent_counter = self.referent_counter.wrapping_add(4);
348        self.u32(r);
349    }
350    fn u32(&mut self, v: u32) {
351        self.align(4);
352        self.out.extend_from_slice(&v.to_le_bytes());
353    }
354    fn align(&mut self, n: usize) {
355        while self.out.len() % n != 0 {
356            self.out.push(0);
357        }
358    }
359    fn conformant_varying_wstr(&mut self, s: &str) {
360        // Include the NUL terminator.
361        let units: Vec<u16> = s.encode_utf16().chain(core::iter::once(0)).collect();
362        let n = units.len() as u32;
363        self.align(4);
364        self.u32(n); // max_count
365        self.u32(0); // offset
366        self.u32(n); // actual_count
367        for u in units {
368            self.out.extend_from_slice(&u.to_le_bytes());
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn edit_flags_esc6_bit_detected() {
379        let f =
380            EditFlags(EditFlags::EDITF_ATTRIBUTESUBJECTALTNAME2 | EditFlags::EDITF_ENABLEAKIKEYID);
381        assert!(f.has_esc6());
382        let d = f.describe();
383        assert!(d.contains(&"EDITF_ATTRIBUTESUBJECTALTNAME2"));
384        assert!(d.contains(&"EDITF_ENABLEAKIKEYID"));
385    }
386
387    #[test]
388    fn edit_flags_default_shape_no_esc6() {
389        // Default 2019+ CA EditFlags value seen in the wild: 0x00015014.
390        let f = EditFlags(0x0001_5014);
391        assert!(!f.has_esc6());
392    }
393
394    #[test]
395    fn interface_flags_esc11_detected_on_missing_encryption() {
396        // Only the default IF_LOCKICERTREQUEST bit set (no encryption enforce).
397        let f = InterfaceFlags(InterfaceFlags::IF_LOCKICERTREQUEST);
398        assert!(f.has_esc11());
399    }
400
401    #[test]
402    fn interface_flags_esc11_clear_when_encryption_enforced() {
403        let f = InterfaceFlags(
404            InterfaceFlags::IF_LOCKICERTREQUEST | InterfaceFlags::IF_ENFORCEENCRYPTICERTREQUEST,
405        );
406        assert!(!f.has_esc11());
407    }
408
409    #[test]
410    fn detect_esc6_emits_finding_only_when_bit_set() {
411        assert!(detect_esc6(
412            "corp-CA-01",
413            EditFlags(EditFlags::EDITF_ATTRIBUTESUBJECTALTNAME2)
414        )
415        .is_some());
416        assert!(detect_esc6("corp-CA-01", EditFlags(0)).is_none());
417    }
418
419    #[test]
420    fn detect_esc11_emits_finding_only_when_encryption_missing() {
421        assert!(detect_esc11("corp-CA-01", InterfaceFlags(0)).is_some());
422        assert!(detect_esc11(
423            "corp-CA-01",
424            InterfaceFlags(InterfaceFlags::IF_ENFORCEENCRYPTICERTREQUEST)
425        )
426        .is_none());
427    }
428
429    #[test]
430    fn get_config_entry_request_carries_all_three_strings() {
431        let stub = build_get_config_entry_request(
432            "corp-CA-01",
433            config_entry::EDIT_FLAGS_NODE,
434            config_entry::EDIT_FLAGS_ENTRY,
435        );
436        for lit in ["corp-CA-01", config_entry::EDIT_FLAGS_ENTRY] {
437            let expected: Vec<u8> = format!("{lit}\0")
438                .encode_utf16()
439                .flat_map(|u| u.to_le_bytes())
440                .collect();
441            assert!(
442                stub.windows(expected.len()).any(|w| w == expected),
443                "config-entry stub must carry `{lit}` as UTF-16LE + NUL"
444            );
445        }
446    }
447
448    #[test]
449    fn severity_display() {
450        assert_eq!(format!("{}", Severity::Critical), "critical");
451        assert_eq!(format!("{}", Severity::High), "high");
452    }
453}