rusthound-ce 2.5.24

Active Directory data collector for Bloodhound Community Edition written in rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use serde::{Deserialize, Serialize};
use serde_json::value::Value;
use ldap3::SearchEntry;
use log::{debug, trace};
use std::collections::HashMap;
use std::error::Error;

use crate::enums::{decode_guid_le, group_scope};
use crate::enums::regex::OBJECT_SID_RE1;
use crate::objects::common::{LdapObject, AceTemplate, SPNTarget, Link, Member};
use crate::enums::acl::parse_ntsecuritydescriptor;
use crate::enums::secdesc::LdapSid;
use crate::enums::sid::{objectsid_to_vec8, sid_maker};
use crate::utils::date::string_to_epoch;

/// Group structure
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct Group {
    #[serde(rename = "ObjectIdentifier")]
    object_identifier: String,
    #[serde(rename = "IsDeleted")]
    is_deleted: bool,
    #[serde(rename = "IsACLProtected")]
    is_acl_protected: bool,
    #[serde(rename = "Properties")]
    properties: GroupProperties,
    #[serde(rename = "Members")]
    members: Vec<Member>,
    #[serde(rename = "HasSIDHistory")]
    has_sid_history: Vec<Member>,
    #[serde(rename = "Aces")]
    aces: Vec<AceTemplate>,
    #[serde(rename = "ContainedBy")]
    contained_by: Option<Member>,
}

impl Group {
    // New group.
    pub fn new() -> Self { 
        Self { ..Default::default() } 
    }

    // Immutable access.
    pub fn members(&self) -> &Vec<Member> {
        &self.members
    }
    pub fn properties(&self) -> &GroupProperties {
        &self.properties 
    }
    pub fn object_identifier(&self) -> &String {
        &self.object_identifier
    }

    // Mutable access.
    pub fn properties_mut(&mut self) -> &mut GroupProperties {
        &mut self.properties
    }
    pub fn object_identifier_mut(&mut self) -> &mut String {
        &mut self.object_identifier
    }
    pub fn members_mut(&mut self) -> &mut Vec<Member> {
        &mut self.members
    }
    pub fn has_sid_history_mut(&mut self) -> &mut Vec<Member> {
        &mut self.has_sid_history
    }
    
