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::decode_guid_le;
10use crate::enums::regex::OBJECT_SID_RE1;
11use crate::objects::common::{LdapObject, GPOChange, Link, AceTemplate, SPNTarget, Member};
12use crate::objects::trust::Trust;
13use crate::utils::date::{span_to_string, string_to_epoch};
14use crate::enums::acl::parse_ntsecuritydescriptor;
15use crate::enums::forestlevel::get_forest_level;
16use crate::enums::gplink::parse_gplink;
17use crate::enums::secdesc::LdapSid;
18use crate::enums::sid::sid_maker;
19
20#[derive(Debug, Clone, Deserialize, Serialize, Default)]
22pub struct Domain {
23 #[serde(rename = "Properties")]
24 properties: DomainProperties,
25 #[serde(rename = "GPOChanges")]
26 gpo_changes: GPOChange,
27 #[serde(rename = "ChildObjects")]
28 child_objects: Vec<Member>,
29 #[serde(rename = "Trusts")]
30 trusts: Vec<Trust>,
31 #[serde(rename = "Links")]
32 links: Vec<Link>,
33 #[serde(rename = "InheritanceHashes")]
34 inheritance_hashes: Vec<String>,
35 #[serde(rename = "ForestRootIdentifier")]
36 forest_root_identifier: Option<String>,
37 #[serde(rename = "Aces")]
38 aces: Vec<AceTemplate>,
39 #[serde(rename = "ObjectIdentifier")]
40 object_identifier: String,
41 #[serde(rename = "IsDeleted")]
42 is_deleted: bool,
43 #[serde(rename = "IsACLProtected")]
44 is_acl_protected: bool,
45 #[serde(rename = "ContainedBy")]
46 contained_by: Option<Member>,
47}
48
49impl Domain {
50 pub fn new() -> Self {
52 Self { ..Default::default() }
53 }
54
55 pub fn object_identifier(&self) -> &String {
57 &self.object_identifier
58 }
59 pub fn properties(&self) -> &DomainProperties {
60 &self.properties
61 }
62 pub fn inheritance_hashes(&self) -> &Vec<String> {
63 &self.inheritance_hashes
64 }
65 pub fn forest_root_identifier(&self) -> &Option<String> {
66 &self.forest_root_identifier
67 }
68
69 pub fn properties_mut(&mut self) -> &mut DomainProperties {
71 &mut self.properties
72 }
73 pub fn object_identifier_mut(&mut self) -> &mut String {
74 &mut self.object_identifier
75 }
76 pub fn gpo_changes_mut(&mut self) -> &mut GPOChange {
77 &mut self.gpo_changes
78 }
79 pub fn trusts_mut(&mut self) -> &mut Vec<Trust> {
80 &mut self.trusts
81 }
82 pub fn inheritance_hashes_mut(&mut self) -> &mut Vec<String> {
83 &mut self.inheritance_hashes
84 }
85
86 pub fn parse(
89 &mut self,
90 result: SearchEntry,
91 domain_name: &str,
92 dn_sid: &mut HashMap<String, String>,
93 sid_type: &mut HashMap<String, String>,
94 schema_guid_map: &HashMap<String, String>,
95 ) -> Result<String, Box<dyn Error>> {
96 let result_dn: String = result.dn.to_uppercase();
97 let result_attrs: HashMap<String, Vec<String>> = result.attrs;
98 let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;
99
100 debug!("Parse domain: {result_dn}");
102
103 for (key, value) in &result_attrs {
105 trace!(" {key:?}:{value:?}");
106 }
107 for (key, value) in &result_bin {
109 trace!(" {key:?}:{value:?}");
110 }
111
112 self.properties.domain = domain_name.to_uppercase();
114 self.properties.distinguishedname = result_dn;
115
116 #[allow(unused_assignments)]
118 let mut sid: String = "".to_owned();
119 let mut global_domain_sid: String = "DOMAIN_SID".to_owned();
120 for (key, value) in &result_attrs {
122 match key.as_str() {
123 "distinguishedName" => {
124 self.properties.distinguishedname = value[0].to_owned().to_uppercase();
126 let name = value[0]
127 .split(",")
128 .filter(|x| x.starts_with("DC="))
129 .map(|x| x.strip_prefix("DC=").unwrap_or(""))
130 .collect::<Vec<&str>>()
131 .join(".");
132 self.properties.name = name.to_uppercase();
133 self.properties.domain = name.to_uppercase();
134 }
135 "msDS-Behavior-Version" => {
136 let level = get_forest_level(value[0].to_string());
137 self.properties.functionallevel = level;
138 }
139 "whenCreated" => {
140 let epoch = string_to_epoch(&value[0])?;
141 if epoch.is_positive() {
142 self.properties.whencreated = epoch;
143 }
144 }
145 "gPLink" => {
146 self.links = parse_gplink(value[0].to_string())?;
147 }
148 "isCriticalSystemObject" => {
149 self.properties.highvalue = value[0].contains("TRUE");
150 }
151 "ms-DS-MachineAccountQuota" => {
153 let machine_account_quota = value[0].parse::<i32>().unwrap_or(0);
154 self.properties.machineaccountquota = machine_account_quota;
155 if machine_account_quota > 0 {
156 info!("MachineAccountQuota: {}", machine_account_quota.to_string().yellow().bold());
157 }
158 }
159 "isDeleted" => {
160 self.is_deleted = true;
161 }
162 "msDS-ExpirePasswordsOnSmartCardOnlyAccounts" => {
163 self.properties.expirepasswordsonsmartcardonlyaccounts = true;
164 }
165 "dSHeuristics" => {
166 self.properties.dsheuristics = value[0].to_owned();
168 }
169 "minPwdLength" => {
170 self.properties.minpwdlength = value[0].parse::<i32>().unwrap_or(0);
171 }
172 "pwdProperties" => {
173 self.properties.pwdproperties = value[0].parse::<i32>().unwrap_or(0);
174 }
175 "pwdHistoryLength" => {
176 self.properties.pwdhistorylength = value[0].parse::<i32>().unwrap_or(0);
177 }
178 "lockoutThreshold" => {
179 self.properties.lockoutthreshold = value[0].parse::<i32>().unwrap_or(0);
180 }
181 "minPwdAge" => {
182 self.properties.minpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
183 }
184 "maxPwdAge" => {
185 self.properties.maxpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
186 }
187 "lockoutDuration" => {
188 self.properties.lockoutduration = span_to_string(value[0].parse::<i64>().unwrap_or(0));
189 }
190 "lockOutObservationWindow" => {
191 self.properties.lockoutobservationwindow = value[0].parse::<i64>().unwrap_or(0);
192 }
193 _ => {}
194 }
195 }
196
197 for (key, value) in &result_bin {
199 match key.as_str() {
200 "objectGUID" => {
201 let guid = decode_guid_le(&value[0]);
203 self.properties.objectguid = guid;
204 }
205 "objectSid" => {
206 sid = sid_maker(LdapSid::parse(&value[0]).unwrap().1, domain_name);
208 self.object_identifier = sid.to_owned();
209
210 for domain_sid in OBJECT_SID_RE1.captures_iter(&sid) {
211 self.properties.domainsid = domain_sid[0].to_owned().to_string();
212 global_domain_sid = domain_sid[0].to_owned().to_string();
213 }
214
215 self.properties.collected = true;
217 }
218 "nTSecurityDescriptor" => {
219 let relations_ace = parse_ntsecuritydescriptor(
221 self,
222 &value[0],
223 "Domain",
224 &result_attrs,
225 &result_bin,
226 domain_name,
227 schema_guid_map,
228 );
229 self.aces = relations_ace;
230 }
231 _ => {}
232 }
233 }
234
235 dn_sid.insert(
237 self.properties.distinguishedname.to_string(),
238 self.object_identifier.to_string()
239 );
240 sid_type.insert(
242 self.object_identifier.to_string(),
243 "Domain".to_string(),
244 );
245
246 Ok(global_domain_sid)
249 }
250}
251
252impl LdapObject for Domain {
253 fn to_json(&self) -> Value {
255 serde_json::to_value(self).unwrap()
256 }
257
258 fn get_object_identifier(&self) -> &String {
260 &self.object_identifier
261 }
262 fn get_is_acl_protected(&self) -> &bool {
263 &self.is_acl_protected
264 }
265 fn get_aces(&self) -> &Vec<AceTemplate> {
266 &self.aces
267 }
268 fn get_spntargets(&self) -> &Vec<SPNTarget> {
269 panic!("Not used by current object.");
270 }
271 fn get_allowed_to_delegate(&self) -> &Vec<Member> {
272 panic!("Not used by current object.");
273 }
274 fn get_links(&self) -> &Vec<Link> {
275 &self.links
276 }
277 fn get_contained_by(&self) -> &Option<Member> {
278 &self.contained_by
279 }
280 fn get_child_objects(&self) -> &Vec<Member> {
281 &self.child_objects
282 }
283 fn get_haslaps(&self) -> &bool {
284 &false
285 }
286
287 fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
289 &mut self.aces
290 }
291 fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
292 panic!("Not used by current object.");
293 }
294 fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
295 panic!("Not used by current object.");
296 }
297
298 fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
300 self.is_acl_protected = is_acl_protected;
301 self.properties.isaclprotected = is_acl_protected;
302 }
303 fn set_aces(&mut self, aces: Vec<AceTemplate>) {
304 self.aces = aces;
305 }
306 fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
307 }
309 fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
310 }
312 fn set_links(&mut self, links: Vec<Link>) {
313 self.links = links;
314 }
315 fn set_contained_by(&mut self, contained_by: Option<Member>) {
316 self.contained_by = contained_by;
317 }
318 fn set_child_objects(&mut self, child_objects: Vec<Member>) {
319 self.child_objects = child_objects
320 }
321 fn set_owner_rights_flags(&mut self, any: bool, any_inherited: bool) {
322 self.properties.doesanyacegrantownerrights = any;
323 self.properties.doesanyinheritedacegrantownerrights = any_inherited;
324 }
325}
326
327#[derive(Debug, Clone, Deserialize, Serialize, Default)]
329pub struct DomainProperties {
330 domain: String,
331 name: String,
332 distinguishedname: String,
333 domainsid: String,
334 objectguid: String,
335 netbios: String,
336 isaclprotected: bool,
337 doesanyacegrantownerrights: bool,
338 doesanyinheritedacegrantownerrights: bool,
339 highvalue: bool,
340 description: Option<String>,
341 whencreated: i64,
342 machineaccountquota: i32,
343 expirepasswordsonsmartcardonlyaccounts: bool,
344 minpwdlength: i32,
345 pwdproperties: i32,
346 pwdhistorylength: i32,
347 lockoutthreshold: i32,
348 minpwdage: String,
349 maxpwdage: String,
350 lockoutduration: String,
351 lockoutobservationwindow: i64,
352 functionallevel: String,
353 dsheuristics: String,
354 collected: bool
355}
356
357impl DomainProperties {
358 pub fn distinguishedname(&self) -> &String {
360 &self.distinguishedname
361 }
362 pub fn objectguid(&self) -> &String {
363 &self.objectguid
364 }
365 pub fn netbios(&self) -> &String {
366 &self.netbios
367 }
368
369 pub fn domain_mut(&mut self) -> &mut String {
371 &mut self.domain
372 }
373 pub fn name_mut(&mut self) -> &mut String {
374 &mut self.name
375 }
376 pub fn highvalue_mut(&mut self) -> &mut bool {
377 &mut self.highvalue
378 }
379 pub fn distinguishedname_mut(&mut self) -> &mut String {
380 &mut self.distinguishedname
381 }
382 pub fn netbios_mut(&mut self) -> &mut String {
383 &mut self.netbios
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
392 fn parse_preserves_dsheuristics_value() {
393 let mut domain = Domain::new();
394 let result = SearchEntry {
395 dn: "DC=example,DC=local".to_string(),
396 attrs: HashMap::from([(
397 "dSHeuristics".to_string(),
398 vec!["0000000001000001".to_string()],
399 )]),
400 bin_attrs: HashMap::new(),
401 };
402 let mut dn_sid = HashMap::new();
403 let mut sid_type = HashMap::new();
404 let schema_guid_map = HashMap::new();
405
406 domain
407 .parse(
408 result,
409 "example.local",
410 &mut dn_sid,
411 &mut sid_type,
412 &schema_guid_map,
413 )
414 .unwrap();
415
416 assert_eq!(domain.properties.dsheuristics, "0000000001000001");
417 assert_eq!(domain.to_json()["Properties"]["dsheuristics"], "0000000001000001");
418 }
419
420 #[test]
421 fn parse_fills_object_guid_from_bin_attrs() {
422 let mut domain = Domain::new();
423 let raw = vec![
424 0x58, 0xEC, 0x7B, 0xF7, 0xA7, 0x73, 0x8D, 0x40,
425 0xAF, 0x0D, 0x42, 0xF0, 0xD7, 0x2C, 0x71, 0x14,
426 ];
427 let result = SearchEntry {
428 dn: "DC=example,DC=local".to_string(),
429 attrs: HashMap::new(),
430 bin_attrs: HashMap::from([("objectGUID".to_string(), vec![raw])]),
431 };
432 let mut dn_sid = HashMap::new();
433 let mut sid_type = HashMap::new();
434 let schema_guid_map = HashMap::new();
435
436 domain
437 .parse(result, "example.local", &mut dn_sid, &mut sid_type, &schema_guid_map)
438 .unwrap();
439
440 assert_eq!(domain.properties.objectguid, "F77BEC58-73A7-408D-AF0D-42F0D72C7114");
441 assert_eq!(
442 domain.to_json()["Properties"]["objectguid"],
443 "F77BEC58-73A7-408D-AF0D-42F0D72C7114"
444 );
445 }
446}