Skip to main content

rusthound_ce/objects/
enterpriseca.rs

1use colored::Colorize;
2use serde::{Deserialize, Serialize};
3use serde_json::value::Value;
4use x509_parser::oid_registry::asn1_rs::oid;
5use x509_parser::prelude::*;
6use ldap3::SearchEntry;
7use log::{debug, error, info, trace};
8use std::collections::HashMap;
9use std::error::Error;
10
11use crate::enums::{
12    MaskFlags, SecurityDescriptor, AceFormat, Acl,
13    decode_guid_le, parse_ntsecuritydescriptor, sid_maker, parse_ca_security
14};
15use crate::json::checker::common::get_name_from_full_distinguishedname;
16use crate::objects::common::{LdapObject, AceTemplate, SPNTarget, Link, Member};
17use crate::utils::crypto::calculate_sha1;
18use crate::utils::date::string_to_epoch;
19
20// Web enrollment endpoint types (ESC8)
21
22#[derive(Debug, Clone, Serialize, Deserialize, Default)]
23pub struct WebEnrollmentResult {
24    #[serde(rename = "Url")]
25    pub url: String,
26    #[serde(rename = "Type")]
27    pub enrollment_type: String,
28    #[serde(rename = "Status")]
29    pub status: String,
30    #[serde(rename = "ADCSWebEnrollmentHTTP")]
31    pub adcs_web_enrollment_http: bool,
32    #[serde(rename = "ADCSWebEnrollmentHTTPS")]
33    pub adcs_web_enrollment_https: bool,
34    #[serde(rename = "ADCSWebEnrollmentEPA")]
35    pub adcs_web_enrollment_epa: bool,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, Default)]
39pub struct WebEnrollmentEndpoint {
40    #[serde(rename = "Result")]
41    pub result: Option<WebEnrollmentResult>,
42    #[serde(rename = "Collected")]
43    pub collected: bool,
44    #[serde(rename = "FailureReason")]
45    pub failure_reason: Option<String>,
46}
47
48/// EnterpriseCA structure
49#[derive(Debug, Clone, Deserialize, Serialize, Default)]
50pub struct EnterpriseCA {
51    #[serde(rename = "Properties")]
52    properties: EnterpriseCAProperties,
53    #[serde(rename = "HostingComputer")]
54    hosting_computer: String,
55    #[serde(rename = "CARegistryData")]
56    ca_registry_data: CARegistryData,
57    #[serde(rename = "EnabledCertTemplates")]
58    enabled_cert_templates: Vec<Member>,
59    #[serde(rename = "HttpEnrollmentEndpoints")]
60    http_enrollment_endpoints: Vec<WebEnrollmentEndpoint>,
61    #[serde(rename = "Aces")]
62    aces: Vec<AceTemplate>,
63    #[serde(rename = "ObjectIdentifier")]
64    object_identifier: String,
65    #[serde(rename = "IsDeleted")]
66    is_deleted: bool,
67    #[serde(rename = "IsACLProtected")]
68    is_acl_protected: bool,
69    #[serde(rename = "ContainedBy")]
70    contained_by: Option<Member>,
71}
72
73impl EnterpriseCA {
74    // New EnterpriseCA
75    pub fn new() -> Self { 
76        Self { ..Default::default() } 
77    }
78
79    // Immutable access.
80    pub fn enabled_cert_templates(&self) -> &Vec<Member> {
81        &self.enabled_cert_templates
82    }
83
84    // Mutable access.
85    pub fn enabled_cert_templates_mut(&mut self) -> &mut Vec<Member> {
86        &mut self.enabled_cert_templates
87    }
88
89    // DNS hostname of the CA, used for the ESC8 probe.
90    pub fn dns_host(&self) -> &str {
91        &self.properties.dnshostname
92    }
93
94    // Inject ESC8 probe results into this EnterpriseCA.
95    pub fn apply_esc8(&mut self, endpoints: Vec<WebEnrollmentEndpoint>) {
96        self.http_enrollment_endpoints = endpoints;
97    }
98
99    /// Function to parse and replace value in json template for Enterprise CA object.
100    pub fn parse(
101        &mut self,
102        result: SearchEntry,
103        domain: &str,
104        dn_sid: &mut HashMap<String, String>,
105        sid_type: &mut HashMap<String, String>,
106        domain_sid: &str,
107        schema_guid_map: &HashMap<String, String>,
108    ) -> Result<(), Box<dyn Error>> {
109        let result_dn: String = result.dn.to_uppercase();
110        let result_attrs: HashMap<String, Vec<String>> = result.attrs;
111        let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;
112
113        // Debug for current object
114        debug!("Parse EnterpriseCA: {result_dn}");
115
116        // Trace all result attributes
117        for (key, value) in &result_attrs {
118            trace!("  {key:?}:{value:?}");
119        }
120        // Trace all bin result attributes
121        for (key, value) in &result_bin {
122            trace!("  {key:?}:{value:?}");
123        }
124
125        // Change all values...
126        self.properties.domain = domain.to_uppercase();
127        self.properties.distinguishedname = result_dn;
128        self.properties.domainsid = domain_sid.to_string();
129        let ca_name = get_name_from_full_distinguishedname(&self.properties.distinguishedname);
130        self.properties.caname = ca_name;
131
132        // With a check
133        for (key, value) in &result_attrs {
134            match key.as_str() {
135                "name" => {
136                    let name = format!("{}@{}", &value[0], domain);
137                    self.properties.name = name.to_uppercase();
138                }
139                "description" => {
140                    self.properties.description = Some(value[0].to_owned());
141                }
142                "dNSHostName" => {
143                    self.properties.dnshostname = value[0].to_owned();
144                }
145                "certificateTemplates" => {
146                    if value.is_empty() {
147                        error!("No certificate templates enabled for {}", self.properties.caname);
148                    } else {
149                        //ca.enabled_templates = value.to_vec();
150                        info!("Found {} enabled certificate templates", value.len().to_string().bold());
151                        trace!("Enabled certificate templates: {:?}", value);
152                        let enabled_templates: Vec<Member> = value.iter().map(|template_name| {
153                            let mut member = Member::new();
154                            *member.object_identifier_mut() = template_name.to_owned();
155                            *member.object_type_mut() = String::from("CertTemplate");
156
157                            member
158                        }).collect();
159                        self.enabled_cert_templates = enabled_templates;
160                    }
161                }
162                "whenCreated" => {
163                    let epoch = string_to_epoch(&value[0])?;
164                    if epoch.is_positive() {
165                        self.properties.whencreated = epoch;
166                    }
167                }
168                "isDeleted" => {
169                    self.is_deleted = true;
170                }
171                _ => {}
172            }
173        }
174
175        // For all, bins attributs
176        for (key, value) in &result_bin {
177            match key.as_str() {
178                "objectGUID" => {
179                    // objectGUID raw to string
180                    let guid = decode_guid_le(&value[0]);
181                    self.object_identifier = guid.to_owned();
182                }
183                "nTSecurityDescriptor" => {
184                    // nTSecurityDescriptor raw to string
185                    let relations_ace = parse_ntsecuritydescriptor(
186                        self,
187                        &value[0],
188                        "EnterpriseCA",
189                        &result_attrs,
190                        &result_bin,
191                        domain,
192                        schema_guid_map,
193                    );
194                    // Aces
195                    self.aces = relations_ace;
196                    // HostingComputer
197                    self.hosting_computer = Self::get_hosting_computer(&value[0], domain);
198                    // CASecurity
199                    let ca_security_data = parse_ca_security(&value[0], &self.hosting_computer, domain);
200                    if !ca_security_data.is_empty() {
201                        let ca_security = CASecurity {
202                            data: ca_security_data,
203                            collected: true,
204                            failure_reason: None,
205                        };
206                        self.properties.casecuritycollected = true;
207                        let ca_registry_data = CARegistryData::new(ca_security);
208                        self.ca_registry_data = ca_registry_data;
209                    } else {
210                        let ca_security = CASecurity {
211                            data: Vec::new(),
212                            collected: false,
213                            failure_reason: Some(String::from("Failed to get CASecurity!"))
214                        };
215                        self.properties.casecuritycollected = false;
216                        let ca_registry_data = CARegistryData::new(ca_security);
217                        self.ca_registry_data = ca_registry_data;
218                    }
219                }
220                "cACertificate" => {
221                    //info!("{:?}:{:?}", key,value[0].to_owned());
222                    let certsha1: String = calculate_sha1(&value[0]);
223                    self.properties.certthumbprint = certsha1.to_owned();
224                    self.properties.certname = certsha1.to_owned();
225                    self.properties.certchain = vec![certsha1.to_owned()];
226
227                    // Parsing certificate.
228                    let res = X509Certificate::from_der(&value[0]);
229                    match res {
230                        Ok((_rem, cert)) => {
231                            // println!("Basic Constraints Extensions:");
232                            for ext in cert.extensions() {
233                                // println!("{:?} : {:?}",&ext.oid, ext);
234                                if &ext.oid == &oid!(2.5.29.19) {
235                                    // <https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.BasicConstraints.html>
236                                    if let ParsedExtension::BasicConstraints(basic_constraints) = &ext.parsed_extension() {
237                                        let _ca = &basic_constraints.ca;
238                                        let _path_len_constraint = &basic_constraints.path_len_constraint;
239                                        // println!("ca: {:?}", _ca);
240                                        // println!("path_len_constraint: {:?}", _path_len_constraint);
241                                        match _path_len_constraint {
242                                            Some(_path_len_constraint) => {
243                                                if _path_len_constraint > &0 {
244                                                    self.properties.hasbasicconstraints = true;
245                                                    self.properties.basicconstraintpathlength = _path_len_constraint.to_owned();
246
247                                                } else {
248                                                    self.properties.hasbasicconstraints = false;
249                                                    self.properties.basicconstraintpathlength = 0;
250                                                }
251                                            }
252                                            None => {
253                                                self.properties.hasbasicconstraints = false;
254                                                self.properties.basicconstraintpathlength = 0;
255                                            }
256                                        }
257                                    }
258                                }
259                            }
260                        },
261                        _ => error!("CA x509 certificate parsing failed: {:?}", res),
262                    }
263                }
264                _ => {}
265            }
266        }
267
268        // Push DN and SID in HashMap
269        if self.object_identifier != "SID" {
270            dn_sid.insert(
271                self.properties.distinguishedname.to_string(),
272                self.object_identifier.to_string(),
273            );
274            // Push DN and Type
275            sid_type.insert(
276                self.object_identifier.to_string(),
277                "EnterpriseCA".to_string(),
278            );
279        }
280
281        // Trace and return EnterpriseCA struct
282        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
283        Ok(())
284    }
285
286    /// Function to get HostingComputer from ACL if ACE get ManageCertificates and is not Group.
287    fn get_hosting_computer(
288        nt: &[u8],
289        domain: &str,
290    ) -> String {
291        let mut hosting_computer = String::from("Not found");
292        let blacklist_sid = [
293            // <https://learn.microsoft.com/fr-fr/windows-server/identity/ad-ds/manage/understand-security-identifiers>
294            "-544", // Administrators
295            "-519", // Enterprise Administrators
296            "-512", // Domain Admins
297        ];
298        let secdesc: SecurityDescriptor = SecurityDescriptor::parse(nt).unwrap().1;
299        if secdesc.offset_dacl as usize != 0 
300        {
301            let res = Acl::parse(&nt[secdesc.offset_dacl as usize..]);
302            match res {
303                Ok(_res) => {
304                    let dacl = _res.1;
305                    let aces = dacl.data;
306                    for ace in aces {
307                        if ace.ace_type == 0x00 {
308                            let sid = sid_maker(AceFormat::get_sid(ace.data.to_owned()).unwrap(), domain);
309                            let mask = match AceFormat::get_mask(&ace.data) {
310                                Some(mask) => mask,
311                                None => continue,
312                            };
313                            if (MaskFlags::MANAGE_CERTIFICATES.bits() | mask) == mask
314                            && !blacklist_sid.iter().any(|blacklisted| sid.ends_with(blacklisted)) 
315                            {
316                                // println!("SID MANAGE_CERTIFICATES: {:?}",&sid);
317                                hosting_computer = sid;
318                                return hosting_computer
319                            }
320                        }
321                    }
322                },
323                Err(err) => error!("Error. Reason: {err}")
324            }
325        }
326        hosting_computer
327    }
328}
329
330impl LdapObject for EnterpriseCA {
331    // To JSON
332    fn to_json(&self) -> Value {
333        serde_json::to_value(self).unwrap()
334    }
335
336    // Get values
337    fn get_object_identifier(&self) -> &String {
338        &self.object_identifier
339    }
340    fn get_is_acl_protected(&self) -> &bool {
341        &self.is_acl_protected
342    }
343    fn get_aces(&self) -> &Vec<AceTemplate> {
344        &self.aces
345    }
346    fn get_spntargets(&self) -> &Vec<SPNTarget> {
347        panic!("Not used by current object.");
348    }
349    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
350        panic!("Not used by current object.");
351    }
352    fn get_links(&self) -> &Vec<Link> {
353        panic!("Not used by current object.");
354    }
355    fn get_contained_by(&self) -> &Option<Member> {
356        &self.contained_by
357    }
358    fn get_child_objects(&self) -> &Vec<Member> {
359        panic!("Not used by current object.");
360    }
361    fn get_haslaps(&self) -> &bool {
362        &false
363    }
364
365    // Get mutable values
366    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
367        &mut self.aces
368    }
369    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
370        panic!("Not used by current object.");
371    }
372    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
373        panic!("Not used by current object.");
374    }
375
376    // Edit values
377    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
378        self.is_acl_protected = is_acl_protected;
379        self.properties.isaclprotected = is_acl_protected;
380    }
381    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
382        self.aces = aces;
383    }
384    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
385        // Not used by current object.
386    }
387    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
388        // Not used by current object.
389    }
390    fn set_links(&mut self, _links: Vec<Link>) {
391        // Not used by current object.
392    }
393    fn set_contained_by(&mut self, contained_by: Option<Member>) {
394        self.contained_by = contained_by;
395    }
396    fn set_child_objects(&mut self, _child_objects: Vec<Member>) {
397        // Not used by current object.
398    }
399}
400
401
402// EnterpriseCA properties structure
403#[derive(Debug, Clone, Deserialize, Serialize)]
404pub struct EnterpriseCAProperties {
405    domain: String,
406    name: String,
407    distinguishedname: String,
408    domainsid: String,
409    isaclprotected: bool,
410    description: Option<String>,
411    whencreated: i64,
412    flags: String,
413    caname: String,
414    dnshostname: String,
415    certthumbprint: String,
416    certname: String,
417    certchain: Vec<String>,
418    hasbasicconstraints: bool,
419    basicconstraintpathlength: u32,
420    unresolvedpublishedtemplates: Vec<String>,
421    casecuritycollected: bool,
422    enrollmentagentrestrictionscollected: bool,
423    isuserspecifiessanenabledcollected: bool,
424    roleseparationenabledcollected: bool,
425}
426
427impl Default for EnterpriseCAProperties {
428    fn default() -> EnterpriseCAProperties {
429        EnterpriseCAProperties {
430            domain: String::from(""),
431            name: String::from(""),
432            distinguishedname: String::from(""),
433            domainsid: String::from(""),
434            isaclprotected: false,
435            description: None,
436            whencreated: -1,
437            flags: String::from(""),
438            caname: String::from(""),
439            dnshostname: String::from(""),
440            certthumbprint: String::from(""),
441            certname: String::from(""),
442            certchain: Vec::new(),
443            hasbasicconstraints: false,
444            basicconstraintpathlength: 0,
445            unresolvedpublishedtemplates: Vec::new(),
446            casecuritycollected: false,
447            enrollmentagentrestrictionscollected: false,
448            isuserspecifiessanenabledcollected: false,
449            roleseparationenabledcollected: false,
450       }
451    }
452 }
453
454// CARegistryData properties structure
455#[derive(Debug, Clone, Deserialize, Serialize, Default)]
456pub struct CARegistryData {
457    #[serde(rename = "CASecurity")]
458    ca_security: CASecurity,
459    #[serde(rename = "EnrollmentAgentRestrictions")]
460    enrollment_agent_restrictions: EnrollmentAgentRestrictions,
461    #[serde(rename = "IsUserSpecifiesSanEnabled")]
462    is_user_specifies_san_enabled: IsUserSpecifiesSanEnabled,
463    #[serde(rename = "RoleSeparationEnabled")]
464    role_separation_enabled: RoleSeparationEnabled,
465}
466
467impl CARegistryData {
468    pub fn new(
469        ca_security: CASecurity,
470    ) -> Self { 
471        Self { 
472            ca_security,
473            ..Default::default()
474        }
475    }
476}
477
478// CASecurity properties structure
479#[derive(Debug, Clone, Deserialize, Serialize)]
480pub struct CASecurity {
481    #[serde(rename = "Data")]
482    data: Vec<AceTemplate>,
483    #[serde(rename = "Collected")]
484    collected: bool,
485    #[serde(rename = "FailureReason")]
486    failure_reason: Option<String>,
487}
488
489
490impl Default for CASecurity {
491    fn default() -> CASecurity {
492        CASecurity {
493            data: Vec::new(),
494            collected: true,
495            failure_reason: None,
496        }
497    }
498}
499
500// EnrollmentAgentRestrictions properties structure
501#[derive(Debug, Clone, Deserialize, Serialize)]
502pub struct EnrollmentAgentRestrictions {
503    #[serde(rename = "Restrictions")]
504    restrictions: Vec<String>, // data to validate
505    #[serde(rename = "Collected")]
506    collected: bool,
507    #[serde(rename = "FailureReason")]
508    failure_reason: Option<String>,
509}
510
511impl Default for EnrollmentAgentRestrictions {
512    fn default() -> EnrollmentAgentRestrictions {
513        EnrollmentAgentRestrictions {
514            restrictions: Vec::new(),
515            collected: true,
516            failure_reason: None,
517        }
518    }
519}
520
521// IsUserSpecifiesSanEnabled properties structure
522#[derive(Debug, Clone, Deserialize, Serialize)]
523pub struct IsUserSpecifiesSanEnabled {
524    #[serde(rename = "Value")]
525    value: bool,
526    #[serde(rename = "Collected")]
527    collected: bool,
528    #[serde(rename = "FailureReason")]
529    failure_reason: Option<String>,
530}
531
532impl Default for IsUserSpecifiesSanEnabled {
533    fn default() -> IsUserSpecifiesSanEnabled {
534        IsUserSpecifiesSanEnabled {
535            value: false,
536            collected: true,
537            failure_reason: None,
538        }
539    }
540}
541
542// RoleSeparationEnabled properties structure
543#[derive(Debug, Clone, Deserialize, Serialize)]
544pub struct RoleSeparationEnabled {
545    #[serde(rename = "Value")]
546    value: bool,
547    #[serde(rename = "Collected")]
548    collected: bool,
549    #[serde(rename = "FailureReason")]
550    failure_reason: Option<String>,
551}
552
553impl Default for RoleSeparationEnabled {
554    fn default() -> RoleSeparationEnabled {
555        RoleSeparationEnabled {
556            value: false,
557            collected: true,
558            failure_reason: None,
559        }
560    }
561}