Skip to main content

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