-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathchecks.py
More file actions
4434 lines (4105 loc) · 164 KB
/
Copy pathchecks.py
File metadata and controls
4434 lines (4105 loc) · 164 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
All security checks. Each function receives an ADConnector and returns
(list[Finding], dict). run_all_checks() aggregates them all.
Original checks : 1–24 (preserved verbatim)
New checks : 25–35
25. GPP / cpassword in SYSVOL (MS14-025)
26. AdminSDHolder ACL Inspection
27. SID History Abuse
28. Shadow Credentials (msDS-KeyCredentialLink)
29. RC4 / Legacy Kerberos Encryption Still Permitted
30. Foreign Security Principals in Privileged Groups
31. Pre-Windows 2000 Compatible Access Group
32. Dangerous Constrained Delegation Targets (LDAP / CIFS / HOST on DCs)
33. Orphaned AD Subnets (not mapped to any site)
34. Legacy FRS SYSVOL Replication
35. RBCD Configured on the Domain Object Itself
Bonus: Indirect Privileged Group Membership (non-direct transitive members)
"""
import datetime
import os
import socket
import struct
import urllib.request
import xml.etree.ElementTree as ET
from typing import List, Tuple, Dict, Any
from connector import ADConnector
from models import Finding
F = Finding
NOW = datetime.datetime.now(datetime.timezone.utc)
# ── helpers ────────────────────────────────────────────────────────────────────
def _attr_raw(entry, name):
raw = getattr(entry, name, None)
if raw is None:
return None
if hasattr(raw, "value"):
return raw.value
if hasattr(raw, "raw_values") and raw.raw_values:
return raw.raw_values[0]
return raw
def _ldap_ts_to_dt(raw):
if raw is None:
return None
if isinstance(raw, datetime.datetime):
return raw.replace(tzinfo=datetime.timezone.utc) if raw.tzinfo is None else raw
if isinstance(raw, bytes):
raw = raw.decode("utf-8", errors="ignore")
if isinstance(raw, str) and len(raw) >= 14 and not raw.lstrip("-").isdigit():
try:
clean = raw.split(".")[0].replace("Z", "")
return datetime.datetime.strptime(clean, "%Y%m%d%H%M%S").replace(
tzinfo=datetime.timezone.utc
)
except (ValueError, IndexError):
pass
try:
v = int(raw)
if v <= 0:
return None
epoch = datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc)
return epoch + datetime.timedelta(microseconds=v // 10)
except (ValueError, TypeError, OverflowError):
return None
def _days_since(dt):
if dt is None:
return None
return (NOW - dt).days
def _100ns_to_days(val: int) -> int:
if val >= 0:
return 0
return abs(val) // 864_000_000_000
# UAC flags
UAC_DISABLED = 0x0002
UAC_PASSWD_NOTREQD = 0x0020
UAC_DONT_EXPIRE_PASSWD = 0x10000
UAC_NO_PREAUTH = 0x400000
UAC_USE_DES_KEY_ONLY = 0x200000
# Well-known SID RIDs
_DA_RID = "512"
_EA_RID = "519"
_DC_RID = "516"
_RODC_RID = "521"
_EDC_RID = "498"
_SA_RID = "518"
_ADMINS = "S-1-5-32-544"
_EVERYONE = "S-1-1-0"
_AUTH_USERS = "S-1-5-11"
_ANON = "S-1-5-7"
_ENTERPRISE_DCS = "S-1-5-9"
_SYSTEM = "S-1-5-18"
# Access mask flags
AM_GENERIC_ALL = 0x10000000
AM_GENERIC_WRITE = 0x40000000
AM_WRITE_DACL = 0x00040000
AM_WRITE_OWNER = 0x00080000
AM_WRITE_PROP = 0x00000020
# Replication right GUIDs
REPL_GET_CHANGES = "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2"
REPL_GET_CHANGES_ALL = "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"
REPL_GET_CHANGES_FIL = "89e95b76-444d-4c62-991a-0facbeda640c"
# ADCS EKU OIDs
CLIENT_AUTH = {
"1.3.6.1.5.5.7.3.2",
"1.3.6.1.5.2.3.4",
"1.3.6.1.4.1.311.20.2.2",
"2.5.29.37.0",
}
ANY_PURPOSE = "2.5.29.37.0"
ENROLL_AGENT = "1.3.6.1.4.1.311.20.2.1"
ENROLL_RIGHT = "0e10c968-78fb-11d2-90d4-00c04f79dc55"
AUTOENROLL_RIGHT = "a05b8cc2-17bc-4802-a710-e7c15ab866a2"
CA_MANAGE = 0x00000001
CA_OFFICER = 0x00000010
_CA_TYPE_TEMPLATES = {"CA", "SubCA", "CrossCA", "RootCertificateAuthority"}
CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT = 0x00000001
CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT_ALT_NAME = 0x00010000
CT_FLAG_SUBJECT_ALT_REQUIRE_UPN = 0x00000400
CT_FLAG_SUBJECT_ALT_REQUIRE_EMAIL = 0x00000800
CT_FLAG_SUBJECT_ALT_REQUIRE_DNS = 0x00000008
CT_FLAG_SUBJECT_REQUIRE_EMAIL = 0x00000010
CT_FLAG_SUBJECT_REQUIRE_DNS_AS_CN = 0x00000004
CT_FLAG_NO_SECURITY_EXTENSION = 0x00080000
CT_FLAG_PEND_ALL_REQUESTS = 0x00000002
CT_FLAG_AUTO_ENROLLMENT = 0x00000020
DEPRECATED_OS_PATTERNS = (
"windows xp",
"windows vista",
"windows 7",
"windows 8",
"windows 8.1",
"nt 4",
"windows 2000",
"server 2003",
"server 2008",
)
# High-value Kerberos service prefixes for delegation checks (check 32)
DANGEROUS_SVC_PREFIXES = (
"ldap/",
"ldaps/",
"krbtgt/",
"host/",
"cifs/",
"gc/",
"rpcss/",
"dnshost/",
)
def _priv_group_dns(base_dn: str) -> set:
return {
f"CN=Domain Admins,CN=Users,{base_dn}",
f"CN=Enterprise Admins,CN=Users,{base_dn}",
f"CN=Schema Admins,CN=Users,{base_dn}",
f"CN=Administrators,CN=Builtin,{base_dn}",
f"CN=Account Operators,CN=Builtin,{base_dn}",
f"CN=Backup Operators,CN=Builtin,{base_dn}",
f"CN=Print Operators,CN=Builtin,{base_dn}",
f"CN=Server Operators,CN=Builtin,{base_dn}",
f"CN=Group Policy Creator Owners,CN=Users,{base_dn}",
f"CN=Replicator,CN=Builtin,{base_dn}",
}
def _get_domain_sid(ad: ADConnector) -> str:
dom = ad.get_domain_object()
if not dom:
return ""
raw = getattr(dom, "objectSid", None)
if not raw or not raw.value:
return ""
s = str(raw.value)
parts = s.split("-")
if len(parts) == 8:
return "-".join(parts[:7])
return s
def _sid_is_privileged(sid: str, domain_sid: str) -> bool:
always_ok = {
_ADMINS,
_ENTERPRISE_DCS,
_SYSTEM,
"S-1-5-9",
"S-1-5-32-548",
"S-1-5-32-569",
"S-1-5-11",
}
if sid in always_ok:
return True
if not domain_sid:
return False
for rid in (_DA_RID, _EA_RID, _DC_RID, _SA_RID, _RODC_RID, _EDC_RID, "517"):
if sid == f"{domain_sid}-{rid}":
return True
return False
def _sid_is_dc(sid: str, ad: ADConnector) -> bool:
try:
results = ad.search(
f"(&(objectClass=computer)(objectSid={sid})"
f"(userAccountControl:1.2.840.113556.1.4.803:=8192))",
["sAMAccountName"],
)
return bool(results)
except Exception:
return False
# ── ACL binary parsing ──────────────────────────────────────────────────────────
def _parse_sd(raw_sd: bytes):
import struct
aces = []
if not raw_sd or len(raw_sd) < 20:
return aces
try:
revision, sbz1, control, off_owner, off_group, off_sacl, off_dacl = (
struct.unpack_from("<BBHIIII", raw_sd, 0)
)
if off_dacl == 0:
return aces
acl_rev, _, acl_size, ace_count, _ = struct.unpack_from(
"<BBHHH", raw_sd, off_dacl
)
offset = off_dacl + 8
for _ in range(ace_count):
if offset + 4 > len(raw_sd):
break
ace_type, ace_flags, ace_size = struct.unpack_from("<BBH", raw_sd, offset)
ace_data = raw_sd[offset : offset + ace_size]
access_mask = (
struct.unpack_from("<I", ace_data, 4)[0] if len(ace_data) >= 8 else 0
)
object_type = None
sid_offset = 8
if ace_type in (0x05, 0x06, 0x07, 0x08):
obj_flags = (
struct.unpack_from("<I", ace_data, 8)[0]
if len(ace_data) >= 12
else 0
)
sid_offset = 12
if obj_flags & 0x1:
if len(ace_data) >= sid_offset + 16:
b = ace_data[sid_offset : sid_offset + 16]
object_type = (
f"{int.from_bytes(b[0:4],'little'):08x}-"
f"{int.from_bytes(b[4:6],'little'):04x}-"
f"{int.from_bytes(b[6:8],'little'):04x}-"
f"{b[8:10].hex()}-{b[10:16].hex()}"
)
sid_offset += 16
if obj_flags & 0x2:
sid_offset += 16
if sid_offset + 8 <= len(ace_data):
sid_rev = ace_data[sid_offset]
sub_count = ace_data[sid_offset + 1]
authority = int.from_bytes(
ace_data[sid_offset + 2 : sid_offset + 8], "big"
)
subs = []
for i in range(sub_count):
so = sid_offset + 8 + i * 4
if so + 4 <= len(ace_data):
subs.append(struct.unpack_from("<I", ace_data, so)[0])
sid = f"S-{sid_rev}-{authority}-" + "-".join(str(s) for s in subs)
aces.append(
{
"ace_type": ace_type,
"access_mask": access_mask,
"object_type": object_type,
"trustee_sid": sid,
}
)
offset += ace_size
except Exception:
pass
return aces
def _get_template_enrollees(ad: ADConnector, tmpl_dn: str, domain_sid: str) -> list:
from ldap3 import BASE
from ldap3.protocol.microsoft import security_descriptor_control
enrollees = []
try:
ctrl = security_descriptor_control(sdflags=0x04)
ad.conn.search(
search_base=tmpl_dn,
search_filter="(objectClass=*)",
search_scope=BASE,
attributes=["nTSecurityDescriptor"],
controls=ctrl,
)
if not ad.conn.entries:
return enrollees
sd_attr = getattr(ad.conn.entries[0], "nTSecurityDescriptor", None)
raw_sd = sd_attr.raw_values[0] if (sd_attr and sd_attr.raw_values) else None
if not raw_sd:
return enrollees
seen = set()
for ace in _parse_sd(raw_sd):
if ace["ace_type"] not in (0x00, 0x05):
continue
sid = ace["trustee_sid"]
otype = (ace.get("object_type") or "").lower().strip()
mask = ace["access_mask"]
if ace["ace_type"] == 0x05 and otype not in (
ENROLL_RIGHT,
AUTOENROLL_RIGHT,
):
continue
if ace["ace_type"] == 0x00 and not (mask & AM_GENERIC_ALL):
continue
if _sid_is_privileged(sid, domain_sid):
continue
if sid in seen:
continue
seen.add(sid)
enrollees.append(ad.resolve_sid(sid))
except Exception as e:
print(f" [~] Enrollee ACL fetch failed ({tmpl_dn[:60]}): {e}")
return enrollees
def _fmt_tmpl(name: str, enrollees: list) -> str:
if enrollees:
return f"{name} (enrollees: {', '.join(enrollees)})"
return name
# ── SMB probes ─────────────────────────────────────────────────────────────────
_SMB2_DIALECT_MAP = {
0x0202: "SMB 2.0.2",
0x0210: "SMB 2.1",
0x0300: "SMB 3.0",
0x0302: "SMB 3.0.2",
0x0311: "SMB 3.1.1",
}
_SMB1_NEGOTIATE_PKT = (
b"\x00\x00\x00\x2f"
b"\xff\x53\x4d\x42" # \xffSMB
b"\x72" # Command: Negotiate
b"\x00\x00\x00\x00" # NT Status
b"\x18\x01\x28" # Flags / Flags2
b"\x00\x00" # PID High
b"\x00\x00\x00\x00\x00\x00\x00\x00" # Security signature
b"\x00\x00\xff\xff\xfe\xff\x00\x00\x00\x00" # Reserved/TID/PID/UID/MID
b"\x00" # Word count
b"\x0c\x00" # Byte count
b"\x02NT LM 0.12\x00" # Dialect
)
def _smb_recv(sock: socket.socket, length: int) -> bytes:
buf = b""
while len(buf) < length:
chunk = sock.recv(length - len(buf))
if not chunk:
break
buf += chunk
return buf
def _is_conn_reset(exc: Exception) -> bool:
msg = str(exc).lower()
return (
"10054" in msg
or "connection was forcibly closed" in msg
or "connection reset" in msg
or "econnreset" in msg
)
def _smb1_negotiate(ip: str, timeout: float = 3.0) -> bool:
"""Return True only if the server responds with a successful SMBv1 negotiate."""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
s.connect((ip, 445))
s.sendall(_SMB1_NEGOTIATE_PKT)
nb = _smb_recv(s, 4)
if len(nb) < 4:
return False
body_len = struct.unpack(">I", nb)[0] & 0x00FFFFFF
body = _smb_recv(s, min(body_len, 256))
if len(body) < 9:
return False
# \xffSMB + 0x72 (negotiate response) + NT Status 0x00000000
return (
body[0:4] == b"\xff\x53\x4d\x42"
and body[4] == 0x72
and struct.unpack_from("<I", body, 5)[0] == 0
)
except Exception:
return False
def _build_smb2_negotiate() -> bytes:
"""
Build an SMB2 Negotiate Request offering dialects 2.0.2 – 3.1.1.
SMB 3.1.1 requires PREAUTH_INTEGRITY_CAPABILITIES (MS-SMB2 §2.2.3).
Response offsets (from byte 0 of TCP payload, after NetBIOS header):
0– 3 ProtocolId (\xfeSMB)
4– 5 StructureSize = 64
6– 7 CreditCharge
8–11 NT Status
12–13 Command
...
64–65 [body] StructureSize = 65
66–67 [body] SecurityMode bit 0x01 = enabled, 0x02 = required
68–69 [body] DialectRevision
"""
dialects = (0x0202, 0x0210, 0x0300, 0x0302, 0x0311)
dialect_bytes = b"".join(struct.pack("<H", d) for d in dialects)
# PREAUTH_INTEGRITY_CAPABILITIES context (SHA-512, type 0x0001)
preauth_data = struct.pack("<HHH", 1, 0, 0x0001) # 6 bytes
neg_ctx = (
struct.pack("<HHI", 0x0001, len(preauth_data), 0) + preauth_data
) # 14 bytes total
# NegotiateContextOffset is absolute from start of SMB2 header (64 bytes).
# Fixed body = 36, dialects = 10 → absolute 110; pad to 8-byte boundary → 112.
dialects_end = 64 + 36 + len(dialect_bytes) # 110
pad_len = (8 - dialects_end % 8) % 8 # 2
neg_ctx_offset = dialects_end + pad_len # 112
body = (
struct.pack("<H", 36) # StructureSize
+ struct.pack("<H", len(dialects)) # DialectCount
+ struct.pack("<H", 0x0001) # SecurityMode: signing enabled
+ struct.pack("<H", 0) # Reserved
+ struct.pack("<I", 0x0000007F) # Capabilities
+ b"\x00" * 16 # ClientGuid
+ struct.pack("<I", neg_ctx_offset) # NegotiateContextOffset
+ struct.pack("<H", 1) # NegotiateContextCount
+ struct.pack("<H", 0) # Reserved2
+ dialect_bytes
+ b"\x00" * pad_len # Alignment padding
+ neg_ctx
)
smb2_hdr = (
b"\xfeSMB"
+ struct.pack("<H", 64) # StructureSize
+ b"\x00\x00" # CreditCharge
+ b"\x00\x00\x00\x00" # Status
+ b"\x00\x00" # Command: Negotiate (0)
+ b"\x1f\x00" # CreditRequest
+ b"\x00\x00\x00\x00" # Flags
+ b"\x00\x00\x00\x00" # NextCommand
+ b"\x00" * 8 # MessageId
+ b"\x00" * 4 # Reserved
+ b"\x00" * 4 # TreeId
+ b"\x00" * 8 # SessionId
+ b"\x00" * 16 # Signature
)
payload = smb2_hdr + body
return b"\x00" + len(payload).to_bytes(3, "big") + payload
def _check_smb_signing(ip: str, timeout: float = 3.0) -> tuple:
"""
Return (signing_status, smb_version).
signing_status : "required" | "enabled_not_required" | "disabled" |
"smb2_disabled" | "unreachable" | "error"
smb_version : e.g. "SMB 3.1.1", or None
"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
s.connect((ip, 445))
s.sendall(_build_smb2_negotiate())
nb = _smb_recv(s, 4)
if len(nb) < 4:
return "smb2_disabled", None
body_len = struct.unpack(">I", nb)[0] & 0x00FFFFFF
body = _smb_recv(s, min(body_len, 512))
if len(body) < 68 or body[0:4] != b"\xfeSMB":
return "smb2_disabled", None
nt_status = struct.unpack_from("<I", body, 8)[0]
if nt_status != 0:
return "error", None
sec_mode = struct.unpack_from("<H", body, 66)[0]
dialect_code = (
struct.unpack_from("<H", body, 68)[0] if len(body) >= 70 else None
)
ver = (
_SMB2_DIALECT_MAP.get(dialect_code)
if dialect_code is not None
else None
)
if sec_mode & 0x02:
return "required", ver
if sec_mode & 0x01:
return "enabled_not_required", ver
return "disabled", ver
except socket.timeout:
return "error", None
except ConnectionRefusedError:
return "unreachable", None
except Exception as e:
if _is_conn_reset(e):
return "smb2_disabled", None
return "error", None
def _check_null_session(ip: str, timeout: float = 3.0) -> bool:
null_session_pkt = (
b"\x00\x00\x00\x59"
b"\xff\x53\x4d\x42"
b"\x73"
b"\x00\x00\x00\x00"
b"\x18"
b"\x07\xc0"
b"\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
b"\x00\x00"
b"\xff\xff"
b"\xff\xfe"
b"\x00\x00"
b"\x40\x00"
b"\x0d"
b"\xff"
b"\x00"
b"\x00\x00"
b"\xff\x00"
b"\x02\x00"
b"\x01\x00"
b"\x00\x00\x00\x00"
b"\x00\x00"
b"\x00\x00"
b"\x00\x00\x00\x00"
b"\x60\x48\x06\x06"
b"\x11\x00"
b"\x00"
b"\x00"
b"\x57\x69\x6e\x64\x6f\x77\x73\x00"
b"\x57\x69\x6e\x64\x6f\x77\x73\x00"
)
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
s.connect((ip, 445))
s.sendall(null_session_pkt)
resp = s.recv(256)
if len(resp) >= 13 and resp[4:8] == b"\xff\x53\x4d\x42":
return struct.unpack_from("<I", resp, 9)[0] == 0
except Exception:
pass
return False
def _check_smb1_hosts(ad: ADConnector) -> tuple:
targets = {
ad.dc_ip: ad.dc_ip
} # DC only — domain-wide host scan removed for performance
print(f" Probing DC ({ad.dc_ip}) for SMBv1 / signing / null sessions...")
smb1_vuln, signing_issues, null_sessions = [], [], []
for label, host in targets.items():
try:
ip = socket.gethostbyname(host)
except Exception:
continue
has_smb1 = _smb1_negotiate(ip)
sign, ver = _check_smb_signing(ip)
ver_str = ver if ver else "SMB2/3"
if has_smb1:
smb1_vuln.append(label)
if sign == "disabled":
signing_issues.append(f"{label} ({ver_str}, signing disabled)")
elif sign == "enabled_not_required":
signing_issues.append(
f"{label} ({ver_str}, signing enabled but not required)"
)
elif sign == "smb2_disabled" and has_smb1:
signing_issues.append(
f"{label} (SMBv1 only — SMB2/3 signing cannot be verified)"
)
# "unreachable" / "error" → probe inconclusive, not a misconfiguration
if _check_null_session(ip):
null_sessions.append(label)
return smb1_vuln, signing_issues, null_sessions
# ══════════════════════════════════════════════════════════════════════════════
# ORIGINAL CHECKS 1–24
# ══════════════════════════════════════════════════════════════════════════════
# -- 1. Password Policy --------------------------------------------------------
def check_password_policy(ad: ADConnector) -> Tuple[List[F], Dict]:
findings, stats = [], {}
print(" [*] Password Policy")
dom = ad.get_domain_object()
if not dom:
return findings, stats
min_len = ad.attr_int(dom, "minPwdLength")
history = ad.attr_int(dom, "pwdHistoryLength")
lockout = ad.attr_int(dom, "lockoutThreshold")
lock_dur = ad.attr_int(dom, "lockoutDuration")
max_age = _100ns_to_days(ad.attr_int(dom, "maxPwdAge", -1))
min_age = _100ns_to_days(ad.attr_int(dom, "minPwdAge", 0))
pwd_props = ad.attr_int(dom, "pwdProperties")
stats["password_policy"] = dict(
min_length=min_len,
history=history,
lockout_threshold=lockout,
max_age_days=max_age,
min_age_days=min_age,
)
if min_len < 8:
findings.append(
F(
"Password Policy",
"Minimum Password Length < 8",
"HIGH",
f"Minimum length is {min_len}.",
recommendation="Set minimum password length to >= 14.",
risk_score=15,
)
)
elif min_len < 12:
findings.append(
F(
"Password Policy",
"Minimum Password Length < 12",
"MEDIUM",
f"Minimum length is {min_len}.",
recommendation="Consider raising to 14+ characters.",
risk_score=5,
)
)
if history < 10:
findings.append(
F(
"Password Policy",
"Password History Too Short",
"MEDIUM",
f"History is {history} (recommended >= 24).",
recommendation="Set password history to 24.",
risk_score=5,
)
)
if max_age == 0:
findings.append(
F(
"Password Policy",
"Passwords Never Expire",
"MEDIUM",
"No maximum password age configured.",
recommendation="Set max password age to <= 90 days.",
risk_score=10,
)
)
elif max_age > 365:
findings.append(
F(
"Password Policy",
"Password Max Age > 1 Year",
"LOW",
f"Max password age is {max_age} days.",
recommendation="Reduce to <= 90 days.",
risk_score=5,
)
)
if lockout == 0:
findings.append(
F(
"Password Policy",
"No Account Lockout Policy",
"CRITICAL",
"Lockout threshold is 0 -- unlimited password guessing allowed.",
recommendation="Set lockout threshold to 5-10 attempts.",
risk_score=20,
)
)
elif lockout > 10:
findings.append(
F(
"Password Policy",
"Lockout Threshold Too High",
"LOW",
f"Lockout threshold is {lockout}.",
recommendation="Reduce to <= 10 failed attempts.",
risk_score=3,
)
)
if lockout > 0 and lock_dur == 0:
findings.append(
F(
"Password Policy",
"Lockout Requires Manual Admin Unlock",
"INFO",
"Lockout duration is 0 -- admin must manually unlock accounts.",
recommendation="Set lockout duration to 15-30 minutes unless intentional.",
risk_score=0,
)
)
if not (pwd_props & 1):
findings.append(
F(
"Password Policy",
"Password Complexity Disabled",
"MEDIUM",
"Complexity requirements are off.",
recommendation="Enable password complexity or enforce passphrase policy.",
risk_score=10,
)
)
if pwd_props & 16:
findings.append(
F(
"Password Policy",
"Reversible Encryption Enabled (Domain Policy)",
"CRITICAL",
"Passwords stored with reversible encryption (effectively plaintext).",
recommendation="Disable reversible password encryption immediately.",
risk_score=25,
)
)
if min_age == 0:
findings.append(
F(
"Password Policy",
"No Minimum Password Age",
"LOW",
"Users can change passwords immediately, bypassing history controls.",
recommendation="Set minimum password age to 1 day.",
risk_score=3,
)
)
psos = ad.search(
"(objectClass=msDS-PasswordSettings)",
["cn", "msDS-MinimumPasswordLength", "msDS-LockoutThreshold"],
base=f"CN=Password Settings Container,CN=System,{ad.base_dn}",
)
if psos:
pso_issues = []
for p in psos:
pname = ad.attr_str(p, "cn")
plen = ad.attr_int(p, "msDS-MinimumPasswordLength")
plockout = ad.attr_int(p, "msDS-LockoutThreshold")
if plen < 8 or plockout == 0:
pso_issues.append(f"{pname} (len={plen}, lockout={plockout})")
if pso_issues:
findings.append(
F(
"Password Policy",
"Weak Fine-Grained Password Policy (PSO)",
"HIGH",
f"{len(pso_issues)} PSO(s) have weak settings.",
details=pso_issues,
recommendation="Review and harden all PSOs.",
risk_score=10,
)
)
stats["psos"] = [ad.attr_str(p, "cn") for p in psos]
return findings, stats
# -- 2. Privileged Accounts ----------------------------------------------------
def check_privileged_accounts(ad: ADConnector) -> Tuple[List[F], Dict]:
findings, stats = [], {}
print(" [*] Privileged Accounts")
PRIV_GROUPS = {
"Domain Admins": f"CN=Domain Admins,CN=Users,{ad.base_dn}",
"Enterprise Admins": f"CN=Enterprise Admins,CN=Users,{ad.base_dn}",
"Schema Admins": f"CN=Schema Admins,CN=Users,{ad.base_dn}",
"Administrators": f"CN=Administrators,CN=Builtin,{ad.base_dn}",
"Account Operators": f"CN=Account Operators,CN=Builtin,{ad.base_dn}",
"Backup Operators": f"CN=Backup Operators,CN=Builtin,{ad.base_dn}",
"Print Operators": f"CN=Print Operators,CN=Builtin,{ad.base_dn}",
"Server Operators": f"CN=Server Operators,CN=Builtin,{ad.base_dn}",
"Group Policy Creator Owners": f"CN=Group Policy Creator Owners,CN=Users,{ad.base_dn}",
"DNS Admins": f"CN=DnsAdmins,CN=Users,{ad.base_dn}",
"Remote Desktop Users": f"CN=Remote Desktop Users,CN=Builtin,{ad.base_dn}",
}
SENSITIVE = {
"Domain Admins",
"Enterprise Admins",
"Schema Admins",
"Administrators",
}
for gname, gdn in PRIV_GROUPS.items():
members = ad.search(
f"(&(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:={gdn}))",
[
"sAMAccountName",
"userAccountControl",
"lastLogonTimestamp",
"pwdLastSet",
"description",
],
)
names, stale, no_expire, pwd_in_desc = [], [], [], []
for u in members:
n = ad.attr_str(u, "sAMAccountName")
names.append(n)
uac = ad.attr_int(u, "userAccountControl")
llt = _ldap_ts_to_dt(_attr_raw(u, "lastLogonTimestamp"))
if _days_since(llt) and _days_since(llt) > 90:
stale.append(f"{n} ({_days_since(llt)}d inactive)")
if uac & UAC_DONT_EXPIRE_PASSWD:
no_expire.append(n)
desc = ad.attr_str(u, "description").lower()
for kw in ("password", "passwd", "pwd", "pass=", "mot de passe"):
if kw in desc:
pwd_in_desc.append(n)
break
stats[f"group_{gname}"] = names
if gname in SENSITIVE and len(names) > 5:
findings.append(
F(
"Privileged Accounts",
f"Too Many Members in '{gname}'",
"HIGH",
f"{len(names)} members (recommended <= 5).",
details=names,
recommendation=f"Reduce '{gname}' membership to essential accounts only.",
risk_score=15,
)
)
if stale and gname in SENSITIVE:
findings.append(
F(
"Privileged Accounts",
f"Stale Members in '{gname}'",
"HIGH",
f"{len(stale)} member(s) inactive for 90+ days.",
details=stale,
recommendation="Disable or remove stale privileged accounts.",
risk_score=12,
)
)
if no_expire and gname in SENSITIVE:
findings.append(
F(
"Privileged Accounts",
f"Non-Expiring Passwords in '{gname}'",
"MEDIUM",
f"{len(no_expire)} admin(s) with non-expiring passwords.",
details=no_expire,
recommendation="Enforce password expiration on all admin accounts.",
risk_score=8,
)
)
if pwd_in_desc:
findings.append(
F(
"Privileged Accounts",
"Password Stored in Account Description",
"HIGH",
f"{len(pwd_in_desc)} account(s) may have passwords in the Description field.",
details=pwd_in_desc,
recommendation="Remove credentials from description fields.",
risk_score=15,
)
)
admin500 = ad.search(
"(&(objectClass=user)(adminCount=1))",
["sAMAccountName", "userAccountControl", "lastLogonTimestamp"],
)
for u in admin500:
if ad.attr_str(u, "sAMAccountName").lower() in (
"administrator",
"administrateur",
):
uac = ad.attr_int(u, "userAccountControl")
if not (uac & UAC_DISABLED):
findings.append(
F(
"Privileged Accounts",
"Built-in Administrator Account Enabled",
"MEDIUM",
"The built-in Administrator account (RID-500) is active.",
recommendation="Rename and/or create a decoy Administrator account. Consider disabling it.",
risk_score=8,
)
)
llt = _ldap_ts_to_dt(_attr_raw(u, "lastLogonTimestamp"))
if llt and _days_since(llt) < 30:
findings.append(
F(
"Privileged Accounts",
"Built-in Administrator Recently Used",
"HIGH",
"RID-500 administrator logged in recently -- should not be used for daily tasks.",
recommendation="Use named admin accounts; reserve RID-500 for break-glass only.",
risk_score=12,
)
)
krb = ad.search("(&(objectClass=user)(sAMAccountName=krbtgt))", ["pwdLastSet"])
if krb:
pls = _ldap_ts_to_dt(_attr_raw(krb[0], "pwdLastSet"))
days = _days_since(pls)
if days is None or days > 180:
findings.append(
F(
"Privileged Accounts",
"krbtgt Password Not Reset Recently",
"HIGH",
f"krbtgt password is {days if days is not None else 'unknown'} days old.",
recommendation="Reset krbtgt password twice (with pause) following Microsoft guidance.",
risk_score=15,
references=[
"https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/ad-forest-recovery-resetting-the-krbtgt-password"
],
)
)
return findings, stats
# -- 3. Kerberos ---------------------------------------------------------------
def check_kerberos(ad: ADConnector) -> Tuple[List[F], Dict]:
findings, stats = [], {}
print(" [*] Kerberos")
kerb = ad.search(
"(&(objectClass=user)(servicePrincipalName=*)"
"(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
[
"sAMAccountName",
"servicePrincipalName",
"adminCount",
"pwdLastSet",
"userAccountControl",
],
)
kerb_admin, kerb_stale_pwd, kerb_details, kerb_neverexpire = [], [], [], []
for u in kerb:
n = ad.attr_str(u, "sAMAccountName")
adm = ad.attr_int(u, "adminCount") == 1
uac = ad.attr_int(u, "userAccountControl")
pls = _ldap_ts_to_dt(_attr_raw(u, "pwdLastSet"))
age = _days_since(pls)
spns = ad.attr_list(u, "servicePrincipalName")
tag = " [ADMIN]" if adm else ""
kerb_details.append(f"{n}{tag} -- SPNs: {', '.join(spns[:3])}")
if adm:
kerb_admin.append(n)
if age and age > 365:
kerb_stale_pwd.append(f"{n} (password age: {age}d)")
if (uac & UAC_DONT_EXPIRE_PASSWD) and adm:
kerb_neverexpire.append(n)
if kerb:
sev = "CRITICAL" if kerb_admin else "HIGH"
findings.append(