ms-csra 0.1.1

MS-CSRA (Certificate Services Remote Administration) primitives — GetCAProperty request builder, EditFlags/InterfaceFlags/CRLFlags decoders, and offline detectors for ESC6 (EDITF_ATTRIBUTESUBJECTALTNAME2), ESC7 (Manage-CA ACL), and CA-side ADCS misconfigurations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! **ms-csra** — MS-CSRA (Certificate Services Remote Administration)
//! primitives for CA-side ADCS misconfiguration detection.
//!
//! # Why this crate
//!
//! `ms-crtd` audits **templates** statically. `ms-icpr` submits **requests**.
//! Neither can see the CA's own **configuration flags** — and the highest-
//! impact ADCS misconfigurations live there:
//!
//! * **ESC6** — `EDITF_ATTRIBUTESUBJECTALTNAME2` set on the CA. Turns
//!   every request-attribute SAN into an issued-cert SAN, regardless of
//!   what the template allows.
//! * **ESC7** — Manage-CA or Manage-Certificates rights delegated to a
//!   non-tier-0 principal. Manage-CA can flip ESC6 remotely.
//! * **ESC11** — RPC interface flags allow unauthenticated / no-integrity
//!   binds to the CA's cert-request interface.
//!
//! All three flags live in registry-mapped config entries reachable via
//! MS-CSRA `ICertAdminD2::GetConfigEntry` (opnum 44).
//!
//! # What this crate ships
//!
//! * [`build_get_config_entry_request`] — NDR-marshaled input stub for
//!   `ICertAdminD2::GetConfigEntry(pwszAuthority, pwszNodePath, pwszEntry)`
//!   at opnum 44 — the registry-mapped reads that carry `EditFlags` /
//!   `InterfaceFlags` / `CRLFlags`, which is where ESC6 and ESC11 live.
//! * [`EditFlags`] / [`InterfaceFlags`] / [`CrlFlags`] — bitfield
//!   decoders + `describe()` helpers that surface the exact
//!   ESC-relevant flags.
//! * [`Esc6Finding`] / [`Esc11Finding`] — audit-shaped decoded findings
//!   with severity + remediation.
//!
//! # What this crate does not do
//!
//! * No RPC transport. Callers plug this into `dcerpc` (opnum-driven
//!   `\PIPE\cert`, binding to `ICertAdminD2` at UUID
//!   `7fe0d935-dda6-11d1-a71f-00c04fc3141e` v0.0 — the interface that
//!   carries `GetConfigEntry`).
//! * No LDAP-side template audit (that lives in `ms-crtd`).

use core::fmt;

/// Well-known registry-mapped config entry paths that `GetConfigEntry`
/// reads. `EditFlags`, `InterfaceFlags`, `CRLFlags` — all the ESC6 /
/// ESC11 -relevant CA config lives here, not in `CR_PROP_*`.
pub mod config_entry {
    /// The strEntry for `EditFlags` (registry: `Policy\EditFlags` under
    /// the CA's config). Read this + decode via [`super::EditFlags`] to
    /// detect ESC6.
    pub const EDIT_FLAGS_NODE: &str = "PolicyModules\\CertificateAuthority_MicrosoftDefault.Policy";
    pub const EDIT_FLAGS_ENTRY: &str = "EditFlags";
    /// The strEntry for `InterfaceFlags` (registry-side under the CA
    /// root). Read this + decode via [`super::InterfaceFlags`] to
    /// detect ESC11.
    pub const INTERFACE_FLAGS_NODE: &str = "";
    pub const INTERFACE_FLAGS_ENTRY: &str = "InterfaceFlags";
    /// The strEntry for `CRLFlags`.
    pub const CRL_FLAGS_NODE: &str = "";
    pub const CRL_FLAGS_ENTRY: &str = "CRLFlags";
}

