rusthound-ce 2.5.11

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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use serde_json::value::Value;
use serde::{Deserialize, Serialize};
use ldap3::SearchEntry;
use log::{debug, trace};
use std::collections::HashMap;
use std::error::Error;

use crate::objects::common::{LdapObject, AceTemplate, SPNTarget, Link, Member};
use crate::enums::{decode_guid_le, get_pki_cert_name_flags, get_pki_enrollment_flags, parse_ntsecuritydescriptor};
use crate::json::checker::common::get_name_from_full_distinguishedname;
use crate::utils::date::{filetime_to_span, span_to_string, string_to_epoch};

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

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

    // Immutable access.
    pub fn properties(&self) -> &CertTemplateProperties {
        &self.properties
    }
    pub fn object_identifier(&self) -> &String {
        &self.object_identifier
    }

    /// Function to parse and replace value in json template for Certificate Template object.
    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 for current object
        debug!("Parse CertTemplate: {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();
        let _ca_name = get_name_from_full_distinguishedname(&self.properties.distinguishedname);

        // With a check
        for (key, value) in &result_attrs {
            match key.as_str() {
                "name" => {
                    let name = format!("{}@{}",&value[0],domain);
                    self.properties.name = name.to_uppercase();
                }
                "description" => {
                    self.properties.description = Some(value[0].to_owned());
                }
                "displayName" => {
                    self.properties.displayname = value[0].to_owned();
                }
                "msPKI-Certificate-Name-Flag" => {
                    if !value.is_empty() {
                        self.properties.certificatenameflag = get_pki_cert_name_flags(value[0].parse::<i64>().unwrap_or(0) as u64);
                        self.properties.enrolleesuppliessubject = self.properties.certificatenameflag.contains("ENROLLEE_SUPPLIES_SUBJECT");
                        self.properties.subjectaltrequireupn = self.properties.certificatenameflag.contains("SUBJECT_ALT_REQUIRE_UPN");
                        self.properties.subjectaltrequiredns = self.properties.certificatenameflag.contains("SUBJECT_ALT_REQUIRE_DNS");
                        self.properties.subjectaltrequiredomaindns = self.properties.certificatenameflag.contains("SUBJECT_ALT_REQUIRE_DOMAIN_DNS");
                        self.properties.subjectaltrequireemail = self.properties.certificatenameflag.contains("SUBJECT_ALT_REQUIRE_EMAIL");
                        self.properties.subjectaltrequirespn = self.properties.certificatenameflag.contains("SUBJECT_ALT_REQUIRE_SPN");
                        self.properties.subjectrequireemail = self.properties.certificatenameflag.contains("SUBJECT_REQUIRE_EMAIL");
                    }
                }
                "msPKI-Enrollment-Flag" => {
                    if !value.is_empty() {
                        self.properties.enrollmentflag = get_pki_enrollment_flags(value[0].parse::<i64>().unwrap_or(0) as u64);
                        self.properties.requiresmanagerapproval = self.properties.enrollmentflag.contains("PEND_ALL_REQUESTS");
                        self.properties.nosecurityextension = self.properties.enrollmentflag.contains("NO_SECURITY_EXTENSION");
                    }
                }
                "msPKI-Private-Key-Flag" => {
                    // if !value.is_empty() {
                    //     self.properties.() = get_pki_private_flags(value[0].parse::<i64>().unwrap_or(0) as u64);
                    // }
                }
                "msPKI-RA-Signature" => {
                    if !value.is_empty() {
                        self.properties.authorizedsignatures = value.first().unwrap_or(&"0".to_string()).parse::<i64>().unwrap_or(0);
                    }
                }
                "msPKI-RA-Application-Policies" => {
                    if !value.is_empty() {
                        self.properties.applicationpolicies = value.to_owned();
                    }
                }
                "msPKI-Certificate-Application-Policy" => {
                    if !value.is_empty() {
                        self.properties.certificateapplicationpolicy = value.to_owned();
                    }
                }
                "msPKI-RA-Policies" => {
                    if !value.is_empty() {
                        self.properties.issuancepolicies = value.to_owned();
                    }
                }
                "msPKI-Cert-Template-OID" => {
                    if !value.is_empty() {
                        self.properties.oid = value[0].to_owned();
                    }
                }
                "pKIExtendedKeyUsage" => {
                    if !value.is_empty() {
                        self.properties.ekus = value.to_owned();
                    }
                }
                "msPKI-Template-Schema-Version" => {
                    self.properties.schemaversion = value[0].parse::<i64>().unwrap_or(0);
                }
                "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.object_identifier = guid.to_owned();
                }
                "nTSecurityDescriptor" => {
                    // nTSecurityDescriptor raw to string
                    let relations_ace =  parse_ntsecuritydescriptor(
                        self,
                        &value[0],
                        "CertTemplate",
                        &result_attrs,
                        &result_bin,
                        domain,
                        schema_guid_map,
                    );
                    self.aces = relations_ace;
                }
                "pKIExpirationPeriod" => {
                    self.properties.validityperiod = span_to_string(filetime_to_span(value[0].to_owned())?);
                }
                "pKIOverlapPeriod" => {
                    self.properties.renewalperiod = span_to_string(filetime_to_span(value[0].to_owned())?);
                }
                _ => {}
            }
        }

        // Get all effective ekus.
        self.properties.effectiveekus = Self::get_effectiveekus(
            &self.properties.schemaversion,
            &self.properties.ekus,
            &self.properties.certificateapplicationpolicy,
        );

        // Check if authentication is enabled or not for this template.
        self.properties.authenticationenabled = Self::authentication_is_enabled(self);

        // Push DN and SID in HashMap
        if self.object_identifier != "SID" {
            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(),
                "CertTemplate".to_string()
            );
        }

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

    /// Function to get effective ekus for one template.
    fn get_effectiveekus(
        schema_version: &i64,
        ekus: &[String],
        certificateapplicationpolicy: &[String],
    ) -> Vec<String> {
        if schema_version == &1 && !ekus.is_empty() {
            ekus.to_vec()
        } else {
            certificateapplicationpolicy.to_vec()
        }
    }

    /// Function to check if authentication is enabled or not.
    fn authentication_is_enabled(&mut self) -> bool {
        let authentication_oids = [
            "1.3.6.1.5.5.7.3.2", // ClientAuthentication,
            "1.3.6.1.5.2.3.4", // PKINITClientAuthentication
            "1.3.6.1.4.1.311.20.2.2", // SmartcardLogon
            "2.5.29.37.0", // AnyPurpose
        ];
        self.properties.effectiveekus.iter()
            .any(|eku| authentication_oids.contains(&eku.as_str()))
            || self.properties.effectiveekus.is_empty()
    }
}

