-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathad-reaper.py
More file actions
executable file
·1326 lines (1138 loc) · 58.7 KB
/
Copy pathad-reaper.py
File metadata and controls
executable file
·1326 lines (1138 loc) · 58.7 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
#!/usr/bin/env python3
"""
ad-reaper.py: A comprehensive Active Directory enumeration tool.
This tool combines anonymous (null session) and authenticated enumeration techniques
to provide a broad overview of an Active Directory environment's security posture.
Default Mode (Anonymous):
Performs quick, multi-protocol enumeration targeting low-hanging fruit like
anonymous null sessions. It combines LDAP, SAMR, and SMB enumeration with
active vulnerability testing..
Authenticated Mode:
Leverages credentials to perform a deep-dive enumeration. It checks for accessible shares,
remote access pathways, and common AD misconfigurations.
"""
import sys
import os
import re
import argparse
import ipaddress
import socket
import hashlib
import tempfile
import subprocess
from pathlib import Path
from impacket.dcerpc.v5 import samr, transport, dcomrt
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.ndr import NULL
from impacket.dcerpc.v5.samr import UF_DONT_REQUIRE_PREAUTH
from impacket.dcerpc.v5.samr import DCERPCException
from impacket.dcerpc.v5.samr import UF_ACCOUNTDISABLE
from impacket.nmb import NetBIOSError
from impacket.smb3 import FILE_ATTRIBUTE_DIRECTORY
from impacket.smbconnection import SMBConnection, SessionError
from impacket.nt_errors import STATUS_LOGON_FAILURE, STATUS_ACCESS_DENIED, STATUS_USER_SESSION_DELETED
from ldap3 import Server, Connection, ANONYMOUS, NTLM, SUBTREE, BASE, ALL
from ldap3.core.exceptions import LDAPInvalidCredentialsResult, LDAPSocketOpenError
# ---- Colors ----
class Style:
RESET = '\033[0m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
CYAN = '\033[96m'
def print_info(m): print(f"[*] {m}")
def print_success(m): print(f"[+] {Style.GREEN}{m}{Style.RESET}")
def print_vuln(m): print(f"[+] {Style.RED}{m}{Style.RESET}")
def print_error(m): print(f"[!] {Style.YELLOW}{m}{Style.RESET}")
def print_fail(m): print(f"[-] {Style.RED}{m}{Style.RESET}")
def print_secure(m): print(f"[-] {Style.GREEN}{m}{Style.RESET}")
def print_section(title):
print("\n" + "="*70)
print(f" {title.upper()} ".center(70, "="))
print("="*70 + "\n")
def print_banner():
banner = rf"""
{Style.CYAN} ___ ____ ____
/ | / __ \ / __ \ ___ ____ _ ____ ___ _____
/ /| | / / / / / /_/ // _ \/ __ `// __ \/ _ \ / ___/
/ ___ |/ /_/ / / _, _// __/ /_/ // /_/ / __// /
/_/ |_/_____/ /_/ |_| \___/\__,_// .___/\___//_/
/_/ {Style.RESET}
Multi-protocol Active Directory Enumeration Tool
"""
print(banner)
# ---- Openssl Patch ----
def ensure_legacy_provider():
"""
Attempts to enable the OpenSSL legacy provider if MD4 is missing.
This may required when running in a virtual enviroment.
"""
try:
hashlib.new('md4')
return
except ValueError:
pass
if "REAPER_OPENSSL_PATCHED" in os.environ:
return
std_paths = ["/etc/ssl/openssl.cnf", "/etc/pki/tls/openssl.cnf", "/usr/lib/ssl/openssl.cnf"]
base_cnf = next((p for p in std_paths if os.path.exists(p)), None)
if not base_cnf:
return
legacy_cnf_content = f"""
.include {base_cnf}
[openssl_init]
providers = provider_sect
[provider_sect]
default = default_sect
legacy = legacy_sect
[default_sect]
activate = 1
[legacy_sect]
activate = 1
"""
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.cnf', delete=False) as tmp:
tmp.write(legacy_cnf_content)
tmp_path = tmp.name
env = os.environ.copy()
env["OPENSSL_CONF"] = tmp_path
env["REAPER_OPENSSL_PATCHED"] = "1"
result = subprocess.run([sys.executable] + sys.argv, env=env)
if os.path.exists(tmp_path):
os.remove(tmp_path)
sys.exit(result.returncode)
except Exception:
return
ensure_legacy_provider()
# ---- Helpers ----
def strip_ansi(text):
"""Remove ANSI escape sequences (colors) from string for clean logging."""
return re.sub(r'\x1B\[[0-?]*[ -/]*[@-~]', '', text)
def dn_to_dns(dn):
""" Convert LDAP DN → DNS name properly """
if not dn:
return None
parts = [p[3:] for p in dn.split(',') if p.startswith('DC=')]
return '.'.join(parts).lower() if parts else None
def parse_identity(s):
if '/' in s: return s.split('/', 1) # noqa: E701
if '\\' in s: return s.split('\\', 1) # noqa: E701
return '', s
def parse_hashes(h):
try:
lm, nt = h.split(':')
if len(lm) == 32 and len(nt) == 32:
return lm, nt
except: # noqa: E722
pass
print_error("Invalid hash format. Expected LM:NT")
sys.exit(1)
def check_port(ip, port, timeout=2):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
return s.connect_ex((ip, port)) == 0
# ---- Core enumeration functions ----
def spider_smb_share(conn, share, path='\\', max_depth=5, current_depth=0, spider_log=None):
"""Recursively lists files and directories in a given path."""
found_sensitive = False
SENSITIVE_EXTS = ('.xml', '.txt', '.ini', '.config', '.kdbx', '.toml', '.cfg', '.pdf')
def log_and_print(msg, level="info"):
if level == "vuln": print_vuln(msg) # noqa: E701
else: print(msg) # noqa: E701
if spider_log: spider_log.write(strip_ansi(msg) + '\n') # noqa: E701
if current_depth > max_depth:
return False
try:
files = conn.listPath(share, path + "*")
for f in files:
filename = f.get_longname()
if filename in ('.', '..'): continue # noqa: E701
is_dir = f.get_attributes() & FILE_ATTRIBUTE_DIRECTORY
full_path = f"{path}{filename}"
if is_dir:
log_and_print(f" > {Style.CYAN}{full_path}/{Style.RESET}")
if spider_smb_share(conn, share, full_path + "\\", max_depth, current_depth + 1, spider_log):
found_sensitive = True
else:
if filename.lower().endswith(SENSITIVE_EXTS) or 'password' in filename.lower():
log_and_print(f" > {full_path} (SENSITIVE)", "vuln")
found_sensitive = True
else:
log_and_print(f" > {full_path}")
except: # noqa: E722
pass
return found_sensitive
def check_smb_null_session(target_ip, spider_shares=False, spider_log=None):
"""
Checks for an SMB null session, lists shares, and enumerates files.
Returns True if any potentially sensitive files are found, otherwise False.
"""
found_sensitive_file = False
SHARES_TO_SKIP = ('IPC$', 'PRINT$')
def log_and_print(msg, type="info"):
if type == "success": print_success(msg) # noqa: E701
elif type == "info": print_info(msg) # noqa: E701
elif type == "error": print_error(msg) # noqa: E701
if spider_log: spider_log.write(strip_ansi(msg) + '\n') # noqa: E701
log_and_print("Checking for anonymous SMB login and share listing (port 445)...")
for user in ['', '.', 'anonymous', 'guest']: # Null session users
conn = None
try:
conn = SMBConnection(target_ip, target_ip, timeout=5)
conn.login(user, '')
log_and_print(f"SUCCESS: Anonymous SMB login (user: '{user}') is ALLOWED!", "success")
shares = conn.listShares()
log_and_print("Enumerating accessible shares...")
log_and_print(f" {Style.CYAN}{'Share Name':<20} {'Comment'}{Style.RESET}")
log_and_print(f" {'-'*20} {'-'*30}")
discovered_shares = []
for share in shares:
name = share['shi1_netname'][:-1]
print(f" {name:<20} {share['shi1_remark'][:-1]}")
discovered_shares.append(name)
log_and_print("\n Checking for read/write access on discovered shares...")
for share_name in discovered_shares:
if share_name in SHARES_TO_SKIP:
continue
access_summary = []
can_read = False
try:
conn.listPath(share_name, '\\*')
access_summary.append(f"{Style.GREEN}READ{Style.RESET}")
can_read = True
except SessionError:
access_summary.append(f"{Style.RED}NO READ{Style.RESET}")
try:
temp_file = 'ad-reaper-test.tmp'
tid, fid = conn.createFile(share_name, temp_file)
conn.closeFile(tid, fid)
conn.deleteFile(share_name, temp_file)
access_summary.append(f"{Style.RED}WRITE{Style.RESET}")
except SessionError:
access_summary.append(f"{Style.RED}NO WRITE{Style.RESET}")
log_and_print(f" -> {share_name:<15} Access: [{', '.join(access_summary)}]")
if spider_shares and can_read:
log_and_print(f"\n --- Scanning Share: {Style.CYAN}{share_name}{Style.RESET} ---")
if spider_smb_share(conn, share_name, spider_log=spider_log):
found_sensitive_file = True
return found_sensitive_file
except SessionError as e:
if e.getErrorCode() == STATUS_ACCESS_DENIED:
print_error(f"Login with user '{user}' OK, but share listing is DENIED. Trying next user...")
elif e.getErrorCode() == STATUS_LOGON_FAILURE:
pass
else:
print_error(f"SMB Error with user '{user}': {e}")
break
except (ConnectionRefusedError, NetBIOSError):
print_error(f"Error connecting to SMB on {target_ip} (Connection refused or host not found)")
return found_sensitive_file
except Exception as e:
print_error(f"An unexpected error occurred with SMB on {target_ip}: {e}")
return found_sensitive_file
finally:
if conn:
try:
conn.logoff()
except SessionError as e:
# Ignore error if the session was already deleted by the server
if e.getErrorCode() != STATUS_USER_SESSION_DELETED:
raise
except Exception:
pass
print_fail("FAILED: Anonymous SMB login is NOT allowed or no user could list shares.")
return found_sensitive_file
def query_ldap_anonymous(target_ip, output_dir=None):
"""
Attempts to bind anonymously to LDAP to retrieve the default naming context,
domain information, and enumerate users/SPNs if permitted.
"""
print_info("Anonymous LDAP bind check...")
server = Server(target_ip, get_info=ALL)
conn = None
domain_dn = None
user_list = []
spn_list = []
asrep_list = []
adcs_servers = []
try:
conn = Connection(server, authentication=ANONYMOUS, auto_bind=True)
print_success("Anonymous LDAP bind SUCCESS")
conn.search('', '(objectClass=*)', BASE, attributes=['defaultNamingContext', 'configurationNamingContext'])
if not conn.entries:
return None, [], [], [], []
domain_dn = conn.entries[0].defaultNamingContext.value
config_nc = conn.entries[0].configurationNamingContext.value if 'configurationNamingContext' in conn.entries[0] else None
domain_attrs = [
'defaultNamingContext', 'dnsHostName', 'serverName',
'domainControllerFunctionality', 'forestFunctionality',
'domainFunctionality', 'namingContexts'
]
conn.search('', '(objectClass=*)', BASE, attributes=domain_attrs)
if not conn.entries:
print_error("Could not retrieve domain info from RootDSE.")
return None, [], [], [], []
domain_info = conn.entries[0]
if 'defaultNamingContext' in domain_info:
domain_dn = domain_info.defaultNamingContext.value
print(f" - {Style.CYAN}Domain DN:{Style.RESET} {domain_dn}")
else:
print_error("Could not retrieve defaultNamingContext. Aborting LDAP enum.")
return None, [], [], [], []
for attr in domain_attrs:
if attr == 'defaultNamingContext':
continue
if attr in domain_info:
value = domain_info[attr].value
attr_formatted = ' '.join(word.capitalize() for word in attr.replace('Functionality', ' Func Level').split())
if isinstance(value, list):
print(f" - {Style.CYAN}{attr_formatted}:{Style.RESET}")
for item in value:
print(f" - {item}")
else:
print(f" - {Style.CYAN}{attr_formatted}:{Style.RESET} {value}")
raw_file = Path(output_dir) / "ldap_users_raw.txt" if output_dir else None
if raw_file and raw_file.exists():
print_info(f"Skipping LDAP user enum (Found {raw_file})")
with open(raw_file, 'r') as f:
for line in f:
parts = line.strip().split('|', 1)
if parts and parts[0].strip():
user_list.append(parts[0].strip())
else:
print_info("Querying for active, non-system user accounts...")
real_users_filter = f'(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE}))(!(sAMAccountName=HealthMailbox*)))'
conn.search(domain_dn, real_users_filter, SUBTREE, attributes=['sAMAccountName', 'description', 'userAccountControl'])
if conn.entries:
print_success("Found active users via LDAP:")
print(f"{Style.YELLOW}{'Username':<25} {'Vulnerability'}{Style.RESET}")
print(f"{'-'*25} {'-'*25}")
f_raw = open(raw_file, 'w') if raw_file else None
for entry in conn.entries:
username = entry.sAMAccountName.value
try:
uac = int(entry.userAccountControl.value) if 'userAccountControl' in entry else 0
except (ValueError, TypeError):
uac = 0
if username:
user_list.append(username)
vuln_flag = ""
if uac & UF_DONT_REQUIRE_PREAUTH:
vuln_flag = f"{Style.RED}[AS-REP]{Style.RESET}"
asrep_list.append(username)
print(f"{Style.YELLOW}{username:<25}{Style.RESET} {vuln_flag}")
if f_raw: f_raw.write(f"{username} | {entry.description.value or ''}\n") # noqa: E701
if f_raw: f_raw.close() # noqa: E701
print_info("Querying for users with Service Principal Names (SPNs)...")
spn_filter = '(&(objectClass=user)(servicePrincipalName=*)(!(sAMAccountName=krbtgt)))'
conn.search(domain_dn, spn_filter, SUBTREE, attributes=['sAMAccountName', 'servicePrincipalName'], paged_size=500) # Paged for large DCs
if conn.entries:
print_vuln("Found users with SPNs (Potential Kerberoast Targets):")
for entry in conn.entries:
username = entry.sAMAccountName.value
spns = entry.servicePrincipalName.value
spn_display = spns[0] if isinstance(spns, list) else spns
spn_list.append(spn_display)
print(f" > {Style.RED}{username:<25}{Style.RESET} SPN: {spn_display}...")
else:
print_secure("No users with SPNs found via anonymous LDAP.")
print_info("Querying for high-value Server objects...")
server_filter = '(&(objectClass=computer)(operatingSystem=*Server*))'
conn.search(domain_dn, server_filter, SUBTREE, attributes=['sAMAccountName', 'operatingSystem', 'dNSHostName'], paged_size=500)
if conn.entries:
print_success(" Found Server Objects:")
for entry in conn.entries:
name = entry.sAMAccountName.value
os = entry.operatingSystem.value or 'N/A'
dns = entry.dNSHostName.value or 'N/A'
print(f" > {Style.CYAN}{name:<20}{Style.RESET} OS: {os} ({dns})")
else:
print_info(" No Server objects found.")
if config_nc:
print_info("Checking for Certificate Authorities (ADCS) via anonymous LDAP...")
pki_base = f"CN=Public Key Services,CN=Services,{config_nc}"
conn.search(pki_base, '(objectClass=pKIEnrollmentService)', attributes=['cn', 'dNSHostName'], paged_size=500)
if conn.entries:
print_vuln("Found Certificate Authorities (ADCS) via anonymous LDAP:")
for entry in conn.entries:
ca_name = entry.cn.value
ca_dns = entry.dNSHostName.value or 'N/A'
adcs_servers.append({'name': ca_name, 'dns': ca_dns})
print(f" > {Style.RED}{ca_name:<25}{Style.RESET} Host: {ca_dns}")
conn.unbind()
return domain_dn, user_list, spn_list, asrep_list, adcs_servers
except LDAPSocketOpenError:
print_fail(f"LDAP connection failed on {target_ip}:389")
except Exception as e:
print_fail(f"Anonymous LDAP failed: {e}")
except LDAPInvalidCredentialsResult:
print_fail("FAILED: Anonymous LDAP bind is NOT allowed.")
except (ConnectionRefusedError, LDAPSocketOpenError):
print_error(f"Error connecting to LDAP on {target_ip} (Connection refused)")
except Exception as e:
print_error(f"An unexpected error occurred with LDAP on {target_ip}: {e}")
finally:
if conn:
conn.unbind()
return None, [], [], [], []
def enumerate_users_samr(target_ip, output_dir=None, domain=None):
"""
Enumerates non-junk domain users via the SAMR RPC interface.
"""
raw_file = Path(output_dir) / "samr_users_raw.txt" if output_dir else None
print_info("Enumerating all domain users via SAMR...")
all_found_users = []
for user in ['', '.']:
if all_found_users: break # noqa: E701
try:
string_binding = r'ncacn_np:%s[\pipe\samr]' % target_ip
rpc_transport = transport.DCERPCTransportFactory(string_binding)
rpc_transport.set_dport(445)
rpc_transport.set_credentials(user, '')
rpc_transport.set_connect_timeout(5.0)
print_info(f"Attempting SAMR enum with user: '{user}'")
rpc_transport.connect()
dce = rpc_transport.get_dce_rpc()
dce.bind(samr.MSRPC_UUID_SAMR)
resp = samr.hSamrConnect(dce, serverName=f'\\\\{target_ip}', desiredAccess=samr.MAXIMUM_ALLOWED)
server_handle = resp['ServerHandle']
resp = samr.hSamrEnumerateDomainsInSamServer(dce, server_handle)
domain_name = next((d['Name'] for d in resp['Buffer']['Buffer'] if d['Name'] != 'Builtin'), None)
if not domain_name:
print_error("Could not find a non-Builtin domain via SAMR.")
dce.disconnect()
continue
resp = samr.hSamrLookupDomainInSamServer(dce, server_handle, domain_name)
domain_sid = resp['DomainId']
resp = samr.hSamrOpenDomain(dce, server_handle, desiredAccess=samr.MAXIMUM_ALLOWED, domainId=domain_sid)
domain_handle = resp['DomainHandle']
resp = samr.hSamrEnumerateUsersInDomain(dce, domain_handle)
user_list = []
JUNK_PREFIXES = ('$', 'SM_', 'HealthMailbox', 'DefaultAccount', 'Guest', 'Administrator', 'krbtgt')
for user_info in resp['Buffer']['Buffer']:
username = user_info['Name']
rid = user_info['RelativeId']
if not any(username.startswith(p) for p in JUNK_PREFIXES):
user_list.append((username, rid))
dce.disconnect()
print_success(f"SUCCESS: SAMR enumeration with user '{user}' is ALLOWED!")
if user_list:
if raw_file:
with open(raw_file, 'w') as f:
for username, rid in user_list:
f.write(f"{username} | {rid}\n")
print_success(f"Found {len(user_list)} non-junk users via SAMR:")
for username, rid in user_list:
print(f"{Style.YELLOW}{username:<25}{Style.RESET} (RID: {hex(rid)})")
all_found_users = [u for u, r in user_list]
break
except (DCERPCException, SessionError) as e:
if 'STATUS_ACCESS_DENIED' in str(e):
print_error(f"Login with user '{user}' OK, but SAMR access is DENIED.")
continue
elif e.getErrorCode() != STATUS_LOGON_FAILURE:
print_error(f"SMB Error during SAMR enum: {e}")
break
except (ConnectionRefusedError, NetBIOSError):
print_error(f"Error connecting to RPC/SAMR on {target_ip}")
break
except Exception as e:
print_error(f"An unexpected error occurred with SAMR enumeration: {e}")
break
if not all_found_users:
print_fail("FAILED: Anonymous SAMR enumeration is NOT allowed.")
return all_found_users
def get_domain_from_ldap(target_ip):
"""
Performs a quick anonymous LDAP query to get the domain name.
Returns the NetBIOS domain name.
"""
print_info(f"Attempting to discover domain name from {target_ip} via anonymous LDAP...")
server = Server(target_ip, get_info=['defaultNamingContext'])
conn = None
try:
conn = Connection(server, authentication=ANONYMOUS, auto_bind=True) # noqa: F841
if server.info and server.info.other.get('defaultNamingContext'):
domain_dn = server.info.other['defaultNamingContext'][0]
netbios_name = domain_dn.split(',')[0].replace('DC=', '').upper()
print_success(f" -> Discovered domain: {netbios_name}")
return netbios_name
except (LDAPSocketOpenError, ConnectionRefusedError):
print_error(f" -> Could not connect to LDAP on {target_ip} to auto-discover domain.")
except Exception:
pass # Fail silently if anonymous bind is not allowed
return None
# ---- Authenticated Functions ----
def enumerate_smb_shares_auth(target_ip, domain, username, password, lmhash, nthash, spider_shares=False, spider_log=None):
"""Connects to SMB with credentials and lists accessible shares."""
def log_and_print(msg, type="info"):
if type == "success": print_success(msg) # noqa: E701
elif type == "info": print_info(msg) # noqa: E701
elif type == "fail": print_fail(msg) # noqa: E701
if spider_log: spider_log.write(strip_ansi(msg) + '\n') # noqa: E701
print_section("Authenticated SMB Share Enumeration")
conn = None
try:
conn = SMBConnection(target_ip, target_ip, timeout=5)
conn.login(username, password, domain, lmhash=lmhash, nthash=nthash)
log_and_print(f"SMB Auth Successful as {domain}\\{username}", "success")
shares = conn.listShares()
log_and_print(f" {Style.CYAN}{'Share Name':<20} {'Comment'}{Style.RESET}")
log_and_print(f" {'-'*20} {'-'*30}")
discovered_shares = [s['shi1_netname'][:-1] for s in shares]
for share_name in discovered_shares:
# Find the corresponding remark for printing
remark = next((s['shi1_remark'][:-1] for s in shares if s['shi1_netname'][:-1] == share_name), "")
log_and_print(f" {share_name:<20} {remark}")
# After listing, check for read/write access on all discovered shares.
log_and_print("\n Checking for read/write access on discovered shares...")
SHARES_TO_SKIP_CHECKS = ('IPC$', 'PRINT$')
for share_name in discovered_shares:
if share_name in SHARES_TO_SKIP_CHECKS:
continue
access_summary = []
can_read = False
# Test for READ access
try:
conn.listPath(share_name, '\\*')
access_summary.append(f"{Style.GREEN}READ{Style.RESET}")
can_read = True
except SessionError:
access_summary.append(f"{Style.RED}NO READ{Style.RESET}")
# Test for WRITE access
try:
# Attempt to create and immediately delete a temporary file.
temp_file = 'ad-reaper-test.tmp'
tid, fid = conn.createFile(share_name, temp_file)
conn.closeFile(tid, fid)
conn.deleteFile(share_name, temp_file)
access_summary.append(f"{Style.RED}WRITE{Style.RESET}")
except SessionError:
access_summary.append(f"{Style.RED}NO WRITE{Style.RESET}")
log_and_print(f" -> {share_name:<15} Access: [{', '.join(access_summary)}]")
if spider_shares and can_read:
log_and_print(f"\n --- Scanning Share: {Style.CYAN}{share_name}{Style.RESET} ---")
spider_smb_share(conn, share_name, spider_log=spider_log)
except SessionError as e:
if e.getErrorCode() == STATUS_LOGON_FAILURE:
log_and_print(f"SMB Login Failed: Invalid Credentials for {username}", "fail")
else:
log_and_print(f"SMB Error: {e}", "fail")
except Exception as e:
log_and_print(f"Connection Error: {e}", "fail")
finally:
if conn:
try:
conn.logoff()
except: # noqa: E722
pass
def enumerate_ldap_auth(target_ip, domain, username, password, lmhash, nthash, output_dir=None):
"""
Performs a comprehensive, authenticated LDAP enumeration.
Returns the domain's search_base, a list of the user's groups, and a
dictionary of findings (SPNs, admin users).
"""
findings = {'spns': [], 'admin_users': [], 'asrep_users': [], 'adcs_servers': []}
print_section("Authenticated LDAP Enumeration")
user_dn = f"{domain}\\{username}" if domain else username
user_groups = []
user_list = []
search_base = None
try:
server = Server(target_ip, get_info=ALL)
auth_password = f"{lmhash}:{nthash}" if lmhash and nthash else password
conn = Connection(server, user=user_dn, password=auth_password, authentication=NTLM, auto_bind=True)
print_success(f"LDAP Bind Successful as {user_dn}")
if server.info and server.info.other.get('defaultNamingContext'):
search_base = server.info.other['defaultNamingContext'][0]
print_info(f"Target Domain: {search_base}")
else:
print_fail("Could not determine DefaultNamingContext.")
return None, [], findings, []
print_info(f"Querying groups for user '{username}'...")
conn.search(search_base, f'(sAMAccountName={username})', attributes=['memberOf', 'primaryGroupID', 'msDS-AllowedToDelegateTo'])
if conn.entries:
entry = conn.entries[0]
primary_group_id = entry.primaryGroupID.value if 'primaryGroupID' in entry else None
if 'memberOf' in entry:
print(f" {Style.YELLOW}Group Memberships:{Style.RESET}")
for group in entry.memberOf:
cn = str(group).split(',')[0].replace('CN=', '').lower()
print(f" - {cn}")
user_groups.append(cn)
if primary_group_id:
conn.search(search_base, f'(primaryGroupToken={primary_group_id})', attributes=['sAMAccountName'])
if conn.entries:
primary_group_name = conn.entries[0].sAMAccountName.value.lower()
if primary_group_name not in user_groups:
print(f" - {primary_group_name} (Primary Group)")
user_groups.append(primary_group_name)
if 'msDS-AllowedToDelegateTo' in entry and entry['msDS-AllowedToDelegateTo']:
print_vuln(f" User '{username}' has Explicit Delegation rights (msDS-AllowedToDelegateTo):")
for target in entry['msDS-AllowedToDelegateTo']:
print(f" - {target}")
print_info("Checking for Deleted Objects (Tombstoned)...")
try:
# LDAP_SERVER_SHOW_DELETED_OID = '1.2.840.113556.1.4.417'
del_base = f"CN=Deleted Objects,{search_base}"
conn.search(
del_base,
'(isDeleted=TRUE)',
search_scope=SUBTREE,
attributes=['sAMAccountName', 'lastKnownParent', 'objectClass'],
controls=[('1.2.840.113556.1.4.417', True, None)]
)
res = conn.result
if res['result'] == 0:
if conn.entries:
# Exclude only the base container DN to get the actual deleted items
deleted_items = [e for e in conn.entries if e.entry_dn.lower() != del_base.lower()]
if deleted_items:
print_success(f" -> Found {len(deleted_items)} deleted objects!")
for entry in deleted_items:
u_name = entry.sAMAccountName.value if 'sAMAccountName' in entry and entry.sAMAccountName.value else None
if not u_name:
u_name = entry.entry_dn.split(',')[0].replace('CN=', '').split('\x00')[0]
o_type = entry.objectClass.value[-1] if 'objectClass' in entry else 'Object'
parent = entry.lastKnownParent.value if 'lastKnownParent' in entry and entry.lastKnownParent.value else 'N/A'
print(f" - {Style.YELLOW}{str(u_name):<25}{Style.RESET} ({o_type}) (Original Parent: {parent})")
else:
print_info(" -> No deleted objects found.")
elif res['result'] == 50:
print_error(" -> Not authorized to query the Deleted Objects container.")
elif res['result'] == 32:
print_info(" -> Deleted Objects container not found (Recycle Bin likely disabled).")
except Exception as e:
print_error(f" -> Error querying deleted objects: {e}")
raw_file = Path(output_dir) / "ldap_users_raw.txt" if output_dir else None
existing_users = set()
if raw_file and raw_file.exists():
print_info(f"Loading existing users from {raw_file}...")
with open(raw_file, 'r') as f:
for line in f:
parts = line.strip().split('|', 1)
if parts and parts[0].strip():
u = parts[0].strip()
existing_users.add(u)
user_list.append(u)
print_info("Querying for active, non-system user accounts...")
real_users_filter = f'(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE}))(!(sAMAccountName=HealthMailbox*)))'
conn.search(search_base, real_users_filter, search_scope=SUBTREE, attributes=['sAMAccountName', 'description', 'userAccountControl'], size_limit=0)
if conn.entries:
new_users_found = False
f_raw = open(raw_file, 'a') if raw_file else None
for entry in conn.entries:
u_name = entry.sAMAccountName.value
desc = entry.description.value or 'N/A'
if u_name:
# Check for AS-REP Vulnerability (DONT_REQ_PREAUTH bit)
try:
uac = int(entry.userAccountControl.value) if 'userAccountControl' in entry else 0
except (ValueError, TypeError):
uac = 0
if uac & UF_DONT_REQUIRE_PREAUTH:
findings['asrep_users'].append(u_name)
if u_name not in existing_users:
if not new_users_found:
print_success("Found NEW active users via authenticated LDAP:")
print(f"{Style.YELLOW}{'Username':<25} {'Description'}{Style.RESET}")
print(f"{'-'*25} {'-'*40}")
new_users_found = True
print(f"{Style.YELLOW}{u_name:<25}{Style.RESET} {desc}")
user_list.append(u_name)
existing_users.add(u_name)
if f_raw: f_raw.write(f"{u_name} | {desc}\n") # noqa: E701
if f_raw: f_raw.close() # noqa: E701
if not new_users_found:
if existing_users:
print_info(" No new users found (synced with existing dump).")
else:
print_info(" No active users found with this filter.")
else:
print_info(" No active users found with this filter.")
if findings['asrep_users']:
print_vuln(f" Found {len(findings['asrep_users'])} users with 'Do Not Require Pre-auth' set (AS-REP Roastable):")
for u in findings['asrep_users']:
print(f" > {Style.RED}{u}{Style.RESET}")
print_info("Querying for high-value Server objects...")
server_filter = '(&(objectClass=computer)(operatingSystem=*Server*))'
conn.search(search_base, server_filter, search_scope=SUBTREE, attributes=['sAMAccountName', 'operatingSystem', 'dNSHostName'])
if conn.entries:
print_success(" Found Server Objects:")
for entry in conn.entries:
name = entry.sAMAccountName.value
os = entry.operatingSystem.value or 'N/A'
dns = entry.dNSHostName.value or 'N/A'
print(f" > {Style.CYAN}{name:<20}{Style.RESET} OS: {os} ({dns})")
else:
print_info(" No Server objects found.")
print_info("Scanning for Service Principal Names (SPNs)...")
spn_filter = '(&(objectClass=user)(servicePrincipalName=*)(!(sAMAccountName=krbtgt)))'
conn.search(search_base, spn_filter, attributes=['sAMAccountName', 'servicePrincipalName'])
if conn.entries:
print_success(" Found user accounts with SPNs (Potential Kerberoast Targets):")
spn_users = [] # Collect users for roasting
for entry in conn.entries:
u = entry.sAMAccountName.value
spn_val = entry.servicePrincipalName.value
if isinstance(spn_val, list):
spn_val = spn_val[0]
if not u.endswith('$'):
findings['spns'].append({'user': u, 'spn': spn_val})
spn_users.append(u)
print(f" > {Style.YELLOW}{u:<20}{Style.RESET} (SPN: {spn_val})")
else:
print(f" > {Style.CYAN}{u:<20}{Style.RESET} (SPN: {spn_val}) [Machine Account]")
else:
print_secure(" No user accounts with SPNs found.")
print_info("Querying for privileged accounts (adminCount=1)...")
conn.search(search_base, '(&(objectClass=user)(adminCount=1))', attributes=['sAMAccountName'])
if conn.entries:
print_success(" -> Found accounts with adminCount=1 (High-Value Targets):")
for entry in conn.entries:
if 'sAMAccountName' in entry:
findings['admin_users'].append(entry.sAMAccountName.value)
print(f" - {Style.YELLOW}{entry.sAMAccountName.value}{Style.RESET}")
if server.info and server.info.other.get('configurationNamingContext'):
config_nc = server.info.other['configurationNamingContext'][0]
print_info("Querying for Certificate Authorities (ADCS) in Configuration NC...")
pki_base = f"CN=Public Key Services,CN=Services,{config_nc}"
conn.search(pki_base, '(objectClass=pKIEnrollmentService)', attributes=['cn', 'dNSHostName'])
if conn.entries:
print_success(f" -> Found {len(conn.entries)} Certificate Authorities:")
for entry in conn.entries:
ca_name = entry.cn.value
ca_dns = entry.dNSHostName.value or 'N/A'
findings['adcs_servers'].append({'name': ca_name, 'dns': ca_dns})
print(f" - {Style.YELLOW}{ca_name:<25}{Style.RESET} Host: {ca_dns}")
conn.unbind()
return search_base, user_groups, findings, user_list
except LDAPSocketOpenError:
print_fail(f"Could not connect to LDAP port 389 on {target_ip}")
except Exception as e:
print_fail(f"LDAP Error: {e}")
return search_base, user_groups, findings, user_list
def find_ad_misconfigs_auth(target_ip, domain, username, password, lmhash, nthash, search_base):
"""
Checks for common, high-impact misconfigurations via authenticated LDAP.
Returns a dictionary of findings (unconstrained delegation, LAPS).
"""
if not search_base:
print_info("Skipping misconfig check (no search_base)")
return {}
findings = {'unconstrained_delegation': [], 'constrained_delegation': [], 'laps_readable': []}
print_section("AD Misconfiguration Check")
user_dn = f"{domain}\\{username}" if domain else username
try:
server = Server(target_ip, get_info=ALL)
conn = Connection(server, user=user_dn, password=password if password else None, authentication=NTLM, auto_bind=True)
# Unconstrained Delegation Check
print_info("Checking for accounts with Unconstrained Delegation...")
delegation_filter = '(userAccountControl:1.2.840.113556.1.4.803:=524288)'
conn.search(search_base, delegation_filter, attributes=['sAMAccountName', 'objectClass'], paged_size=500) # Paged
if not conn.entries:
print_secure(" -> No accounts with Unconstrained Delegation found.")
else:
for entry in conn.entries:
obj_type = "User"
if 'computer' in [x.lower() for x in entry.objectClass.value]:
obj_type = "Computer"
print_vuln(f" -> VULNERABLE: {entry.sAMAccountName.value} ({obj_type}) has Unconstrained Delegation!")
findings['unconstrained_delegation'].append(entry.sAMAccountName.value)
# Constrained Delegation Check
print_info("Checking for Users with Constrained Delegation (Outbound Control)...")
# Filter for standard users (excluding computers) with constrained delegation configured
constrained_filter = '(&(objectClass=user)(!(objectClass=computer))(msDS-AllowedToDelegateTo=*))'
conn.search(search_base, constrained_filter, attributes=['sAMAccountName', 'msDS-AllowedToDelegateTo'], paged_size=500)
if conn.entries:
for entry in conn.entries:
u_name = entry.sAMAccountName.value
targets = entry['msDS-AllowedToDelegateTo'].value
targets_str = ", ".join(targets) if isinstance(targets, list) else str(targets)
print_vuln(f" -> VULNERABLE: User '{u_name}' has Constrained Delegation to: {targets_str}")
findings['constrained_delegation'].append({'user': u_name, 'targets': targets})
else:
print_secure(" -> No standard users found with Constrained Delegation.")
# LAPS Check
print_info("Checking for readable LAPS passwords...")
found_laps = False
# Legacy LAPS Check
try:
conn.search(
search_base,
'(ms-Mcs-AdmPwd=*)', # presence filter
attributes=['sAMAccountName', 'ms-Mcs-AdmPwd'],
paged_size=500
)
for entry in conn.entries:
if 'ms-Mcs-AdmPwd' in entry:
laps_pw = entry['ms-Mcs-AdmPwd']
if laps_pw.value:
print_vuln(f" -> VULNERABLE: Can read LAPS password for {entry.sAMAccountName.value}: {laps_pw.value}")
found_laps = True
if entry.sAMAccountName.value not in findings['laps_readable']:
findings['laps_readable'].append(entry.sAMAccountName.value)
except Exception as e:
err = str(e).lower()
if 'invalid attribute type' in err or 'no such attribute' in err or 'undefined attribute type' in err:
print_info(" -> Legacy LAPS attribute (ms-Mcs-AdmPwd) not present in schema — skipping")
else:
print_error(f" -> Legacy LAPS check failed: {str(e).splitlines()[0]}")
# Modern LAPS Check
try:
conn.search(
search_base,
'(msLAPS-Password=*)',
attributes=['sAMAccountName', 'msLAPS-Password'],
paged_size=500
)
for entry in conn.entries:
laps_pw = entry.get('msLAPS-Password')
if laps_pw and laps_pw.value:
print_vuln(f" -> VULNERABLE: Can read LAPS password for {entry.sAMAccountName.value}: {laps_pw.value}")
found_laps = True
if entry.sAMAccountName.value not in findings['laps_readable']:
findings['laps_readable'].append(entry.sAMAccountName.value)
except Exception as e:
err = str(e).lower()
if 'invalid attribute type' in err or 'no such attribute' in err or 'undefined attribute type' in err:
print_info(" -> Modern LAPS attributes (msLAPS-*) not present in schema (legacy environment) — skipping")
else:
print_error(f" -> Modern LAPS check failed: {str(e).splitlines()[0]}")
if not found_laps:
print_secure(" -> No readable LAPS passwords found.")
else:
pass
conn.unbind()
except Exception as e:
if 'invalid attribute type' in str(e):
print_fail(" -> LAPS attributes not found in schema (legacy env?)")
else:
print_error(f"Misconfig check failed: {e}")
return findings
def check_access_paths_auth(target_ip, user_groups, username, password, lmhash, nthash, domain):
"""Checks for RDP, WinRM, and WMI access with credentials."""
print_section("Remote Access Check")
# Port checks
for port, name in [(5985, "WinRM"), (3389, "RDP"), (135, "WMI/RPC"), (1433, "MSSQL")]:
status = f"{Style.GREEN}OPEN{Style.RESET}" if check_port(target_ip, port) else f"{Style.RED}CLOSED{Style.RESET}"
print(f" > {name} ({port}): {status}")
# WMI Access Check
if check_port(target_ip, 135):
print_info(" -> Port 135 is open, attempting WMI authentication...")
dcom = None
try:
dcom = dcomrt.DCOMConnection(target_ip, username, password, domain, lmhash, nthash, oxidResolver=True)
iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)
iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)
iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)
print_success(" -> WMI Access is CONFIRMED (wmiexec.py should work)")
iWbemLevel1Login.RemRelease()
except Exception as e:
if "rpc_s_access_denied" in str(e).lower() or "access denied" in str(e).lower():
print_error(" -> WMI Access DENIED (Creds rejected)")
else:
print_error(f" -> WMI Auth check failed: {e}")
finally:
if dcom:
try:
# DCOM disconnect is crucial to stop background threads
dcom.disconnect()
except: # noqa: E722
pass
# Group correlation
flat_groups = [g.lower() for g in user_groups]
if check_port(target_ip, 5985) and any(x in flat_groups for x in ['remote management users', 'administrators']):
print_success(" -> WinRM Access LIKELY (Group Membership Match)")
if check_port(target_ip, 3389) and any(x in flat_groups for x in ['remote desktop users', 'administrators']):
print_success(" -> RDP Access LIKELY (Group Membership Match)")
# --- Post-Scan Suggestions ---
def print_suggestions(target_ip, findings, auth_creds=None):
"""Prints a list of suggested follow-up commands based on scan findings."""
print_section("Actionable Suggestions")
# Use a flag to check if any suggestions were printed
suggestions_made = False
domain = findings.get('domain_name', 'lab.local')
adcs_servers = findings.get('adcs_servers', [])
if adcs_servers:
print(f"{Style.YELLOW}[!] Active Directory Certificate Services (ADCS) Found:{Style.RESET}")
ca_info = adcs_servers[0]
print(f" CA '{ca_info['name']}' is running on {ca_info['dns']}.")
print(" You should enumerate it for misconfigurations (e.g., ESC1, ESC8) using Certipy.")