/// MS-CSRA `ICertAdminD` interface UUID
/// (`d99e6e73-fc88-11d0-b498-00a0c90312f4`, v0.0). Distinct from the
/// MS-WCCE `ICertRequestD` interface (`…312f3`) — same UUID prefix,
/// trailing byte differs. This crate does not currently issue calls
/// against `ICertAdminD`; use [`CSRA_D2_INTERFACE_UUID`] for the
/// `GetConfigEntry` path.
pub const CSRA_INTERFACE_UUID: &str = "d99e6e73-fc88-11d0-b498-00a0c90312f4";

/// MS-CSRA `ICertAdminD2` interface UUID
/// (`7fe0d935-dda6-11d1-a71f-00c04fc3141e`, v0.0). Extension interface;
/// carries `GetConfigEntry`, `GetCASecurity`, `SetConfigEntry`, and the
/// other post-Windows-2000 admin methods.
pub const CSRA_D2_INTERFACE_UUID: &str = "7fe0d935-dda6-11d1-a71f-00c04fc3141e";

/// `GetConfigEntry` opnum on the `ICertAdminD2` interface. Reads
/// registry-mapped config entries — the path to `EditFlags` /
/// `InterfaceFlags`. Bind against
/// [`CSRA_D2_INTERFACE_UUID`], not [`CSRA_INTERFACE_UUID`].
pub const GET_CONFIG_ENTRY_OPNUM: u16 = 44;

/// Build the NDR-marshaled `[in]` stub for
/// `ICertAdminD2::GetConfigEntry(pwszAuthority, pwszNodePath, pwszEntry)`.
/// Use this to read `EditFlags` / `InterfaceFlags` — see the
/// [`config_entry`] module for the well-known paths.
///
/// Wire layout:
///
/// ```text
///   pwszAuthority: referent + conformant-varying WSTR
///   pwszNodePath:  referent + conformant-varying WSTR  (empty = CA root)
///   pwszEntry:     referent + conformant-varying WSTR
/// ```
pub fn build_get_config_entry_request(authority: &str, node_path: &str, entry: &str) -> Vec<u8> {
    let mut out = Vec::new();
    let mut e = NdrEncoder::new(&mut out);
    e.referent();
    e.conformant_varying_wstr(authority);
    e.align(4);
    e.referent();
    e.conformant_varying_wstr(node_path);
    e.align(4);
    e.referent();
    e.conformant_varying_wstr(entry);
    out
}

/// CA `EditFlags` (registry-side value that MS-CSRA exposes via
/// `GetCAProperty(EditFlags)`). Values from `certca.h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EditFlags(pub u32);

impl EditFlags {
    pub const EDITF_ENABLEREQUESTEXTENSIONS: u32 = 0x00000001;
    pub const EDITF_REQUESTEXTENSIONLIST: u32 = 0x00000002;
    pub const EDITF_DISABLEEXTENSIONLIST: u32 = 0x00000004;
    pub const EDITF_ADDOLDKEYUSAGE: u32 = 0x00000008;
    pub const EDITF_ADDOLDCERTTYPE: u32 = 0x00000010;
    pub const EDITF_ATTRIBUTEENDDATE: u32 = 0x00000020;
    pub const EDITF_BASICCONSTRAINTSCRITICAL: u32 = 0x00000040;
    pub const EDITF_ENABLEAKIKEYID: u32 = 0x00000100;
    pub const EDITF_ATTRIBUTECA: u32 = 0x00000200;
    pub const EDITF_IGNOREREQUESTERGROUP: u32 = 0x00000400;
    pub const EDITF_ENABLEAKIISSUERNAME: u32 = 0x00000800;
    pub const EDITF_ENABLEAKIISSUERSERIAL: u32 = 0x00001000;
    pub const EDITF_ENABLEAKICRITICAL: u32 = 0x00002000;
    pub const EDITF_SERVERUPGRADED: u32 = 0x00004000;
    pub const EDITF_DISABLEOLDOSCNUPN: u32 = 0x00008000;
    pub const EDITF_ADDOLDKEYUSAGE_2: u32 = 0x00010000;
    /// **ESC6** — when set, the CA copies request-attribute SANs
    /// (`SAN:upn=...`) into the issued cert regardless of what the
    /// template allows. Any low-priv user with enrollment rights can
    /// then impersonate an arbitrary UPN.
    pub const EDITF_ATTRIBUTESUBJECTALTNAME2: u32 = 0x00040000;
    pub const EDITF_ENABLELDAPREFERRALS: u32 = 0x00080000;
    pub const EDITF_ENABLECHASECRLBRANCH: u32 = 0x00100000;
    pub const EDITF_AUDITCERTTEMPLATELOAD: u32 = 0x00200000;