    /// Function to parse and replace value for group object.
    /// <https://bloodhound.readthedocs.io/en/latest/further-reading/json.html#groups>
    pub fn parse(
        &mut self,
        result: SearchEntry,
        domain: &str,
        dn_sid: &mut HashMap<String, String>,
        sid_type: &mut HashMap<String, String>,
        domain_sid: &str,
        schema_guid_map: &HashMap<String, String>,
    ) -> Result<(), Box<dyn Error>> {
        let result_dn: String = result.dn.to_uppercase();
        let result_attrs: HashMap<String, Vec<String>> = result.attrs;
        let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;

        debug!("Parse group: {result_dn}");

        // Trace all result attributes
        for (key, value) in &result_attrs {
            trace!("  {key:?}:{value:?}");
        }
        // Trace all bin result attributes
        for (key, value) in &result_bin {
            trace!("  {key:?}:{value:?}");
        }

        // Change all values...
        self.properties.domain = domain.to_uppercase();
        self.properties.distinguishedname = result_dn;
        self.properties.domainsid = domain_sid.to_string();

        // With a check
        for (key, value) in &result_attrs {
            match key.as_str() {
                "name" => {
                    let name = &value[0];
                    let email = format!("{}@{}", name.to_owned(), domain);
                    self.properties.name = email.to_uppercase();
                }
                "description" => {
                    self.properties.description = Some(value[0].to_owned());
                }
                "adminCount" => {
                    // adminCount is not limited to 1: any non-zero value means
                    // the object is (or was) in a protected group, so
                    // AdminSDHolder owns its DACL.
                    let admincount = value[0].parse::<i32>().unwrap_or(0) != 0;
                    self.properties.admincount = admincount;
                    self.properties.adminsdholderprotected = admincount;
                }
                "groupType" => {
                    self.properties.groupscope = group_scope(value[0].parse::<i64>().unwrap_or(0));
                }
                "sAMAccountName" => {
                    self.properties.samaccountname = value[0].to_owned();
                }
                "member" => {
                    if !value.is_empty() {
                        let mut _vec_members: Vec<Member> = Vec::new();

                        for member in value {
                            let _member = member.trim();
                            if _member.is_empty() {
                                continue;
                            }
                            if _member.eq_ignore_ascii_case("SID") {
                                continue;
                            }

                            let mut m = Member::new();
                            *m.object_identifier_mut() = _member.to_uppercase();
                            _vec_members.push(m);
                        }
                        
                        self.members = _vec_members;
                    }
                }
                "objectSid" => {
                    // objectSid to vec and raw to string
                    let vec_sid = objectsid_to_vec8(&value[0]);
                    let sid = sid_maker(LdapSid::parse(&vec_sid).unwrap().1, domain);
                    self.object_identifier = sid.to_owned();

                    /*let re = Regex::new(r"^S-[0-9]{1}-[0-9]{1}-[0-9]{1,}-[0-9]{1,}-[0-9]{1,}-[0-9]{1,}").unwrap();
                    for domain_sid in re.captures_iter(&sid) 
                    {
                        group_json["Properties"]["domainsid"] = domain_sid[0].to_owned().to_string();
                    }*/

                    // highvalue
                    if sid.ends_with("-512") 
                        || sid.ends_with("-516") 
                        || sid.ends_with("-519") 
                        || sid.ends_with("-520") 
                    {
                        self.properties.highvalue = true;
                    } else if sid.ends_with("S-1-5-32-544") 
                        || sid.ends_with("S-1-5-32-548") 
                        || sid.ends_with("S-1-5-32-549")
                        || sid.ends_with("S-1-5-32-550") 
                        || sid.ends_with("S-1-5-32-551")
                    {
                        self.properties.highvalue = true;
                    } else {
                        self.properties.highvalue = false;
                    }
                }
                "whenCreated" => {
                    let epoch = string_to_epoch(&value[0])?;
                    if epoch.is_positive() {
                        self.properties.whencreated = epoch;
                    }
                }
                "isDeleted" => {
                    self.is_deleted = true;
                }
                _ => {}
            }
        }

        // For all, bins attributs
        for (key, value) in &result_bin {
            match key.as_str() {
                "objectGUID" => {
                    // objectGUID raw to string
                    let guid = decode_guid_le(&value[0]);
                    self.properties.objectguid = guid;
                }
                "objectSid" => {
                    // objectSid raw to string
                    let sid = sid_maker(LdapSid::parse(&value[0]).unwrap().1, domain);
                    self.object_identifier = sid.to_owned();

                    for domain_sid in OBJECT_SID_RE1.captures_iter(&sid) {
                        self.properties.domainsid = domain_sid[0].to_owned().to_string();
                    }
    
                    // highvalue
                    if sid.ends_with("-512") 
                        || sid.ends_with("-516") 
                        || sid.ends_with("-519") 
                        || sid.ends_with("-520") 
                    {
                        self.properties.highvalue = true;
                    }
                    else if sid.ends_with("S-1-5-32-544") 
                        || sid.ends_with("S-1-5-32-548") 
                        || sid.ends_with("S-1-5-32-549")
                        || sid.ends_with("S-1-5-32-550") 
                        || sid.ends_with("S-1-5-32-551") 
                    {
                        self.properties.highvalue = true;
                    }
                    else {
                        self.properties.highvalue = false;
                    }
                }
                "nTSecurityDescriptor" => {
                    // nTSecurityDescriptor raw to string
                    let relations_ace = parse_ntsecuritydescriptor(
                        self,
                        &value[0],
                        "Group",
                        &result_attrs,
                        &result_bin,
                        domain,
                        schema_guid_map,
                    );
                    self.aces = relations_ace;
                }
                "sIDHistory" => {
                    let mut list_sid_history: Vec<String> = Vec::new();
                    let mut has_sid_history: Vec<Member> = Vec::new();
                    for bsid in value {
                        debug!("sIDHistory: {:?}", &bsid);
                        let sid = sid_maker(LdapSid::parse(bsid).unwrap().1, domain);
                        let mut member = Member::new();
                        *member.object_identifier_mut() = sid.clone();
                        has_sid_history.push(member);
                        list_sid_history.push(sid);
                    }
                    self.properties.sidhistory = list_sid_history;
                    self.has_sid_history = has_sid_history;
                }
                _ => {}
            }
        }

        // Push DN and SID in HashMap
        dn_sid.insert(
            self.properties.distinguishedname.to_string(),
            self.object_identifier.to_string(),
        );
        // Push DN and Type
        sid_type.insert(
            self.object_identifier.to_string(),
            "Group".to_string(),
        );

        // Trace and return Group struct
        // trace!("JSON OUTPUT: {:?}",serde_json::to_string(&self).unwrap());
        Ok(())
    }
}

