Skip to main content

rusthound_ce/objects/
rootca.rs

1use serde_json::value::Value;
2use serde::{Deserialize, Serialize};
3use x509_parser::oid_registry::asn1_rs::oid;
4use x509_parser::prelude::*;
5use ldap3::SearchEntry;
6use log::{debug, error, trace};
7use std::collections::HashMap;
8use std::error::Error;
9
10use crate::objects::common::{LdapObject, AceTemplate, SPNTarget, Link, Member};
11use crate::enums::{decode_guid_le, parse_ntsecuritydescriptor};
12use crate::utils::date::string_to_epoch;
13use crate::utils::crypto::calculate_sha1;
14
15
16/// RootCA structure
17#[derive(Debug, Clone, Deserialize, Serialize, Default)]
18pub struct RootCA {
19    #[serde(rename = "Properties")]
20    properties: RootCAProperties,
21    #[serde(rename = "DomainSID")]
22    domain_sid: String,
23    #[serde(rename = "Aces")]
24    aces: Vec<AceTemplate>,
25    #[serde(rename = "ObjectIdentifier")]
26    object_identifier: String,
27    #[serde(rename = "IsDeleted")]
28    is_deleted: bool,
29    #[serde(rename = "IsACLProtected")]
30    is_acl_protected: bool,
31    #[serde(rename = "ContainedBy")]
32    contained_by: Option<Member>,
33}
34
35impl RootCA {
36    // New RootCA
37    pub fn new() -> Self { 
38        Self { ..Default::default() } 
39    }
40
41    /// Function to parse and replace value in json template for ROOT CA object.
42    pub fn parse(
43        &mut self,
44        result: SearchEntry,
45        domain: &str,
46        dn_sid: &mut HashMap<String, String>,
47        sid_type: &mut HashMap<String, String>,
48        domain_sid: &str,
49        schema_guid_map: &HashMap<String, String>,
50    ) -> Result<(), Box<dyn Error>> {
51        let result_dn: String = result.dn.to_uppercase();
52        let result_attrs: HashMap<String, Vec<String>> = result.attrs;
53        let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;
54
55        // Debug for current object
56        debug!("Parse RootCA: {result_dn}");
57
58        // Trace all result attributes
59        for (key, value) in &result_attrs {
60            trace!("  {key:?}:{value:?}");
61        }
62        // Trace all bin result attributes
63        for (key, value) in &result_bin {
64            trace!("  {key:?}:{value:?}");
65        }
66
67        // Change all values...
68        self.properties.domain = domain.to_uppercase();
69        self.properties.distinguishedname = result_dn;    
70        self.properties.domainsid = domain_sid.to_string();
71        self.domain_sid = domain_sid.to_string();
72
73        // With a check
74        for (key, value) in &result_attrs {
75            match key.as_str() {
76                "name" => {
77                    let name = format!("{}@{}", &value[0], domain);
78                    self.properties.name = name.to_uppercase();
79                }
80                "description" => {
81                    self.properties.description = value.first().cloned();
82                }
83                "whenCreated" => {
84                    let epoch = string_to_epoch(&value[0])?;
85                    if epoch.is_positive() {
86                        self.properties.whencreated = epoch;
87                    }
88                }
89                "IsDeleted" => {
90                    self.is_deleted = true;
91                }
92                _ => {}
93            }
94        }
95
96        // For all, bins attributs
97        for (key, value) in &result_bin {
98            match key.as_str() {
99                "objectGUID" => {
100                    // objectGUID raw to string
101                    self.object_identifier = decode_guid_le(&value[0]).to_owned();
102                }
103                "nTSecurityDescriptor" => {
104                    // nTSecurityDescriptor raw to string
105                    let relations_ace = parse_ntsecuritydescriptor(
106                        self,
107                        &value[0],
108                        "RootCA",
109                        &result_attrs,
110                        &result_bin,
111                        domain,
112                        schema_guid_map,
113                    );
114                    self.aces = relations_ace;
115                }
116                "cACertificate" => {
117                    //info!("{:?}:{:?}", key,value[0].to_owned());
118                    let certsha1: String = calculate_sha1(&value[0]);
119                    self.properties.certthumbprint = certsha1.to_string();
120                    self.properties.certname = certsha1.to_string();
121                    self.properties.certchain = vec![certsha1.to_string()];
122
123                    // Parsing certificate.
124                    let res = X509Certificate::from_der(&value[0]);
125                    match res {
126                        Ok((_rem, cert)) => {
127                            // println!("Basic Constraints Extensions:");
128                            for ext in cert.extensions() {
129                                // println!("{:?} : {:?}",&ext.oid, ext);
130                                if &ext.oid == &oid!(2.5.29.19) {
131                                    // <https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.BasicConstraints.html>
132                                    if let ParsedExtension::BasicConstraints(basic_constraints) = &ext.parsed_extension() {
133                                        let _ca = &basic_constraints.ca;
134                                        let _path_len_constraint = &basic_constraints.path_len_constraint;
135                                        // println!("ca: {:?}", _ca);
136                                        // println!("path_len_constraint: {:?}", _path_len_constraint);
137                                        match _path_len_constraint {
138                                            Some(_path_len_constraint) => {
139                                                if _path_len_constraint > &0 {
140                                                    self.properties.hasbasicconstraints = true;
141                                                    self.properties.basicconstraintpathlength = _path_len_constraint.to_owned();
142
143                                                } else {
144                                                    self.properties.hasbasicconstraints = false;
145                                                    self.properties.basicconstraintpathlength = 0_u32;
146                                                }
147                                            },
148                                            None => {
149                                                self.properties.hasbasicconstraints = false;
150                                                self.properties.basicconstraintpathlength = 0_u32;
151                                            }
152                                        }
153                                    }
154                                }
155                            }
156                        },
157                        _ => error!("CA x509 certificate parsing failed: {:?}", res),
158                    }
159                }
160                _ => {}
161            }
162        }
163
164        // Push DN and SID in HashMap
165        if self.object_identifier != "SID" {
166            dn_sid.insert(
167                self.properties.distinguishedname.to_string(),
168                self.object_identifier.to_string()
169            );
170            // Push DN and Type
171            sid_type.insert(
172                self.object_identifier.to_string(),
173                "RootCA".to_string()
174            );
175        }
176
177        // Trace and return RootCA struct
178        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
179        Ok(())
180    }
181}
182
183impl LdapObject for RootCA {
184    // To JSON
185    fn to_json(&self) -> Value {
186        serde_json::to_value(self).unwrap()
187    }
188
189    // Get values
190    fn get_object_identifier(&self) -> &String {
191        &self.object_identifier
192    }
193    fn get_is_acl_protected(&self) -> &bool {
194        &self.is_acl_protected
195    }
196    fn get_aces(&self) -> &Vec<AceTemplate> {
197        &self.aces
198    }
199    fn get_spntargets(&self) -> &Vec<SPNTarget> {
200        panic!("Not used by current object.");
201    }
202    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
203        panic!("Not used by current object.");
204    }
205    fn get_links(&self) -> &Vec<Link> {
206        panic!("Not used by current object.");
207    }
208    fn get_contained_by(&self) -> &Option<Member> {
209        &self.contained_by
210    }
211    fn get_child_objects(&self) -> &Vec<Member> {
212        panic!("Not used by current object.");
213    }
214    fn get_haslaps(&self) -> &bool {
215        &false
216    }
217    
218    // Get mutable values
219    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
220        &mut self.aces
221    }
222    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
223        panic!("Not used by current object.");
224    }
225    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
226        panic!("Not used by current object.");
227    }
228    
229    // Edit values
230    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
231        self.is_acl_protected = is_acl_protected;
232        self.properties.isaclprotected = is_acl_protected;
233    }
234    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
235        self.aces = aces;
236    }
237    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
238        // Not used by current object.
239    }
240    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
241        // Not used by current object.
242    }
243    fn set_links(&mut self, _links: Vec<Link>) {
244        // Not used by current object.
245    }
246    fn set_contained_by(&mut self, contained_by: Option<Member>) {
247        self.contained_by = contained_by;
248    }
249    fn set_child_objects(&mut self, _child_objects: Vec<Member>) {
250        // Not used by current object.
251    }
252}
253
254
255// RootCA properties structure
256#[derive(Debug, Clone, Deserialize, Serialize)]
257pub struct RootCAProperties {
258   domain: String,
259   name: String,
260   distinguishedname: String,
261   domainsid: String,
262   isaclprotected: bool,
263   description: Option<String>,
264   whencreated: i64,
265   certthumbprint: String,
266   certname: String,
267   certchain: Vec<String>,
268   hasbasicconstraints: bool,
269   basicconstraintpathlength: u32,
270}
271
272impl Default for RootCAProperties {
273    fn default() -> RootCAProperties {
274        RootCAProperties {
275            domain: String::from(""),
276            name: String::from(""),
277            distinguishedname: String::from(""),
278            domainsid: String::from(""),
279            isaclprotected: false,
280            description: None,
281            whencreated: -1,
282            certthumbprint: String::from(""),
283            certname: String::from(""),
284            certchain: Vec::new(),
285            hasbasicconstraints: false,
286            basicconstraintpathlength: 0,
287       }
288    }
289}