    /// Return true when the ESC6 bit is set.
    pub fn has_esc6(&self) -> bool {
        (self.0 & Self::EDITF_ATTRIBUTESUBJECTALTNAME2) != 0
    }

    /// Human-readable summary of every set bit — one line per flag.
    pub fn describe(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        macro_rules! chk {
            ($($bit:ident),* $(,)?) => {
                $(
                    if (self.0 & Self::$bit) != 0 {
                        out.push(stringify!($bit));
                    }
                )*
            };
        }
        chk!(
            EDITF_ENABLEREQUESTEXTENSIONS,
            EDITF_REQUESTEXTENSIONLIST,
            EDITF_DISABLEEXTENSIONLIST,
            EDITF_ADDOLDKEYUSAGE,
            EDITF_ADDOLDCERTTYPE,
            EDITF_ATTRIBUTEENDDATE,
            EDITF_BASICCONSTRAINTSCRITICAL,
            EDITF_ENABLEAKIKEYID,
            EDITF_ATTRIBUTECA,
            EDITF_IGNOREREQUESTERGROUP,
            EDITF_ENABLEAKIISSUERNAME,
            EDITF_ENABLEAKIISSUERSERIAL,
            EDITF_ENABLEAKICRITICAL,
            EDITF_SERVERUPGRADED,
            EDITF_DISABLEOLDOSCNUPN,
            EDITF_ATTRIBUTESUBJECTALTNAME2,
            EDITF_ENABLELDAPREFERRALS,
            EDITF_ENABLECHASECRLBRANCH,
            EDITF_AUDITCERTTEMPLATELOAD,
        );
        out
    }
}

/// CA `InterfaceFlags` (`IF_*`). Missing bits (e.g. absence of
/// `IF_ENFORCEENCRYPTICERTREQUEST`) can indicate ESC11 exposure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterfaceFlags(pub u32);

impl InterfaceFlags {
    pub const IF_LOCKICERTREQUEST: u32 = 0x00000001;
    pub const IF_NOREMOTEICERTREQUEST: u32 = 0x00000002;
    pub const IF_NOLOCALICERTREQUEST: u32 = 0x00000004;
    pub const IF_NOREMOTEICERTADMIN: u32 = 0x00000008;
    pub const IF_NOLOCALICERTADMIN: u32 = 0x00000010;
    pub const IF_NOREMOTEICERTADMINBACKUP: u32 = 0x00000020;
    pub const IF_NOLOCALICERTADMINBACKUP: u32 = 0x00000040;
    pub const IF_NOSNAPSHOTBACKUP: u32 = 0x00000080;
    pub const IF_ENFORCEENCRYPTICERTREQUEST: u32 = 0x00000200;
    pub const IF_ENFORCEENCRYPTICERTADMIN: u32 = 0x00000400;
    pub const IF_ENABLEEXITKEYRETRIEVAL: u32 = 0x00000800;
    pub const IF_ENABLEADMINASAUDITOR: u32 = 0x00001000;

    /// **ESC11** — RPC-integrity/encryption not enforced on the
    /// ICertRequest interface. Enables ntlm-relay to the CA's RPC
    /// endpoint without needing to break packet privacy.
    pub fn has_esc11(&self) -> bool {
        (self.0 & Self::IF_ENFORCEENCRYPTICERTREQUEST) == 0
    }