impl LdapObject for CertTemplate {
    // 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.
    }
}


// CertTemplate properties structure
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CertTemplateProperties {
   domain: String,
   name: String,
   distinguishedname: String,
   domainsid: String,
   isaclprotected: bool,
   description: Option<String>,
   whencreated: i64,
   validityperiod: String,
   renewalperiod: String,
   schemaversion: i64,
   displayname: String,
   oid: String,
   enrollmentflag: String,
   requiresmanagerapproval: bool,
   nosecurityextension: bool,
   certificatenameflag: String,
   enrolleesuppliessubject: bool,
   subjectaltrequireupn: bool,
   subjectaltrequiredns: bool,
   subjectaltrequiredomaindns: bool,
   subjectaltrequireemail: bool,
   subjectaltrequirespn: bool,
   subjectrequireemail: bool,
   ekus: Vec<String>,
   certificateapplicationpolicy: Vec<String>,
   authorizedsignatures: i64,
   applicationpolicies: Vec<String>,
   issuancepolicies: Vec<String>,
   effectiveekus: Vec<String>,
   authenticationenabled: bool,
}

impl Default for CertTemplateProperties {
    fn default() -> CertTemplateProperties {
        CertTemplateProperties {
            domain: String::from(""),
            name: String::from(""),
            distinguishedname: String::from(""),
            domainsid: String::from(""),
            isaclprotected: false,
            description: None,
            whencreated: -1,
            validityperiod: String::from(""),
            renewalperiod: String::from(""),
            schemaversion: 1,
            displayname: String::from(""),
            oid: String::from(""),
            enrollmentflag: String::from(""),
            requiresmanagerapproval: false,
            nosecurityextension: false,
            certificatenameflag: String::from(""),
            enrolleesuppliessubject: false,
            subjectaltrequireupn: false,
            subjectaltrequiredns: false,
            subjectaltrequiredomaindns: false,
            subjectaltrequireemail: false,
            subjectaltrequirespn: false,
            subjectrequireemail: false,
            ekus: Vec::new(),
            certificateapplicationpolicy: Vec::new(),
            authorizedsignatures: 0,
            applicationpolicies: Vec::new(),
            issuancepolicies: Vec::new(),
            effectiveekus: Vec::new(),
            authenticationenabled: false,
       }
    }
 }

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

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

    const SUBJECT_NAME_FLAG_PROPERTIES: [&str; 6] = [
        "subjectaltrequiredomaindns",
        "subjectaltrequirespn",
        "subjectaltrequireupn",
        "subjectaltrequireemail",
        "subjectaltrequiredns",
        "subjectrequireemail",
    ];

    fn parse_certtemplate_with_name_flag(flag: Option<i64>) -> CertTemplate {
        let mut attrs = HashMap::new();
        attrs.insert("name".to_string(), vec!["RustHoundLab".to_string()]);
        if let Some(flag) = flag {
            attrs.insert(
                "msPKI-Certificate-Name-Flag".to_string(),
                vec![flag.to_string()],
            );
        }

        let result = SearchEntry {
            dn: "CN=RustHoundLab,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=example,DC=local".to_string(),
            attrs,
            bin_attrs: HashMap::new(),
        };
        let mut certtemplate = CertTemplate::new();
        let mut dn_sid = HashMap::new();
        let mut sid_type = HashMap::new();

        certtemplate
            .parse(
                result,
                "example.local",
                &mut dn_sid,
                &mut sid_type,
                "S-1-5-21-1-2-3",
                &HashMap::new(),
            )
            .unwrap();

        certtemplate
    }

    #[test]
    fn parse_maps_each_subject_name_flag_to_its_boolean_property() {
        let cases = [
            (0x0040_0000, "subjectaltrequiredomaindns"),
            (0x0080_0000, "subjectaltrequirespn"),
            (0x0200_0000, "subjectaltrequireupn"),
            (0x0400_0000, "subjectaltrequireemail"),
            (0x0800_0000, "subjectaltrequiredns"),
            (0x2000_0000, "subjectrequireemail"),
        ];

        for (flag, expected_property) in cases {
            let certtemplate = parse_certtemplate_with_name_flag(Some(flag));
            let properties = &certtemplate.to_json()["Properties"];

            for property in SUBJECT_NAME_FLAG_PROPERTIES {
                assert_eq!(
                    properties[property],
                    property == expected_property,
                    "unexpected value for {property} with flag {flag:#010x}",
                );
            }
        }
    }

    #[test]
    fn subject_name_flag_properties_default_to_false_when_attribute_is_absent() {
        let certtemplate = parse_certtemplate_with_name_flag(None);
        let properties = &certtemplate.to_json()["Properties"];

        for property in SUBJECT_NAME_FLAG_PROPERTIES {
            assert_eq!(properties[property], false, "{property} should default to false");
        }
    }
}