impl LdapObject for Group {
    // To JSON
    fn to_json(&self) -> Value {
        serde_json::to_value(self).unwrap()
    }

    // Get values
    fn get_object_identifier(&self) -> &String {
        &self.object_identifier
    }
    fn get_is_acl_protected(&self) -> &bool {
        &self.is_acl_protected
    }
    fn get_aces(&self) -> &Vec<AceTemplate> {
        &self.aces
    }
    fn get_spntargets(&self) -> &Vec<SPNTarget> {
        panic!("Not used by current object.");
    }
    fn get_allowed_to_delegate(&self) -> &Vec<Member> {
        panic!("Not used by current object.");
    }
    fn get_links(&self) -> &Vec<Link> {
        panic!("Not used by current object.");
    }
    fn get_contained_by(&self) -> &Option<Member> {
        &self.contained_by
    }
    fn get_child_objects(&self) -> &Vec<Member> {
        panic!("Not used by current object.");
    }
    fn get_haslaps(&self) -> &bool {
        &false
    }
    
    // Get mutable values
    fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
        &mut self.aces
    }
    fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
        panic!("Not used by current object.");
    }
    fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
        panic!("Not used by current object.");
    }
    
    // Edit values
    fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
        self.is_acl_protected = is_acl_protected;
        self.properties.isaclprotected = is_acl_protected;
    }
    fn set_aces(&mut self, aces: Vec<AceTemplate>) {
        self.aces = aces;
    }
    fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
        // Not used by current object.
    }
    fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
        // Not used by current object.
    }
    fn set_links(&mut self, _links: Vec<Link>) {
        // Not used by current object.
    }
    fn set_contained_by(&mut self, contained_by: Option<Member>) {
        self.contained_by = contained_by;
    }
    fn set_child_objects(&mut self, _child_objects: Vec<Member>) {
        // Not used by current object.
    }
    fn set_owner_rights_flags(&mut self, any: bool, any_inherited: bool) {
        self.properties.doesanyacegrantownerrights = any;
        self.properties.doesanyinheritedacegrantownerrights = any_inherited;
    }
}

// Group properties structure
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct GroupProperties {
    domain: String,
    name: String,
    distinguishedname: String,
    domainsid: String,
    objectguid: String,
    doesanyacegrantownerrights: bool,
    doesanyinheritedacegrantownerrights: bool,
    isaclprotected: bool,
    highvalue: bool,
    samaccountname: String,
    description: Option<String>,
    whencreated: i64,
    admincount: bool,
    adminsdholderprotected: bool,
    groupscope: String,
    sidhistory: Vec<String>,
}

impl GroupProperties {
    // Get access.
    pub fn name(&self) -> &String {
        &self.name
    }

    // Mutable access.
    pub fn name_mut(&mut self) -> &mut String {
        &mut self.name
    }
    pub fn domain_mut(&mut self) -> &mut String {
        &mut self.domain
    }
    pub fn domainsid_mut(&mut self) -> &mut String {
        &mut self.domainsid
    }
    pub fn highvalue_mut(&mut self) -> &mut bool {
        &mut self.highvalue
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn group_type_maps_to_bloodhound_scope() {
        // groupType is a signed 32-bit value; security groups carry 0x80000000.
        assert_eq!(group_scope(-2147483646), "Global");      // security, global
        assert_eq!(group_scope(-2147483643), "DomainLocal"); // security, builtin local
        assert_eq!(group_scope(-2147483644), "DomainLocal"); // security, resource
        assert_eq!(group_scope(-2147483640), "Universal");   // security, universal
        assert_eq!(group_scope(2), "Global");                // distribution, global
        assert_eq!(group_scope(8), "Universal");             // distribution, universal
        assert_eq!(group_scope(0), "");
    }
}