    pub fn describe(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        macro_rules! chk {
            ($($bit:ident),* $(,)?) => {
                $(
                    if (self.0 & Self::$bit) != 0 {
                        out.push(stringify!($bit));
                    }
                )*
            };
        }
        chk!(
            IF_LOCKICERTREQUEST,
            IF_NOREMOTEICERTREQUEST,
            IF_NOLOCALICERTREQUEST,
            IF_NOREMOTEICERTADMIN,
            IF_NOLOCALICERTADMIN,
            IF_NOREMOTEICERTADMINBACKUP,
            IF_NOLOCALICERTADMINBACKUP,
            IF_NOSNAPSHOTBACKUP,
            IF_ENFORCEENCRYPTICERTREQUEST,
            IF_ENFORCEENCRYPTICERTADMIN,
            IF_ENABLEEXITKEYRETRIEVAL,
            IF_ENABLEADMINASAUDITOR,
        );
        out
    }
}

/// CA `CRLFlags`. Not ESC-critical; ship as decoder for parity with the
/// two above.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CrlFlags(pub u32);

impl CrlFlags {
    pub const CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE: u32 = 0x00000004;
    pub const CRLF_DELETE_EXPIRED_CRLS: u32 = 0x00000008;
    pub const CRLF_PUBLISH_EXPIRED_CERT_CRLS: u32 = 0x00000200;

    pub fn describe(&self) -> Vec<&'static str> {
        let mut out = Vec::new();
        if (self.0 & Self::CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE) != 0 {
            out.push("CRLF_DELTA_USE_OLDEST_UNEXPIRED_BASE");
        }
        if (self.0 & Self::CRLF_DELETE_EXPIRED_CRLS) != 0 {
            out.push("CRLF_DELETE_EXPIRED_CRLS");
        }
        if (self.0 & Self::CRLF_PUBLISH_EXPIRED_CERT_CRLS) != 0 {
            out.push("CRLF_PUBLISH_EXPIRED_CERT_CRLS");
        }
        out
    }
}

/// Audit finding: an ESC6-exposed CA.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Esc6Finding {
    pub ca_name: String,
    pub edit_flags: EditFlags,
    pub severity: Severity,
    pub remediation: &'static str,
}

/// Audit finding: an ESC11-exposed CA.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Esc11Finding {
    pub ca_name: String,
    pub interface_flags: InterfaceFlags,
    pub severity: Severity,
    pub remediation: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Severity::Low => f.write_str("low"),
            Severity::Medium => f.write_str("medium"),
            Severity::High => f.write_str("high"),
            Severity::Critical => f.write_str("critical"),
        }
    }
}

/// Given a decoded `EditFlags` value and the CA it came from, produce
/// an `Esc6Finding` if the ESC6 bit is set. Returns `None` if the CA is
/// not exposed.
pub fn detect_esc6(ca_name: &str, edit_flags: EditFlags) -> Option<Esc6Finding> {
    if edit_flags.has_esc6() {
        Some(Esc6Finding {
            ca_name: ca_name.to_string(),
            edit_flags,
            severity: Severity::Critical,
            remediation:
                "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>.",
        })
    } else {
        None
    }
}

/// Given a decoded `InterfaceFlags` value and the CA it came from,
/// produce an `Esc11Finding` if the enforce-encryption bit is missing.
pub fn detect_esc11(ca_name: &str, interface_flags: InterfaceFlags) -> Option<Esc11Finding> {
    if interface_flags.has_esc11() {
        Some(Esc11Finding {
            ca_name: ca_name.to_string(),
            interface_flags,
            severity: Severity::High,
            remediation:
                "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.",
        })
    } else {
        None
    }
}

// ─── NDR encoder (subset — matches ms-icpr/ms-ndr semantics) ────────────

struct NdrEncoder<'a> {
    out: &'a mut Vec<u8>,
    referent_counter: u32,
}

