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                    self.properties.objectguid = guid;
108                }
109                "nTSecurityDescriptor" => {
110                    // nTSecurityDescriptor raw to string
111                    let relations_ace = parse_ntsecuritydescriptor(
112                        self,
113                        &value[0],
114                        "AIACA",
115                        &result_attrs,
116                        &result_bin,
117                        domain,
118                        schema_guid_map,
119                    );
120                    self.aces = relations_ace;
121                }
122                "cACertificate" => {
123                    //info!("{:?}:{:?}", key,value[0].to_owned());
124                    let certsha1: String = calculate_sha1(&value[0]);
125                    self.properties.certthumbprint = certsha1.to_owned();
126                    self.properties.certname = certsha1.to_owned();
127                    self.properties.certchain = vec![certsha1.to_owned()];
128
129                    // Parsing certificate.
130                    let res = X509Certificate::from_der(&value[0]);
131                    match res {
132                        Ok((_rem, cert)) => {
133                            // println!("Basic Constraints Extensions:");
134                            for ext in cert.extensions() {
135                                // println!("{:?} : {:?}",&ext.oid, ext);
136                                if &ext.oid == &oid!(2.5.29.19) {
137                                    // <https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.BasicConstraints.html>
138                                    if let ParsedExtension::BasicConstraints(basic_constraints) = &ext.parsed_extension() {
139                                        let _ca = &basic_constraints.ca;
140                                        let _path_len_constraint = &basic_constraints.path_len_constraint;
141                                        // println!("ca: {:?}", _ca);
142                                        // println!("path_len_constraint: {:?}", _path_len_constraint);
143                                        match _path_len_constraint {
144                                            Some(_path_len_constraint) => {
145                                                if _path_len_constraint > &0 {
146                                                    self.properties.hasbasicconstraints = true;
147                                                    self.properties.basicconstraintpathlength = _path_len_constraint.to_owned();
148
149                                                } else {
150                                                    self.properties.hasbasicconstraints = false;
151                                                    self.properties.basicconstraintpathlength = 0;
152                                                }
153                                            },
154                                            None => {
155                                                self.properties.hasbasicconstraints = false;
156                                                self.properties.basicconstraintpathlength = 0;
157                                            }
158                                        }
159                                    }
160                                }
161                            }
162                        },
163                        _ => error!("CA x509 certificate parsing failed: {:?}", res),
164                    }
165                }
166                _ => {}
167            }
168        }
169
170        // Push DN and SID in HashMap
171        if self.object_identifier != "SID" {
172            dn_sid.insert(
173                self.properties.distinguishedname.to_owned(),
174                self.object_identifier.to_owned()
175            );
176            // Push DN and Type
177            sid_type.insert(
178                self.object_identifier.to_owned(),
179                "AIACA".to_string()
180            );
181        }
182
183        // Trace and return AIACA struct
184        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
185        Ok(())
186    }
187}
188
189impl LdapObject for AIACA {
190    // To JSON
191    fn to_json(&self) -> Value {
192        serde_json::to_value(self).unwrap()
193    }
194
195    // Get values
196    fn get_object_identifier(&self) -> &String {
197        &self.object_identifier
198    }
199    fn get_is_acl_protected(&self) -> &bool {
200        &self.is_acl_protected
201    }
202    fn get_aces(&self) -> &Vec<AceTemplate> {
203        &self.aces
204    }
205    fn get_spntargets(&self) -> &Vec<SPNTarget> {
206        panic!("Not used by current object.");
207    }
208    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
209        panic!("Not used by current object.");
210    }
211    fn get_links(&self) -> &Vec<Link> {
212        panic!("Not used by current object.");
213    }
214    fn get_contained_by(&self) -> &Option<Member> {
215        &self.contained_by
216    }
217    fn get_child_objects(&self) -> &Vec<Member> {
218        panic!("Not used by current object.");
219    }
220    fn get_haslaps(&self) -> &bool {
221        &false
222    }
223    
224    // Get mutable values
225    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
226        &mut self.aces
227    }
228    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
229        panic!("Not used by current object.");
230    }
231    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
232        panic!("Not used by current object.");
233    }
234    
235    // Edit values
236    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
237        self.is_acl_protected = is_acl_protected;
238        self.properties.isaclprotected = is_acl_protected;
239    }
240    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
241        self.aces = aces;
242    }
243    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
244        // Not used by current object.
245    }
246    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
247        // Not used by current object.
248    }
249    fn set_links(&mut self, _links: Vec<Link>) {
250        // Not used by current object.
251    }
252    fn set_contained_by(&mut self, contained_by: Option<Member>) {
253        self.contained_by = contained_by;
254    }
255    fn set_child_objects(&mut self, _child_objects: Vec<Member>) {
256        // Not used by current object.
257    }
258    fn set_owner_rights_flags(&mut self, any: bool, any_inherited: bool) {
259        self.properties.doesanyacegrantownerrights = any;
260        self.properties.doesanyinheritedacegrantownerrights = any_inherited;
261    }
262}
263
264
265// AIACA properties structure
266#[derive(Debug, Clone, Deserialize, Serialize)]
267pub struct AIACAProperties {
268    domain: String,
269    name: String,
270    distinguishedname: String,
271    domainsid: String,
272    objectguid: String,
273    doesanyacegrantownerrights: bool,
274    doesanyinheritedacegrantownerrights: bool,
275    isaclprotected: bool,
276    description: Option<String>,
277    whencreated: i64,
278    crosscertificatepair: Vec<String>,
279    hascrosscertificatepair: bool,
280    certthumbprint: String,
281    certname: String,
282    certchain: Vec<String>,
283    hasbasicconstraints: bool,
284    basicconstraintpathlength: u32,
285}
286
287impl Default for AIACAProperties {
288    fn default() -> AIACAProperties {
289        AIACAProperties {
290            domain: String::from(""),
291            name: String::from(""),
292            distinguishedname: String::from(""),
293            domainsid: String::from(""),
294            objectguid: String::from(""),
295            doesanyacegrantownerrights: false,
296            doesanyinheritedacegrantownerrights: false,
297            isaclprotected: false,
298            description: None,
299            whencreated: -1,
300            crosscertificatepair: Vec::new(),
301            hascrosscertificatepair: false,
302            certthumbprint: String::from(""),
303            certname: String::from(""),
304            certchain: Vec::new(),
305            hasbasicconstraints: false,
306            basicconstraintpathlength: 0,
307       }
308    }
309}