Skip to main content

rusthound_ce/objects/
domain.rs

1use serde_json::value::Value;
2use serde::{Deserialize, Serialize};
3use colored::Colorize;
4use ldap3::SearchEntry;
5use log::{info, debug, trace};
6use std::collections::HashMap;
7use std::error::Error;
8
9use crate::enums::regex::OBJECT_SID_RE1;
10use crate::objects::common::{LdapObject, GPOChange, Link, AceTemplate, SPNTarget, Member};
11use crate::objects::trust::Trust;
12use crate::utils::date::{span_to_string, string_to_epoch};
13use crate::enums::acl::parse_ntsecuritydescriptor;
14use crate::enums::forestlevel::get_forest_level;
15use crate::enums::gplink::parse_gplink;
16use crate::enums::secdesc::LdapSid;
17use crate::enums::sid::sid_maker;
18
19/// Domain structure
20#[derive(Debug, Clone, Deserialize, Serialize, Default)]
21pub struct Domain {
22    #[serde(rename = "Properties")]
23    properties: DomainProperties,
24    #[serde(rename = "GPOChanges")]
25    gpo_changes: GPOChange,
26    #[serde(rename = "ChildObjects")]
27    child_objects: Vec<Member>,
28    #[serde(rename = "Trusts")]
29    trusts: Vec<Trust>,
30    #[serde(rename = "Links")]
31    links: Vec<Link>,
32    #[serde(rename = "Aces")]
33    aces: Vec<AceTemplate>,
34    #[serde(rename = "ObjectIdentifier")]
35    object_identifier: String,
36    #[serde(rename = "IsDeleted")]
37    is_deleted: bool,
38    #[serde(rename = "IsACLProtected")]
39    is_acl_protected: bool,
40    #[serde(rename = "ContainedBy")]
41    contained_by: Option<Member>,
42}
43
44impl Domain {
45    // New domain.
46    pub fn new() -> Self { 
47        Self { ..Default::default() } 
48    }
49
50    // Get access.
51    pub fn object_identifier(&self) -> &String {
52        &self.object_identifier
53    }
54    pub fn properties(&self) -> &DomainProperties { 
55        &self.properties
56    }
57
58    // Mutable access.
59    pub fn properties_mut(&mut self) -> &mut DomainProperties {
60        &mut self.properties
61    }
62    pub fn object_identifier_mut(&mut self) -> &mut String {
63        &mut self.object_identifier
64    }
65    pub fn gpo_changes_mut(&mut self) -> &mut GPOChange {
66        &mut self.gpo_changes
67    }
68    pub fn trusts_mut(&mut self) -> &mut Vec<Trust> {
69        &mut self.trusts
70    }
71
72    /// Function to parse and replace value for domain object.
73    /// <https://bloodhound.readthedocs.io/en/latest/further-reading/json.html#domains>
74    pub fn parse(
75        &mut self,
76        result: SearchEntry,
77        domain_name: &str,
78        dn_sid: &mut HashMap<String, String>,
79        sid_type: &mut HashMap<String, String>,
80        schema_guid_map: &HashMap<String, String>,
81    ) -> Result<String, Box<dyn Error>> {
82        let result_dn: String = result.dn.to_uppercase();
83        let result_attrs: HashMap<String, Vec<String>> = result.attrs;
84        let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;
85
86        // Debug for current object
87        debug!("Parse domain: {result_dn}");
88
89        // Trace all result attributes
90        for (key, value) in &result_attrs {
91            trace!("  {key:?}:{value:?}");
92        }
93        // Trace all bin result attributes
94        for (key, value) in &result_bin {
95            trace!("  {key:?}:{value:?}");
96        }
97
98        // Change all values...
99        self.properties.domain = domain_name.to_uppercase();
100        self.properties.distinguishedname = result_dn;
101
102        // Change all values...
103        #[allow(unused_assignments)]
104        let mut sid: String = "".to_owned();
105        let mut global_domain_sid: String = "DOMAIN_SID".to_owned();
106        // With a check
107        for (key, value) in &result_attrs {
108            match key.as_str() {
109                "distinguishedName" => {
110                    // name & domain & distinguishedname
111                    self.properties.distinguishedname = value[0].to_owned().to_uppercase();
112                    let name = value[0]
113                        .split(",")
114                        .filter(|x| x.starts_with("DC="))
115                        .map(|x| x.strip_prefix("DC=").unwrap_or(""))
116                        .collect::<Vec<&str>>()
117                        .join(".");
118                    self.properties.name = name.to_uppercase();
119                    self.properties.domain = name.to_uppercase();
120                }
121                "msDS-Behavior-Version" => {
122                    let level = get_forest_level(value[0].to_string());
123                    self.properties.functionallevel  = level;
124                }
125                "whenCreated" => {
126                    let epoch = string_to_epoch(&value[0])?;
127                    if epoch.is_positive() {
128                        self.properties.whencreated = epoch;
129                    }
130                }
131                "gPLink" => {
132                    self.links = parse_gplink(value[0].to_string())?;
133                }
134                "isCriticalSystemObject" => {
135                    self.properties.highvalue = value[0].contains("TRUE");
136                }
137                // The number of computer accounts that a user is allowed to create in a domain.
138                "ms-DS-MachineAccountQuota" => {
139                    let machine_account_quota = value[0].parse::<i32>().unwrap_or(0);
140                    self.properties.machineaccountquota = machine_account_quota;
141                    if machine_account_quota > 0 {
142                        info!("MachineAccountQuota: {}", machine_account_quota.to_string().yellow().bold());
143                    }
144                }
145                "isDeleted" => {
146                    self.is_deleted = true;
147                }
148                "msDS-ExpirePasswordsOnSmartCardOnlyAccounts" => {
149                    self.properties.expirepasswordsonsmartcardonlyaccounts = true;
150                }
151                "dSHeuristics" => {
152                    // A tiny string with a surprisingly large responsibility.
153                    self.properties.dsheuristics = value[0].to_owned();
154                }
155                "minPwdLength" => {
156                    self.properties.minpwdlength = value[0].parse::<i32>().unwrap_or(0);
157                }
158                "pwdProperties" => {
159                    self.properties.pwdproperties = value[0].parse::<i32>().unwrap_or(0);
160                }
161                "pwdHistoryLength" => {
162                    self.properties.pwdhistorylength = value[0].parse::<i32>().unwrap_or(0);
163                }
164                "lockoutThreshold" => {
165                    self.properties.lockoutthreshold = value[0].parse::<i32>().unwrap_or(0);
166                }
167                "minPwdAge" => {
168                    self.properties.minpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
169                }
170                "maxPwdAge" => {
171                    self.properties.maxpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
172                }
173                "lockoutDuration" => {
174                    self.properties.lockoutduration = span_to_string(value[0].parse::<i64>().unwrap_or(0));
175                }
176                "lockOutObservationWindow" => {
177                    self.properties.lockoutobservationwindow = value[0].parse::<i64>().unwrap_or(0);
178                }
179                _ => {}
180            }
181        }
182
183        // For all, bins attributes
184        for (key, value) in &result_bin {
185            match key.as_str() {
186                "objectSid" => {
187                    // objectSid raw to string
188                    sid = sid_maker(LdapSid::parse(&value[0]).unwrap().1, domain_name);
189                    self.object_identifier = sid.to_owned();
190
191                    for domain_sid in OBJECT_SID_RE1.captures_iter(&sid) {
192                        self.properties.domainsid = domain_sid[0].to_owned().to_string();
193                        global_domain_sid = domain_sid[0].to_owned().to_string();
194                    }
195
196                    // Data Quality flag
197                    self.properties.collected = true;
198                }
199                "nTSecurityDescriptor" => {
200                    // nTSecurityDescriptor raw to string
201                    let relations_ace = parse_ntsecuritydescriptor(
202                        self,
203                        &value[0],
204                        "Domain",
205                        &result_attrs,
206                        &result_bin,
207                        domain_name,
208                        schema_guid_map,
209                    );
210                    self.aces = relations_ace;
211                }
212                _ => {}
213            }
214        }
215
216        // Push DN and SID in HashMap
217        dn_sid.insert(
218        self.properties.distinguishedname.to_string(),
219        self.object_identifier.to_string()
220        );
221        // Push DN and Type
222        sid_type.insert(
223            self.object_identifier.to_string(),
224            "Domain".to_string(),
225        );
226
227        // Trace and return Domain struct
228        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
229        Ok(global_domain_sid)
230    }
231}
232
233impl LdapObject for Domain {
234    // To JSON
235    fn to_json(&self) -> Value {
236        serde_json::to_value(self).unwrap()
237    }
238
239    // Get values
240    fn get_object_identifier(&self) -> &String {
241        &self.object_identifier
242    }
243    fn get_is_acl_protected(&self) -> &bool {
244        &self.is_acl_protected
245    }
246    fn get_aces(&self) -> &Vec<AceTemplate> {
247        &self.aces
248    }
249    fn get_spntargets(&self) -> &Vec<SPNTarget> {
250        panic!("Not used by current object.");
251    }
252    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
253        panic!("Not used by current object.");
254    }
255    fn get_links(&self) -> &Vec<Link> {
256        &self.links
257    }
258    fn get_contained_by(&self) -> &Option<Member> {
259        &self.contained_by
260    }
261    fn get_child_objects(&self) -> &Vec<Member> {
262        &self.child_objects
263    }
264    fn get_haslaps(&self) -> &bool {
265        &false
266    }
267    
268    // Get mutable values
269    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
270        &mut self.aces
271    }
272    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
273        panic!("Not used by current object.");
274    }
275    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
276        panic!("Not used by current object.");
277    }
278    
279    // Edit values
280    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
281        self.is_acl_protected = is_acl_protected;
282        self.properties.isaclprotected = is_acl_protected;
283    }
284    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
285        self.aces = aces;
286    }
287    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
288        // Not used by current object.
289    }
290    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
291        // Not used by current object.
292    }
293    fn set_links(&mut self, links: Vec<Link>) {
294        self.links = links;
295    }
296    fn set_contained_by(&mut self, contained_by: Option<Member>) {
297        self.contained_by = contained_by;
298    }
299    fn set_child_objects(&mut self, child_objects: Vec<Member>) {
300        self.child_objects = child_objects
301    }
302}
303
304// Domain properties structure
305#[derive(Debug, Clone, Deserialize, Serialize, Default)]
306pub struct DomainProperties {
307    domain: String,
308    name: String,
309    distinguishedname: String,
310    domainsid: String,
311    isaclprotected: bool,
312    highvalue: bool,
313    description: Option<String>,
314    whencreated: i64,
315    machineaccountquota: i32,
316    expirepasswordsonsmartcardonlyaccounts: bool,
317    minpwdlength: i32,
318    pwdproperties: i32,
319    pwdhistorylength: i32,
320    lockoutthreshold: i32,
321    minpwdage: String,
322    maxpwdage: String,
323    lockoutduration: String,
324    lockoutobservationwindow: i64,
325    functionallevel: String,
326    dsheuristics: String,
327    collected: bool
328}
329
330impl DomainProperties {
331    // Get access.
332    pub fn distinguishedname(&self) -> &String {
333        &self.distinguishedname
334    }
335
336    // Mutable access.
337    pub fn domain_mut(&mut self) -> &mut String {
338       &mut self.domain
339    }
340    pub fn name_mut(&mut self) -> &mut String {
341       &mut self.name
342    }
343    pub fn highvalue_mut(&mut self) -> &mut bool {
344        &mut self.highvalue
345    }
346    pub fn distinguishedname_mut(&mut self) -> &mut String {
347        &mut self.distinguishedname
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn parse_preserves_dsheuristics_value() {
357        let mut domain = Domain::new();
358        let result = SearchEntry {
359            dn: "DC=example,DC=local".to_string(),
360            attrs: HashMap::from([(
361                "dSHeuristics".to_string(),
362                vec!["0000000001000001".to_string()],
363            )]),
364            bin_attrs: HashMap::new(),
365        };
366        let mut dn_sid = HashMap::new();
367        let mut sid_type = HashMap::new();
368        let schema_guid_map = HashMap::new();
369
370        domain
371            .parse(
372                result,
373                "example.local",
374                &mut dn_sid,
375                &mut sid_type,
376                &schema_guid_map,
377            )
378            .unwrap();
379
380        assert_eq!(domain.properties.dsheuristics, "0000000001000001");
381        assert_eq!(domain.to_json()["Properties"]["dsheuristics"], "0000000001000001");
382    }
383}