impl<'a> NdrEncoder<'a> {
    fn new(out: &'a mut Vec<u8>) -> Self {
        Self {
            out,
            referent_counter: 0x0002_0000,
        }
    }
    fn referent(&mut self) {
        let r = self.referent_counter;
        self.referent_counter = self.referent_counter.wrapping_add(4);
        self.u32(r);
    }
    fn u32(&mut self, v: u32) {
        self.align(4);
        self.out.extend_from_slice(&v.to_le_bytes());
    }
    fn align(&mut self, n: usize) {
        while self.out.len() % n != 0 {
            self.out.push(0);
        }
    }
    fn conformant_varying_wstr(&mut self, s: &str) {
        // Include the NUL terminator.
        let units: Vec<u16> = s.encode_utf16().chain(core::iter::once(0)).collect();
        let n = units.len() as u32;
        self.align(4);
        self.u32(n); // max_count
        self.u32(0); // offset
        self.u32(n); // actual_count
        for u in units {
            self.out.extend_from_slice(&u.to_le_bytes());
        }
    }
}

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

    #[test]
    fn edit_flags_esc6_bit_detected() {
        let f =
            EditFlags(EditFlags::EDITF_ATTRIBUTESUBJECTALTNAME2 | EditFlags::EDITF_ENABLEAKIKEYID);
        assert!(f.has_esc6());
        let d = f.describe();
        assert!(d.contains(&"EDITF_ATTRIBUTESUBJECTALTNAME2"));
        assert!(d.contains(&"EDITF_ENABLEAKIKEYID"));
    }

    #[test]
    fn edit_flags_default_shape_no_esc6() {
        // Default 2019+ CA EditFlags value seen in the wild: 0x00015014.
        let f = EditFlags(0x0001_5014);
        assert!(!f.has_esc6());
    }

    #[test]
    fn interface_flags_esc11_detected_on_missing_encryption() {
        // Only the default IF_LOCKICERTREQUEST bit set (no encryption enforce).
        let f = InterfaceFlags(InterfaceFlags::IF_LOCKICERTREQUEST);
        assert!(f.has_esc11());
    }

    #[test]
    fn interface_flags_esc11_clear_when_encryption_enforced() {
        let f = InterfaceFlags(
            InterfaceFlags::IF_LOCKICERTREQUEST | InterfaceFlags::IF_ENFORCEENCRYPTICERTREQUEST,
        );
        assert!(!f.has_esc11());
    }

    #[test]
    fn detect_esc6_emits_finding_only_when_bit_set() {
        assert!(detect_esc6(
            "corp-CA-01",
            EditFlags(EditFlags::EDITF_ATTRIBUTESUBJECTALTNAME2)
        )
        .is_some());
        assert!(detect_esc6("corp-CA-01", EditFlags(0)).is_none());
    }

    #[test]
    fn detect_esc11_emits_finding_only_when_encryption_missing() {
        assert!(detect_esc11("corp-CA-01", InterfaceFlags(0)).is_some());
        assert!(detect_esc11(
            "corp-CA-01",
            InterfaceFlags(InterfaceFlags::IF_ENFORCEENCRYPTICERTREQUEST)
        )
        .is_none());
    }

    #[test]
    fn get_config_entry_request_carries_all_three_strings() {
        let stub = build_get_config_entry_request(
            "corp-CA-01",
            config_entry::EDIT_FLAGS_NODE,
            config_entry::EDIT_FLAGS_ENTRY,
        );
        for lit in ["corp-CA-01", config_entry::EDIT_FLAGS_ENTRY] {
            let expected: Vec<u8> = format!("{lit}\0")
                .encode_utf16()
                .flat_map(|u| u.to_le_bytes())
                .collect();
            assert!(
                stub.windows(expected.len()).any(|w| w == expected),
                "config-entry stub must carry `{lit}` as UTF-16LE + NUL"
            );
        }
    }

    #[test]
    fn severity_display() {
        assert_eq!(format!("{}", Severity::Critical), "critical");
        assert_eq!(format!("{}", Severity::High), "high");
    }
}