-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesc4_scanner.py
More file actions
1274 lines (1055 loc) · 47.4 KB
/
esc4_scanner.py
File metadata and controls
1274 lines (1055 loc) · 47.4 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
# Standard library imports
import argparse
import getpass
import socket
import struct
import time
# Third-party imports
from colored import fore
from ldap3 import ALL, Connection, NTLM, Server
from ldap3.protocol.microsoft import security_descriptor_control
# Constants and Dicts
TAB = " "
ALL_SID = dict()
COLORS = {
"white": fore("white"),
"blue": fore("blue"),
"cyan": fore("cyan"),
"green": fore("green_4"),
"orange": fore("orange_3"),
"red": fore("red")
}
CA_PERMISSIONS_ACCESS_MASKS = {
0x00000001: [
"Administrator",
"Has full control of the CA (configuration, user accounts management, "
"system maintenance)",
],
0x00000002: [
"Officer",
"Authorized to approve or deny certificate requests and manage revocations",
],
0x00000004: [
"Auditor",
"Authorized to view and maintain audit logs",
],
0x00000008: [
"Operator",
"Authorized to perform system backup and recovery operations for the CA",
],
0x00000100: [
"Read",
"Authorized to view basic CA properties (configuration and available templates)",
],
0x00000200: [
"Enroll",
"Authorized to request certificates from the CA",
],
}
AD_OBJECTS_ACCESS_MASKS = {
0x00000001: [
"CC",
"CREATE_CHILD",
"The right to create child objects of the object. ObjectType may "
"identify a specific child class; if absent, applies to all allowed "
"child classes.",
],
0x00000002: [
"DC",
"DELETE_CHILD",
"The right to delete child objects of the object. ObjectType may "
"identify a specific child class; if absent, applies to all child "
"classes.",
],
0x00000004: [
"LC",
"LIST_CONTENTS",
"The right to list child objects of this object",
],
# 0x00000008: ["SW", "SELF_WRITE", ""],
0x00000008: [
"VW",
"WRITE_PROPERTY_EXTENDED",
"The right to perform an operation controlled by a validated write "
"access right. ObjectType may identify a specific validated write; if "
"absent, applies to all validated writes.",
],
0x00000010: [
"RP",
"READ_PROPERTY",
"The right to read properties of the object. ObjectType may identify "
"a property set or attribute; if absent, applies to all attributes.",
],
0x00000020: [
"WP",
"WRITE_PROPERTY",
"The right to write properties of the object. ObjectType may identify "
"a property set or attribute; if absent, applies to all attributes.",
],
0x00000040: [
"DT",
"DELETE_TREE",
"The right to perform a Delete-Tree operation on this object",
],
0x00000080: [
"LO",
"LIST_OBJECT",
"The right to list a particular object",
],
# 0x00000100: ["CR", "EXTENDED_RIGHT", ""],
0x00000100: [
"CR",
"CONTROL_ACCESS",
"The right to perform an operation controlled by a control access "
"right. ObjectType may identify a specific control access right; if "
"absent, applies to all such operations.",
],
0x00010000: ["DE", "DELETE", "The right to delete the object"],
0x00020000: [
"RC",
"READ_CONTROL",
"The right to read data from the security descriptor of the object, "
"not including the data in the SACL",
],
0x00040000: [
"WD",
"WRITE_DAC",
"The right to modify the DACL in the object security descriptor",
],
0x00080000: [
"WO",
"WRITE_OWNER",
"The right to modify the owner of the object in its security "
"descriptor (users can take ownership).",
],
# Generic rights (not stored in AD; shown here for reference):
# 0x10000000: ["GA", "GENERIC_ALL", "Maps to (DE|RC|WD|WO|CC|DC|DT|RP|WP|LC|LO|CR|VW)"],
# 0x20000000: ["GX", "GENERIC_EXECUTE", "Maps to (RC|LC)"],
# 0x40000000: ["GW", "GENERIC_WRITE", "Maps to (RC|WP|VW)"],
# 0x80000000: ["GR", "GENERIC_READ", "Maps to (RC|LC|RP|LO)"],
}
ACL_REVISIONS = {
2: ["Default", "Supports basic ACE types"],
3: ["Compound", "Supports basic and coumpound ACE types"],
4: ["Object", "Supports basic, compound and object ACE types"]
}
ACE_TYPES = {
0x00: ["DACL", 2, "ACCESS_ALLOWED_ACE", "Grants access to a resource"],
0x01: ["DACL", 2, "ACCESS_DENIED_ACE", "Denies access to a resource"],
0x02: ["SACL", 2, "SYSTEM_AUDIT_ACE", "Audits access to a resource"],
0x03: [
"SACL",
2,
"SYSTEM_ALARM_ACE",
"Alarms upon acess to a resource; unused",
],
0x04: [
"DACL",
3,
"ACCESS_ALLOWED_COMPOUND_ACE",
"Grants access to a resource during impersonation",
],
0x05: [
"DACL",
4,
"ACCESS_ALLOWED_OBJECT_ACE",
"Grants access to a resource with an object type",
],
0x06: [
"DACL",
4,
"ACCESS_DENIED_OBJECT_ACE",
"Denies access to a resource with an object type",
],
0x07: [
"SACL",
4,
"SYSTEM_AUDIT_OBJECT_ACE",
"Audits access to a resource with an object type",
],
0x08: [
"SACL",
4,
"SYSTEM_ALARM_OBJECT_ACE",
"Alarms upon access to a resource with an object type; unused",
],
0x09: [
"DACL",
2,
"ACCESS_ALLOWED_CALLBACK_ACE",
"Grants access to a resource with a callback",
],
0x0A: [
"DACL",
2,
"ACCESS_DENIED_CALLBACK_ACE",
"Denies access to a resource with a callback",
],
0x0B: [
"DACL",
4,
"ACCESS_ALLOWED_CALLBACK_OBJECT_ACE",
"Grants access to a resource with a callback and an object type",
],
0x0C: [
"DACL",
4,
"ACCESS_DENIED_CALLBACK_OBJECT_ACE",
"Denies access to a resource with a callback and an object type",
],
0x0D: [
"SACL",
2,
"SYSTEM_AUDIT_CALLBACK_ACE",
"Audits access to a resource with a callbackk",
],
0x0E: [
"SACL",
2,
"SYSTEM_ALARM_CALLBACK_ACE",
"Alarms upon access to a resource with a callback; unused",
],
0x0F: [
"SACL",
4,
"SYSTEM_AUDIT_CALLBACK_OBJECT_ACE",
"Audits access to a resource with a callback and an object type",
],
0x10: [
"SACL",
4,
"SYSTEM_ALARM_CALLBACK_OBJECT_ACE",
"Alarms upon access to a resource with a callback and an object type; unused",
],
0x11: ["SACL", 2, "SYSTEM_MANDATORY_LABEL_ACE", "Specifies a mandatory label"],
0x12: [
"SACL",
2,
"SYSTEM_RESOURCE_ATTRIBUTE_ACE",
"Specifies attributes for the resource",
],
0x13: [
"SACL",
2,
"SYSTEM_SCOPED_POLICY_ID_ACE",
"Specifie a central access policy ID for the resource",
],
0x14: [
"SACL",
2,
"SYSTEM_PROCESS_TRUST_LABEL_ACE",
"Specifies a process trust label to limite resource access",
],
0x15: [
"SACL",
2,
"SYSTEM_ACCESS_FILTER_ACE",
"Specifies an access filter for the resource",
],
}
ACE_FLAGS = {
0x01: ["ObjectInherit", "The ACE can be inherited by an object"],
0x02: ["ContainerInherit", "The ACE can be inherited by a container"],
0x04: ["NoPropagateInherit", "The ACE's inheritance flags are not propagated to children"],
0x08: ["InheritOnly", "The ACE is used only for inheritance and not for access checks"],
0x10: ["Inherited", "The ACE was inherited from a parent container"],
0x20: ["Critical", "The ACE is critical and can't be removed (applies only to Allowed ACEs)"],
0x40: ["SuccessfulAccess", "An audit event should be generated for a successful access"],
# 0x40: ["TrustProtected", "When used with an AccessFilter ACE, this flag prevents modification"]
0x80: ["FailedAccess", "An audit event should be generated for a failed access"]
}
# Auxiliar functions
def convert_domain_str_to_dn(domain_str):
"""
Convert domain string to distinguished name format.
Args:
domain_str (str): Domain name in format 'example.com'
Returns:
str: Distinguished name format 'DC=example,DC=com'
"""
components = domain_str.split(".")
domain_dn = ",".join([f"DC={component}" for component in components])
return domain_dn
def convert_sid_bytes_to_str(sid_bytes):
"""
Convert SID bytes to readable string format.
Args:
sid_bytes (bytes): Raw SID bytes from Active Directory
Returns:
str: SID string in format 'S-1-5-...'
"""
revision, sub_authority_count = struct.unpack('<BB', sid_bytes[:2])
authority = struct.unpack('>Q', b'\x00\x00' + sid_bytes[2:8])[0]
sub_authorities = []
for i in range(sub_authority_count):
sub_authority = struct.unpack('<L', sid_bytes[8 + i * 4:12 + i * 4])[0]
sub_authorities.append(sub_authority)
sid_string = f'S-{revision}-{authority}'
for sub_authority in sub_authorities:
sid_string += f'-{sub_authority}'
return sid_string
def convert_guid_bytes_to_str(guid_bytes):
"""
Convert GUID bytes to readable string format.
Args:
guid_bytes (bytes): Raw GUID bytes from Active Directory
Returns:
str: GUID string in format 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
"""
data = struct.unpack('<IHH8B', guid_bytes)
return '{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(*data)
def get_sam_account_name_from_sid(connection, domain, sid_str):
"""
Retrieve the SAM account name for a given SID from Active Directory.
Args:
connection: LDAP connection object
domain (str): Domain name
sid_str (str): SID string in format S-1-5-...
Returns:
str: SAM account name for the given SID, or an empty string if not found
"""
try:
sam_account_name = ""
search_base = f"{convert_domain_str_to_dn(domain)}"
search_filter = f"(objectSid={sid_str})"
attributes = ["sAMAccountName"]
search_scope = "SUBTREE"
if connection.search(
search_base, search_filter, attributes=attributes, search_scope=search_scope
) and len(connection.entries) > 0: # This LDAP search should only return one result
entry = connection.entries[0]
sam_account_name = str(entry["sAMAccountName"])
return sam_account_name
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return ""
def get_sid_from_sam_account_name(connection, domain, sam_str):
"""
Retrieve the SID for a given SAM account name from Active Directory.
Args:
connection: LDAP connection object
domain (str): Domain name
sam_str (str): SAM account name
Returns:
str: SID string in format S-1-5-... for the given SAM account name,
or an empty string if not found
"""
try:
sid = ""
search_base = f"{convert_domain_str_to_dn(domain)}"
search_filter = f"(sAMAccountName={sam_str})"
attributes = ["objectSid"]
search_scope = "SUBTREE"
if connection.search(
search_base, search_filter, attributes=attributes, search_scope=search_scope
) and len(connection.entries) > 0: # This LDAP search should only return one result
entry = connection.entries[0]
sid = str(entry["objectSid"])
return sid
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return ""
def establish_ldap_connection(domain, user, password="", dc_ip="", pth=False):
"""
Establish LDAP connection to the domain controller.
Args:
domain (str): Domain name
user (str): Username for authentication
password (str, optional): Password for authentication. Defaults to "".
dc_ip (str, optional): Domain controller IP address. Defaults to "".
pth (bool, optional): Whether to use pass-the-hash authentication. Defaults to False.
Returns:
Connection | None: LDAP connection object if successful, otherwise None
"""
try:
if dc_ip == "":
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Resolving {domain}...")
dc_ip = socket.gethostbyname(domain)
print(f"{COLORS['green']}[+] {COLORS['white']}Resolved {domain} to {dc_ip}")
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Establishing LDAP connection as {user}...")
server = Server(f"ldap://{dc_ip}", get_info=ALL)
if not pth:
connection = Connection(
server,
user=f"{domain}\\{user}",
password=password,
authentication=NTLM,
auto_bind=True,
)
else:
connection = Connection(
server,
user=f"{domain}\\{user}",
password=f"aad3b435b51404eeaad3b435b51404ee:{password}",
authentication=NTLM,
auto_bind=True,
)
if connection.bind():
print(f"{COLORS['green']}[+] {COLORS['white']}Successfully established LDAP connection")
return connection
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return None
# Enumeration functions
def enumerate(user, password, ca="", template="", dc_ip="", enabled=False, print_only_vulnerable=False, pth=False):
"""
Orchestrate ESC4 enumeration across LDAP, CAs, and templates.
This function performs the full scan workflow for ESC4: it connects to LDAP,
gathers low-privileged/administrative/user SIDs, enumerates CAs (offerings only),
enumerates certificate templates (security descriptor only), evaluates ESC4
conditions, and prints the results.
Args:
user (str): Username in format 'user@domain.com'.
password (str): Password or NTLM hash when using Pass-the-Hash.
ca (str): Specific CA to enumerate (optional).
template (str): Specific template to enumerate (optional).
dc_ip (str): Domain controller IP address (optional).
enabled (bool): If True, enumerate only templates enabled on some CA.
print_only_vulnerable (bool): If True, print only templates flagged as ESC4.
pth (bool): If True, use Pass-the-Hash authentication.
Returns:
None: Prints ESC4 enumeration output to the console.
"""
domain = user.split("@")[1]
user = user.split("@")[0]
ldap_connection = establish_ldap_connection(domain, user, password, dc_ip, pth)
low_priv_sids = enum_low_priv_sids(ldap_connection, domain)
admin_sids = enum_admin_sids(ldap_connection, domain)
privileged_sids = enum_privileged_member_sids(ldap_connection, domain, admin_sids)
user_sids = enum_user_sids(ldap_connection, domain, user, low_priv_sids)
certification_authorities = enumerate_certification_authorities(ldap_connection, domain, ca)
certificate_templates = enumerate_certificate_templates(ldap_connection, domain, certification_authorities, user_sids, privileged_sids, enabled, template)
print_enumeration_output(certification_authorities, certificate_templates, domain, ldap_connection, print_only_vulnerable)
def enum_low_priv_sids(connection, domain):
"""
Enumerate low-privileged SIDs from Active Directory.
This function retrieves common low-privileged security identifiers including
Everyone, Authenticated Users, Users, Domain Users, and Domain Computers.
Args:
connection: LDAP connection object
domain (str): Domain name
Returns:
dict: Dictionary mapping SIDs to their display names for low-privileged accounts
"""
try:
low_priv_sids = {
"S-1-1-0": "Everyone",
"S-1-5-11": "Authenticated Users",
"S-1-5-32-545": "Users"
}
low_priv_sam_account_names = ["Domain Users", "Domain Computers"]
for sam in low_priv_sam_account_names:
sid = get_sid_from_sam_account_name(connection, domain, sam)
if sid: # Only add if SID is not empty
low_priv_sids[sid] = sam
ALL_SID.update(low_priv_sids)
return low_priv_sids
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return {}
def enum_admin_sids(connection, domain):
"""
Enumerate administrative SIDs from Active Directory.
This function retrieves administrative security identifiers including
Enterprise Domain Controllers, Administrators, Domain Admins, and other
administrative groups.
Args:
connection: LDAP connection object
domain (str): Domain name
Returns:
dict: Dictionary mapping SIDs to their display names for administrative accounts
"""
try:
admin_sids = {
"S-1-5-9": "Enterprise Domain Controllers",
"S-1-5-32-544": "Administrators"
}
admin_sam_account_names = [
"Enterprise Read-only Domain Controllers",
"Administrator",
"Krbtgt",
"Domain Admins",
"Domain Controllers",
"Schema Admins",
"Enterprise Admins",
"Read-only Domain Controllers",
]
for sam in admin_sam_account_names:
sid = get_sid_from_sam_account_name(connection, domain, sam)
if sid: # Only add if SID is not empty
admin_sids[sid] = sam
ALL_SID.update(admin_sids)
return admin_sids
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return {}
def enum_privileged_member_sids(connection, domain, admin_sids):
"""
Expand privileged SIDs to include all direct and nested members of admin groups.
Args:
connection: LDAP connection object
domain (str): Domain name
admin_sids (dict): Mapping of privileged group/account SIDs to display names
Returns:
set[str]: Set of SIDs considered privileged (groups, users, computers)
"""
try:
privileged_set = set()
# Always include seeds (groups and admin accounts we know by SID)
for sid in admin_sids.keys():
privileged_set.add(sid)
domain_dn = convert_domain_str_to_dn(domain)
# Helper: get DN and objectClass for SID
def _get_dn_and_classes_for_sid(target_sid):
if connection.search(
domain_dn,
f"(objectSid={target_sid})",
attributes=["distinguishedName", "objectClass"],
search_scope="SUBTREE",
) and len(connection.entries) > 0:
entry = connection.entries[0]
dn = str(entry["distinguishedName"]) if "distinguishedName" in entry else ""
obj_classes = [str(v) for v in entry["objectClass"]] if "objectClass" in entry else []
return dn, obj_classes
return "", []
# Initialize a queue with admin groups' DNs to expand members
group_dn_queue = []
for sid in list(admin_sids.keys()):
dn, obj_classes = _get_dn_and_classes_for_sid(sid)
if dn and any(cls.lower() == "group" for cls in obj_classes):
group_dn_queue.append(dn)
processed_group_dns = set()
while group_dn_queue:
group_dn = group_dn_queue.pop(0)
if group_dn in processed_group_dns:
continue
processed_group_dns.add(group_dn)
# Fetch group members (DNs)
if connection.search(
domain_dn,
f"(distinguishedName={group_dn})",
attributes=["member"],
search_scope="SUBTREE",
) and len(connection.entries) > 0:
group_entry = connection.entries[0]
members = list(group_entry["member"]) if "member" in group_entry else []
for member_dn in members:
# Resolve member to SID and class
if connection.search(
domain_dn,
f"(distinguishedName={member_dn})",
attributes=["objectSid", "objectClass"],
search_scope="SUBTREE",
) and len(connection.entries) > 0:
member_entry = connection.entries[0]
member_sid = str(member_entry["objectSid"]) if "objectSid" in member_entry else ""
if member_sid:
privileged_set.add(member_sid)
member_classes = [str(v) for v in member_entry["objectClass"]] if "objectClass" in member_entry else []
if any(cls.lower() == "group" for cls in member_classes):
# Nested admin group: expand further
group_dn_queue.append(member_dn)
return privileged_set
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return set()
def enum_user_sids(connection, domain, user, low_priv_sids):
"""
Enumerate all SIDs associated with a user account.
This function retrieves the user's direct SID, primary group SID, and all
group memberships (including nested groups) from Active Directory.
Args:
connection: LDAP connection object
domain (str): Domain name
user (str): Username
low_priv_sids (dict): Dictionary of low-privileged SIDs to include
Returns:
dict: Dictionary mapping SIDs to their display names for the user and their groups
"""
try:
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Getting user SIDs...")
user_sids = {}
search_base = f"{convert_domain_str_to_dn(domain)}"
search_filter = f"(sAMAccountName={user})"
attributes = ["objectSid", "memberOf", "primaryGroupId"]
search_scope = "SUBTREE"
if connection.search(
search_base, search_filter, attributes=attributes, search_scope=search_scope
) and len(connection.entries) > 0: # This LDAP search should only return one result
current_user = connection.entries[0]
current_user_sid = str(current_user["objectSid"])
user_sids[current_user_sid] = user
primary_group_sid = f"{'-'.join(current_user_sid.split('-')[:-1])}-{str(current_user['primaryGroupId'])}"
search_filter = f"(objectSid={primary_group_sid})"
attributes = ["sAMAccountName"]
if connection.search(search_base, search_filter, attributes=attributes, search_scope=search_scope) and len(connection.entries) > 0:
primary_group_name = str(connection.entries[0]["sAMAccountName"])
user_sids[primary_group_sid] = primary_group_name
else:
user_sids[primary_group_sid] = ""
processed_groups = set()
groups = list(current_user["memberOf"])
while groups:
group_dn = groups.pop(0)
if group_dn in processed_groups:
continue
search_filter = f"(distinguishedName={group_dn})"
attributes = ["objectSid", "memberOf", "sAMAccountName"]
if connection.search(search_base, search_filter, attributes=attributes, search_scope=search_scope) and len(connection.entries) > 0:
group = connection.entries[0]
group_sid = str(group["objectSid"])
group_name = str(group["sAMAccountName"])
user_sids[group_sid] = group_name
indirect_membership = group["memberOf"]
if indirect_membership:
for indirect_group_dn in indirect_membership:
if indirect_group_dn not in processed_groups:
groups.append(indirect_group_dn)
for sid, name in low_priv_sids.items():
if sid not in user_sids:
user_sids[sid] = name
print(f"{COLORS['green']}[+] {COLORS['white']}User SIDs:")
for sid, name in user_sids.items():
print(f"{TAB * 3}{domain}\\{name} -> {sid}")
ALL_SID.update(user_sids)
return user_sids
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return {}
def enumerate_certification_authorities(connection, domain, ca=""):
"""
Enumerate Certification Authorities from Active Directory.
This function retrieves CA metadata including DNS hostname, distinguished
name, and the list of certificate templates offered by each CA. CA security
permissions are not enumerated in ESC4 mode.
Args:
connection: LDAP connection object.
domain (str): Domain name.
ca (str): Specific CA name to search for (optional).
Returns:
dict: Mapping of CA name to metadata (DNS, DN, offered templates).
"""
try:
certification_authorities = {}
if ca != "":
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Searching certification authority...")
search_base = (
f"CN={ca},CN=Enrollment Services,CN=Public Key Services,"
f"CN=Services,CN=Configuration,{convert_domain_str_to_dn(domain)}"
)
else:
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Searching certification authorities...")
search_base = (
f"CN=Enrollment Services,CN=Public Key Services,CN=Services,"
f"CN=Configuration,{convert_domain_str_to_dn(domain)}"
)
search_filter = "(objectClass=pKIEnrollmentService)"
attributes = ["name", "dNSHostName", "cACertificateDN", "certificateTemplates"]
search_scope = "SUBTREE"
if connection.search(search_base, search_filter, attributes=attributes, search_scope=search_scope):
if len(connection.entries) == 0:
print(f"{COLORS['red']} No certification authority found")
elif len(connection.entries) == 1:
print(f"{COLORS['green']}[+] {COLORS['white']}Found 1 certification authority:")
ca = connection.entries[0]
ca_name = str(ca["name"]) if "name" in ca else ""
ca_dns_hostname = str(ca["dNSHostName"]) if "dNSHostName" in ca else ""
ca_certificate_dn = str(ca["cACertificateDN"]) if "cACertificateDN" in ca else ""
ca_certificate_templates = list(ca["certificateTemplates"]) if "certificateTemplates" in ca else ""
certification_authorities[ca_name] = {
"ca_dns_hostname": ca_dns_hostname,
"ca_certificate_dn": ca_certificate_dn,
"ca_certificate_templates": ca_certificate_templates,
}
else:
print(f"{COLORS['green']}[+] {COLORS['white']}Found {len(connection.entries)} certification authorities:")
for ca in connection.entries:
ca_name = str(ca["name"]) if "name" in ca else ""
ca_dns_hostname = str(ca["dNSHostName"]) if "dNSHostName" in ca else ""
ca_certificate_dn = str(ca["cACertificateDN"]) if "cACertificateDN" in ca else ""
ca_certificate_templates = list(ca["certificateTemplates"]) if "certificateTemplates" in ca else ""
certification_authorities[ca_name] = {
"ca_dns_hostname": ca_dns_hostname,
"ca_certificate_dn": ca_certificate_dn,
"ca_certificate_templates": ca_certificate_templates,
}
if len(certification_authorities) > 0:
for ca_name, _ in certification_authorities.items():
print(f"{TAB * 3}{ca_name}")
return certification_authorities
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return {}
def enumerate_certificate_templates(connection, domain, ca_dict, user_sids, privileged_sids, enum_only_enabled, template_to_enum=""):
"""
Enumerate certificate templates from Active Directory.
This function retrieves security descriptors for templates (owner, group,
DACL) and correlates them with CA offerings to determine where each
template is enabled. ESC4 analysis is performed separately.
Args:
connection: LDAP connection object.
domain (str): Domain name.
ca_dict (dict): CA information used to compute enabled templates.
user_sids (dict): Dictionary of user SIDs.
privileged_sids (dict): Dictionary of privileged SIDs.
enum_only_enabled (bool): Whether to enumerate only enabled templates.
template_to_enum (str): Specific template name to search for (optional).
Returns:
dict: Mapping of template name to metadata (enabled_in, security_descriptor,
owner, group, parsed DACL).
"""
try:
enabled_certificates = {}
for ca_name, ca_info in ca_dict.items():
for template_name in ca_info["ca_certificate_templates"]:
if template_name not in enabled_certificates:
enabled_certificates[template_name] = set()
enabled_certificates[template_name].add(ca_name)
certificate_templates = {}
if template_to_enum != "":
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Searching certificate template...")
search_base = (
f"CN={template_to_enum},CN=Certificate Templates,CN=Public Key Services,"
f"CN=Services,CN=Configuration,{convert_domain_str_to_dn(domain)}"
)
else:
if enum_only_enabled:
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Searching enabled certificate templates...")
else:
print(f"\n{COLORS['blue']}[*] {COLORS['white']}Searching certificate templates...")
search_base = (
f"CN=Certificate Templates,CN=Public Key Services,CN=Services,"
f"CN=Configuration,{convert_domain_str_to_dn(domain)}"
)
search_filter = "(objectClass=pKICertificateTemplate)"
attributes = ["cn", "ntSecurityDescriptor"]
search_scope = "SUBTREE"
control = security_descriptor_control(sdflags=0x07)
if connection.search(search_base, search_filter, attributes=attributes, search_scope=search_scope, controls=control):
if len(connection.entries) == 0:
print(f"{COLORS['red']} No certificate template found")
else:
for template in connection.entries:
template_name = str(template["cn"]) if "cn" in template else ""
if enum_only_enabled and template_name not in enabled_certificates:
continue
template_enabled_in = enabled_certificates[template_name] if template_name in enabled_certificates else set()
template_security_descriptor = (
template["ntSecurityDescriptor"].raw_values[0]
if "ntSecurityDescriptor" in template
else ""
)
template_owner, template_group, template_dacl = parse_security_descriptor(template_security_descriptor)
# Resolve owner and group SIDs to usernames and add to ALL_SID
if template_owner and template_owner not in ALL_SID:
ALL_SID[template_owner] = get_sam_account_name_from_sid(connection, domain, template_owner)
if template_group and template_group not in ALL_SID:
ALL_SID[template_group] = get_sam_account_name_from_sid(connection, domain, template_group)
certificate_templates[template_name] = {
"enabled_in": template_enabled_in,
"security_descriptor": template_security_descriptor,
"owner": template_owner,
"group": template_group,
"dacl": template_dacl,
}
template_count = len(certificate_templates)
if template_count == 1 and not enum_only_enabled:
print(f"{COLORS['green']}[+] {COLORS['white']}Found 1 certificate template:")
elif template_count == 1 and enum_only_enabled:
print(f"{COLORS['green']}[+] {COLORS['white']}Found 1 enabled certificate template:")
elif template_count > 1 and not enum_only_enabled:
print(f"{COLORS['green']}[+] {COLORS['white']}Found {template_count} certificate templates:")
else:
enabled_count = len([t for t in certificate_templates.values() if t["enabled_in"]])
print(f"{COLORS['green']}[+] {COLORS['white']}Found {enabled_count} enabled certificate templates:")
if len(certificate_templates) > 0:
for template_name, template_info in certificate_templates.items():
if enum_only_enabled and not template_info["enabled_in"]:
continue
print(f"{TAB * 3}{template_name}")
check_if_vulnerable(user_sids, privileged_sids, certificate_templates)
return certificate_templates
except Exception as e:
print(f"{COLORS['red']}[-] {COLORS['white']}{e}")
return {}
def parse_security_descriptor(security_descriptor_bytes):
"""
Parse Windows security descriptor from binary data.
This function extracts the owner SID, group SID, and DACL from a
binary security descriptor. It parses the header structure and
delegates DACL parsing to a separate function.
Args:
security_descriptor_bytes (bytes): Binary security descriptor data
Returns:
tuple[str, str, list]: (owner_sid, group_sid, dacl) where dacl is [revision, ace_list]
"""
# Offsets (ignoring SACL)
owner_offset, group_offset, _, dacl_offset = struct.unpack("<LLLL", security_descriptor_bytes[4:20])
# Get owner and group SIDs
owner_sid = convert_sid_bytes_to_str(security_descriptor_bytes[owner_offset:])
group_sid = convert_sid_bytes_to_str(security_descriptor_bytes[group_offset:])
# If there is a DACL, extract info from it
if dacl_offset != 0:
dacl_bytes = security_descriptor_bytes[dacl_offset:]
acl_revision, ace_list = parse_dacl(dacl_bytes)
dacl = [acl_revision, ace_list]
return owner_sid, group_sid, dacl
def parse_dacl(dacl_bytes):
"""
Parse DACL (Discretionary Access Control List) from binary data.
This function parses the DACL structure to extract ACE (Access Control Entry)
information including ACE type, flags, access mask, and SID. It handles
both standard ACEs and object ACEs with GUIDs.
Args:
dacl_bytes (bytes): Binary DACL data
Returns:
tuple[int, list[dict]]: (acl_revision, ace_list) where ace_list contains parsed ACE dictionaries
"""
# Read first 4 bytes of the DACL to get ACL information (ignoring sbz1, ACL size, and sbz2)
acl_revision, _, _, ace_count, _ = struct.unpack("<BBHHH", dacl_bytes[:8])
# Define initial offset (first 4 bytes already read)
current_offset = 8
# Iterate over ACEs
ace_list = list()
for _ in range(ace_count):
ace = dict()
# Read ACE header
ace_type, ace_flags, ace_size = struct.unpack("<BBH", dacl_bytes[current_offset:current_offset + 4])
ace["type"] = ACE_TYPES[ace_type]
ace["flags"] = ace_flags
# Read ACE
ace_bytes = dacl_bytes[current_offset:current_offset + ace_size]
# Read next 4 bytes to get the access mask
aux_offset = 4
access_mask = struct.unpack("<L", ace_bytes[aux_offset:aux_offset + 4])[0]
ace["access_mask"] = access_mask
# Derive enabled ACE flags and rights for printing/analysis
enabled_flags = []