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                    self.properties.objectguid = guid;
183                }
184                "nTSecurityDescriptor" => {
185                    // nTSecurityDescriptor raw to string
186                    let relations_ace = parse_ntsecuritydescriptor(
187                        self,
188                        &value[0],
189                        "EnterpriseCA",
190                        &result_attrs,
191                        &result_bin,
192                        domain,
193                        schema_guid_map,
194                    );
195                    // Aces
196                    self.aces = relations_ace;
197                    // HostingComputer
198                    self.hosting_computer = Self::get_hosting_computer(&value[0], domain);
199                    // CASecurity
200                    let ca_security_data = parse_ca_security(&value[0], &self.hosting_computer, domain);
201                    if !ca_security_data.is_empty() {
202                        let ca_security = CASecurity {
203                            data: ca_security_data,
204                            collected: true,
205                            failure_reason: None,
206                        };
207                        self.properties.casecuritycollected = true;
208                        let ca_registry_data = CARegistryData::new(ca_security);
209                        self.ca_registry_data = ca_registry_data;
210                    } else {
211                        let ca_security = CASecurity {
212                            data: Vec::new(),
213                            collected: false,
214                            failure_reason: Some(String::from("Failed to get CASecurity!"))
215                        };
216                        self.properties.casecuritycollected = false;
217                        let ca_registry_data = CARegistryData::new(ca_security);
218                        self.ca_registry_data = ca_registry_data;
219                    }
220                }
221                "cACertificate" => {
222                    //info!("{:?}:{:?}", key,value[0].to_owned());
223                    let certsha1: String = calculate_sha1(&value[0]);
224                    self.properties.certthumbprint = certsha1.to_owned();
225                    self.properties.certname = certsha1.to_owned();
226                    self.properties.certchain = vec![certsha1.to_owned()];
227
228                    // Parsing certificate.
229                    let res = X509Certificate::from_der(&value[0]);
230                    match res {
231                        Ok((_rem, cert)) => {
232                            // println!("Basic Constraints Extensions:");
233                            for ext in cert.extensions() {
234                                // println!("{:?} : {:?}",&ext.oid, ext);
235                                if &ext.oid == &oid!(2.5.29.19) {
236                                    // <https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.BasicConstraints.html>
237                                    if let ParsedExtension::BasicConstraints(basic_constraints) = &ext.parsed_extension() {
238                                        let _ca = &basic_constraints.ca;
239                                        let _path_len_constraint = &basic_constraints.path_len_constraint;
240                                        // println!("ca: {:?}", _ca);
241                                        // println!("path_len_constraint: {:?}", _path_len_constraint);
242                                        match _path_len_constraint {
243                                            Some(_path_len_constraint) => {
244                                                if _path_len_constraint > &0 {
245                                                    self.properties.hasbasicconstraints = true;
246                                                    self.properties.basicconstraintpathlength = _path_len_constraint.to_owned();
247
248                                                } else {
249                                                    self.properties.hasbasicconstraints = false;
250                                                    self.properties.basicconstraintpathlength = 0;
251                                                }
252                                            }
253                                            None => {
254                                                self.properties.hasbasicconstraints = false;
255                                                self.properties.basicconstraintpathlength = 0;
256                                            }
257                                        }
258                                    }
259                                }
260                            }
261                        },
262                        _ => error!("CA x509 certificate parsing failed: {:?}", res),
263                    }
264                }
265                _ => {}
266            }
267        }
268
269        // Push DN and SID in HashMap
270        if self.object_identifier != "SID" {
271            dn_sid.insert(
272                self.properties.distinguishedname.to_string(),
273                self.object_identifier.to_string(),
274            );
275            // Push DN and Type
276            sid_type.insert(
277                self.object_identifier.to_string(),
278                "EnterpriseCA".to_string(),
279            );
280        }
281
282        // Trace and return EnterpriseCA struct
283        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
284        Ok(())
285    }
286
287    /// Function to get HostingComputer from ACL if ACE get ManageCertificates and is not Group.
288    fn get_hosting_computer(
289        nt: &[u8],
290        domain: &str,
291    ) -> String {
292        let mut hosting_computer = String::from("Not found");
293        let blacklist_sid = [
294            // <https://learn.microsoft.com/fr-fr/windows-server/identity/ad-ds/manage/understand-security-identifiers>
295            "-544", // Administrators
296            "-519", // Enterprise Administrators
297            "-512", // Domain Admins
298        ];
299        let secdesc: SecurityDescriptor = SecurityDescriptor::parse(nt).unwrap().1;
300        if secdesc.offset_dacl as usize != 0 
301        {
302            let res = Acl::parse(&nt[secdesc.offset_dacl as usize..]);
303            match res {
304                Ok(_res) => {
305                    let dacl = _res.1;
306                    let aces = dacl.data;
307                    for ace in aces {
308                        if ace.ace_type == 0x00 {
309                            let sid = sid_maker(AceFormat::get_sid(ace.data.to_owned()).unwrap(), domain);
310                            let mask = match AceFormat::get_mask(&ace.data) {
311                                Some(mask) => mask,
312                                None => continue,
313                            };
314                            if (MaskFlags::MANAGE_CERTIFICATES.bits() | mask) == mask
315                            && !blacklist_sid.iter().any(|blacklisted| sid.ends_with(blacklisted)) 
316                            {
317                                // println!("SID MANAGE_CERTIFICATES: {:?}",&sid);
318                                hosting_computer = sid;
319                                return hosting_computer
320                            }
321                        }
322                    }
323                },
324                Err(err) => error!("Error. Reason: {err}")
325            }
326        }
327        hosting_computer
328    }
329}
330
331impl LdapObject for EnterpriseCA {
332    // To JSON
333    fn to_json(&self) -> Value {
334        serde_json::to_value(self).unwrap()
335    }
336
337    // Get values
338    fn get_object_identifier(&self) -> &String {
339        &self.object_identifier
340    }
341    fn get_is_acl_protected(&self) -> &bool {
342        &self.is_acl_protected
343    }
344    fn get_aces(&self) -> &Vec<AceTemplate> {
345        &self.aces
346    }
347    fn get_spntargets(&self) -> &Vec<SPNTarget> {
348        panic!("Not used by current object.");
349    }
350    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
351        panic!("Not used by current object.");
352    }
353    fn get_links(&self) -> &Vec<Link> {
354        panic!("Not used by current object.");
355    }
356    fn get_contained_by(&self) -> &Option<Member> {
357        &self.contained_by
358    }
359    fn get_child_objects(&self) -> &Vec<Member> {
360        panic!("Not used by current object.");
361    }
362    fn get_haslaps(&self) -> &bool {
363        &false
364    }
365
366    // Get mutable values
367    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
368        &mut self.aces
369    }
370    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
371        panic!("Not used by current object.");
372    }
373    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
374        panic!("Not used by current object.");
375    }
376
377    // Edit values
378    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
379        self.is_acl_protected = is_acl_protected;
380        self.properties.isaclprotected = is_acl_protected;
381    }
382    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
383        self.aces = aces;
384    }
385    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
386        // Not used by current object.
387    }
388    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
389        // Not used by current object.
390    }
391    fn set_links(&mut self, _links: Vec<Link>) {
392        // Not used by current object.
393    }
394    fn set_contained_by(&mut self, contained_by: Option<Member>) {
395        self.contained_by = contained_by;
396    }
397    fn set_child_objects(&mut self, _child_objects: Vec<Member>) {
398        // Not used by current object.
399    }
400    fn set_owner_rights_flags(&mut self, any: bool, any_inherited: bool) {
401        self.properties.doesanyacegrantownerrights = any;
402        self.properties.doesanyinheritedacegrantownerrights = any_inherited;
403    }
404}
405
406
407// EnterpriseCA properties structure
408#[derive(Debug, Clone, Deserialize, Serialize)]
409pub struct EnterpriseCAProperties {
410    domain: String,
411    name: String,
412    distinguishedname: String,
413    domainsid: String,
414    objectguid: String,
415    doesanyacegrantownerrights: bool,
416    doesanyinheritedacegrantownerrights: bool,
417    isaclprotected: bool,
418    description: Option<String>,
419    whencreated: i64,
420    flags: String,
421    caname: String,
422    dnshostname: String,
423    certthumbprint: String,
424    certname: String,
425    certchain: Vec<String>,
426    hasbasicconstraints: bool,
427    basicconstraintpathlength: u32,
428    unresolvedpublishedtemplates: Vec<String>,
429    casecuritycollected: bool,
430    enrollmentagentrestrictionscollected: bool,
431    isuserspecifiessanenabledcollected: bool,
432    roleseparationenabledcollected: bool,
433}
434
435impl Default for EnterpriseCAProperties {
436    fn default() -> EnterpriseCAProperties {
437        EnterpriseCAProperties {
438            domain: String::from(""),
439            name: String::from(""),
440            distinguishedname: String::from(""),
441            domainsid: String::from(""),
442            objectguid: String::from(""),
443            doesanyacegrantownerrights: false,
444            doesanyinheritedacegrantownerrights: false,
445            isaclprotected: false,
446            description: None,
447            whencreated: -1,
448            flags: String::from(""),
449            caname: String::from(""),
450            dnshostname: String::from(""),
451            certthumbprint: String::from(""),
452            certname: String::from(""),
453            certchain: Vec::new(),
454            hasbasicconstraints: false,
455            basicconstraintpathlength: 0,
456            unresolvedpublishedtemplates: Vec::new(),
457            casecuritycollected: false,
458            enrollmentagentrestrictionscollected: false,
459            isuserspecifiessanenabledcollected: false,
460            roleseparationenabledcollected: false,
461       }
462    }
463 }
464
465// CARegistryData properties structure
466#[derive(Debug, Clone, Deserialize, Serialize, Default)]
467pub struct CARegistryData {
468    #[serde(rename = "CASecurity")]
469    ca_security: CASecurity,
470    #[serde(rename = "EnrollmentAgentRestrictions")]
471    enrollment_agent_restrictions: EnrollmentAgentRestrictions,
472    #[serde(rename = "IsUserSpecifiesSanEnabled")]
473    is_user_specifies_san_enabled: IsUserSpecifiesSanEnabled,
474    #[serde(rename = "RoleSeparationEnabled")]
475    role_separation_enabled: RoleSeparationEnabled,
476}
477
478impl CARegistryData {
479    pub fn new(
480        ca_security: CASecurity,
481    ) -> Self { 
482        Self { 
483            ca_security,
484            ..Default::default()
485        }
486    }
487}
488
489// CASecurity properties structure
490#[derive(Debug, Clone, Deserialize, Serialize)]
491pub struct CASecurity {
492    #[serde(rename = "Data")]
493    data: Vec<AceTemplate>,
494    #[serde(rename = "Collected")]
495    collected: bool,
496    #[serde(rename = "FailureReason")]
497    failure_reason: Option<String>,
498}
499
500
501impl Default for CASecurity {
502    fn default() -> CASecurity {
503        CASecurity {
504            data: Vec::new(),
505            collected: true,
506            failure_reason: None,
507        }
508    }
509}
510
511// EnrollmentAgentRestrictions properties structure
512#[derive(Debug, Clone, Deserialize, Serialize)]
513pub struct EnrollmentAgentRestrictions {
514    #[serde(rename = "Restrictions")]
515    restrictions: Vec<String>, // data to validate
516    #[serde(rename = "Collected")]
517    collected: bool,
518    #[serde(rename = "FailureReason")]
519    failure_reason: Option<String>,
520}
521
522impl Default for EnrollmentAgentRestrictions {
523    fn default() -> EnrollmentAgentRestrictions {
524        EnrollmentAgentRestrictions {
525            restrictions: Vec::new(),
526            collected: true,
527            failure_reason: None,
528        }
529    }
530}
531
532// IsUserSpecifiesSanEnabled properties structure
533#[derive(Debug, Clone, Deserialize, Serialize)]
534pub struct IsUserSpecifiesSanEnabled {
535    #[serde(rename = "Value")]
536    value: bool,
537    #[serde(rename = "Collected")]
538    collected: bool,
539    #[serde(rename = "FailureReason")]
540    failure_reason: Option<String>,
541}
542
543impl Default for IsUserSpecifiesSanEnabled {
544    fn default() -> IsUserSpecifiesSanEnabled {
545        IsUserSpecifiesSanEnabled {
546            value: false,
547            collected: true,
548            failure_reason: None,
549        }
550    }
551}
552
553// RoleSeparationEnabled properties structure
554#[derive(Debug, Clone, Deserialize, Serialize)]
555pub struct RoleSeparationEnabled {
556    #[serde(rename = "Value")]
557    value: bool,
558    #[serde(rename = "Collected")]
559    collected: bool,
560    #[serde(rename = "FailureReason")]
561    failure_reason: Option<String>,
562}
563
564impl Default for RoleSeparationEnabled {
565    fn default() -> RoleSeparationEnabled {
566        RoleSeparationEnabled {
567            value: false,
568            collected: true,
569            failure_reason: None,
570        }
571    }
572}