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#[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 pub fn new() -> Self {
47 Self { ..Default::default() }
48 }
49
50 pub fn object_identifier(&self) -> &String {
52 &self.object_identifier
53 }
54
55 pub fn properties_mut(&mut self) -> &mut DomainProperties {
57 &mut self.properties
58 }
59 pub fn object_identifier_mut(&mut self) -> &mut String {
60 &mut self.object_identifier
61 }
62 pub fn gpo_changes_mut(&mut self) -> &mut GPOChange {
63 &mut self.gpo_changes
64 }
65 pub fn trusts_mut(&mut self) -> &mut Vec<Trust> {
66 &mut self.trusts
67 }
68
69 pub fn parse(
72 &mut self,
73 result: SearchEntry,
74 domain_name: &str,
75 dn_sid: &mut HashMap<String, String>,
76 sid_type: &mut HashMap<String, String>,
77 schema_guid_map: &HashMap<String, String>,
78 ) -> Result<String, Box<dyn Error>> {
79 let result_dn: String = result.dn.to_uppercase();
80 let result_attrs: HashMap<String, Vec<String>> = result.attrs;
81 let result_bin: HashMap<String, Vec<Vec<u8>>> = result.bin_attrs;
82
83 debug!("Parse domain: {result_dn}");
85
86 for (key, value) in &result_attrs {
88 trace!(" {key:?}:{value:?}");
89 }
90 for (key, value) in &result_bin {
92 trace!(" {key:?}:{value:?}");
93 }
94
95 self.properties.domain = domain_name.to_uppercase();
97 self.properties.distinguishedname = result_dn;
98
99 #[allow(unused_assignments)]
101 let mut sid: String = "".to_owned();
102 let mut global_domain_sid: String = "DOMAIN_SID".to_owned();
103 for (key, value) in &result_attrs {
105 match key.as_str() {
106 "distinguishedName" => {
107 self.properties.distinguishedname = value[0].to_owned().to_uppercase();
109 let name = value[0]
110 .split(",")
111 .filter(|x| x.starts_with("DC="))
112 .map(|x| x.strip_prefix("DC=").unwrap_or(""))
113 .collect::<Vec<&str>>()
114 .join(".");
115 self.properties.name = name.to_uppercase();
116 self.properties.domain = name.to_uppercase();
117 }
118 "msDS-Behavior-Version" => {
119 let level = get_forest_level(value[0].to_string());
120 self.properties.functionallevel = level;
121 }
122 "whenCreated" => {
123 let epoch = string_to_epoch(&value[0])?;
124 if epoch.is_positive() {
125 self.properties.whencreated = epoch;
126 }
127 }
128 "gPLink" => {
129 self.links = parse_gplink(value[0].to_string())?;
130 }
131 "isCriticalSystemObject" => {
132 self.properties.highvalue = value[0].contains("TRUE");
133 }
134 "ms-DS-MachineAccountQuota" => {
136 let machine_account_quota = value[0].parse::<i32>().unwrap_or(0);
137 self.properties.machineaccountquota = machine_account_quota;
138 if machine_account_quota > 0 {
139 info!("MachineAccountQuota: {}", machine_account_quota.to_string().yellow().bold());
140 }
141 }
142 "isDeleted" => {
143 self.is_deleted = true;
144 }
145 "msDS-ExpirePasswordsOnSmartCardOnlyAccounts" => {
146 self.properties.expirepasswordsonsmartcardonlyaccounts = true;
147 }
148 "dSHeuristics" => {
149 self.properties.dsheuristics = value[0].to_owned();
151 }
152 "minPwdLength" => {
153 self.properties.minpwdlength = value[0].parse::<i32>().unwrap_or(0);
154 }
155 "pwdProperties" => {
156 self.properties.pwdproperties = value[0].parse::<i32>().unwrap_or(0);
157 }
158 "pwdHistoryLength" => {
159 self.properties.pwdhistorylength = value[0].parse::<i32>().unwrap_or(0);
160 }
161 "lockoutThreshold" => {
162 self.properties.lockoutthreshold = value[0].parse::<i32>().unwrap_or(0);
163 }
164 "minPwdAge" => {
165 self.properties.minpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
166 }
167 "maxPwdAge" => {
168 self.properties.maxpwdage = span_to_string(value[0].parse::<i64>().unwrap_or(0));
169 }
170 "lockoutDuration" => {
171 self.properties.lockoutduration = span_to_string(value[0].parse::<i64>().unwrap_or(0));
172 }
173 "lockOutObservationWindow" => {
174 self.properties.lockoutobservationwindow = value[0].parse::<i64>().unwrap_or(0);
175 }
176 _ => {}
177 }
178 }
179
180 for (key, value) in &result_bin {
182 match key.as_str() {
183 "objectSid" => {
184 sid = sid_maker(LdapSid::parse(&value[0]).unwrap().1, domain_name);
186 self.object_identifier = sid.to_owned();
187
188 for domain_sid in OBJECT_SID_RE1.captures_iter(&sid) {
189 self.properties.domainsid = domain_sid[0].to_owned().to_string();
190 global_domain_sid = domain_sid[0].to_owned().to_string();
191 }
192
193 self.properties.collected = true;
195 }
196 "nTSecurityDescriptor" => {
197 let relations_ace = parse_ntsecuritydescriptor(
199 self,
200 &value[0],
201 "Domain",
202 &result_attrs,
203 &result_bin,
204 domain_name,
205 schema_guid_map,
206 );
207 self.aces = relations_ace;
208 }
209 _ => {}
210 }
211 }
212
213 dn_sid.insert(
215 self.properties.distinguishedname.to_string(),
216 self.object_identifier.to_string()
217 );
218 sid_type.insert(
220 self.object_identifier.to_string(),
221 "Domain".to_string(),
222 );
223
224 Ok(global_domain_sid)
227 }
228}
229
230impl LdapObject for Domain {
231 fn to_json(&self) -> Value {
233 serde_json::to_value(self).unwrap()
234 }
235
236 fn get_object_identifier(&self) -> &String {
238 &self.object_identifier
239 }
240 fn get_is_acl_protected(&self) -> &bool {
241 &self.is_acl_protected
242 }
243 fn get_aces(&self) -> &Vec<AceTemplate> {
244 &self.aces
245 }
246 fn get_spntargets(&self) -> &Vec<SPNTarget> {
247 panic!("Not used by current object.");
248 }
249 fn get_allowed_to_delegate(&self) -> &Vec<Member> {
250 panic!("Not used by current object.");
251 }
252 fn get_links(&self) -> &Vec<Link> {
253 &self.links
254 }
255 fn get_contained_by(&self) -> &Option<Member> {
256 &self.contained_by
257 }
258 fn get_child_objects(&self) -> &Vec<Member> {
259 &self.child_objects
260 }
261 fn get_haslaps(&self) -> &bool {
262 &false
263 }
264
265 fn get_aces_mut(&mut self) -> &mut Vec<AceTemplate> {
267 &mut self.aces
268 }
269 fn get_spntargets_mut(&mut self) -> &mut Vec<SPNTarget> {
270 panic!("Not used by current object.");
271 }
272 fn get_allowed_to_delegate_mut(&mut self) -> &mut Vec<Member> {
273 panic!("Not used by current object.");
274 }
275
276 fn set_is_acl_protected(&mut self, is_acl_protected: bool) {
278 self.is_acl_protected = is_acl_protected;
279 self.properties.isaclprotected = is_acl_protected;
280 }
281 fn set_aces(&mut self, aces: Vec<AceTemplate>) {
282 self.aces = aces;
283 }
284 fn set_spntargets(&mut self, _spn_targets: Vec<SPNTarget>) {
285 }
287 fn set_allowed_to_delegate(&mut self, _allowed_to_delegate: Vec<Member>) {
288 }
290 fn set_links(&mut self, links: Vec<Link>) {
291 self.links = links;
292 }
293 fn set_contained_by(&mut self, contained_by: Option<Member>) {
294 self.contained_by = contained_by;
295 }
296 fn set_child_objects(&mut self, child_objects: Vec<Member>) {
297 self.child_objects = child_objects
298 }
299}
300
301#[derive(Debug, Clone, Deserialize, Serialize, Default)]
303pub struct DomainProperties {
304 domain: String,
305 name: String,
306 distinguishedname: String,
307 domainsid: String,
308 isaclprotected: bool,
309 highvalue: bool,
310 description: Option<String>,
311 whencreated: i64,
312 machineaccountquota: i32,
313 expirepasswordsonsmartcardonlyaccounts: bool,
314 minpwdlength: i32,
315 pwdproperties: i32,
316 pwdhistorylength: i32,
317 lockoutthreshold: i32,
318 minpwdage: String,
319 maxpwdage: String,
320 lockoutduration: String,
321 lockoutobservationwindow: i64,
322 functionallevel: String,
323 dsheuristics: String,
324 collected: bool
325}
326
327impl DomainProperties {
328 pub fn domain_mut(&mut self) -> &mut String {
330 &mut self.domain
331 }
332 pub fn name_mut(&mut self) -> &mut String {
333 &mut self.name
334 }
335 pub fn highvalue_mut(&mut self) -> &mut bool {
336 &mut self.highvalue
337 }
338 pub fn distinguishedname_mut(&mut self) -> &mut String {
339 &mut self.distinguishedname
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn parse_preserves_dsheuristics_value() {
349 let mut domain = Domain::new();
350 let result = SearchEntry {
351 dn: "DC=example,DC=local".to_string(),
352 attrs: HashMap::from([(
353 "dSHeuristics".to_string(),
354 vec!["0000000001000001".to_string()],
355 )]),
356 bin_attrs: HashMap::new(),
357 };
358 let mut dn_sid = HashMap::new();
359 let mut sid_type = HashMap::new();
360 let schema_guid_map = HashMap::new();
361
362 domain
363 .parse(
364 result,
365 "example.local",
366 &mut dn_sid,
367 &mut sid_type,
368 &schema_guid_map,
369 )
370 .unwrap();
371
372 assert_eq!(domain.properties.dsheuristics, "0000000001000001");
373 assert_eq!(domain.to_json()["Properties"]["dsheuristics"], "0000000001000001");
374 }
375}