-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpyadrecon.py
More file actions
7448 lines (6410 loc) · 353 KB
/
pyadrecon.py
File metadata and controls
7448 lines (6410 loc) · 353 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
"""
PyADRecon - Python Active Directory Reconnaissance Tool
A Python port of ADRecon with NTLM and Kerberos authentication support.
Author: LRVT - https://github.com/l4rm4nd
License: MIT
"""
import argparse
import csv
import os
import sys
import socket
import struct
import ssl
import re
import json
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, field
from pathlib import Path
import logging
import threading
import subprocess
import tempfile
import traceback
# Third-party imports
LDAP3_AVAILABLE = False
# Default values if ldap3 not available (for --help to work)
SUBTREE = 2
BASE = 0
ALL_ATTRIBUTES = '*'
LDAPException = Exception
LDAPBindError = Exception
try:
import ldap3
from ldap3 import Server, Connection, ALL, NTLM, KERBEROS, SASL, SUBTREE, BASE, ALL_ATTRIBUTES, Tls
from ldap3.core.exceptions import LDAPException, LDAPBindError
from ldap3.utils.conv import escape_filter_chars
from ldap3.protocol.microsoft import security_descriptor_control
LDAP3_AVAILABLE = True
# Try to import ntlm-auth for workstation spoofing
try:
import ntlm_auth
NTLM_AUTH_AVAILABLE = True
except ImportError:
NTLM_AUTH_AVAILABLE = False
except ImportError:
NTLM_AUTH_AVAILABLE = False
# Check for Kerberos SASL packages
KERBEROS_AVAILABLE = False
try:
import gssapi
KERBEROS_AVAILABLE = True
except ImportError:
try:
import winkerberos
KERBEROS_AVAILABLE = True
except ImportError:
pass
try:
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.krb5.types import Principal, KerberosTime, Ticket
from impacket.krb5 import constants
from impacket.krb5.asn1 import TGS_REP, EncTGSRepPart, EncTicketPart
from impacket.krb5.ccache import CCache
from impacket.smbconnection import SMBConnection
from impacket.nmb import NetBIOSError
from impacket.ldap import ldaptypes
IMPACKET_AVAILABLE = True
except ImportError:
IMPACKET_AVAILABLE = False
print("[*] impacket not available - SMB features disabled")
# Fallback class if impacket not available
class ldaptypes:
pass
try:
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
OPENPYXL_AVAILABLE = True
except ImportError:
OPENPYXL_AVAILABLE = False
print("[*] openpyxl not available - Excel export disabled")
# Try to import dashboard generator
DASHBOARD_AVAILABLE = False
try:
from dashboard_generator import generate_dashboard
DASHBOARD_AVAILABLE = True
except ImportError:
DASHBOARD_AVAILABLE = False
if not KERBEROS_AVAILABLE:
print("[*] gssapi/winkerberos not available - Kerberos authentication disabled")
print("[*] Install with: pip install gssapi (Linux) or pip install winkerberos (Windows)")
# Constants
VERSION = "v0.13.3" # Automatically updated by CI/CD pipeline during release
BANNER = f"""
╔═════════════════════════════════════════════════════════
║ PyADRecon {VERSION} - Python AD Reconnaissance Tool
║ A Python implementation inspired by ADRecon
║ -------------------------------------------------------
║ Author: LRVT - https://github.com/l4rm4nd/PyADRecon
╚═════════════════════════════════════════════════════════
"""
# AD Constants
SAM_USER_OBJECT = 805306368
SAM_COMPUTER_OBJECT = 805306369
SAM_GROUP_OBJECT = 268435456
SAM_ALIAS_OBJECT = 536870912
# UserAccountControl flags
UAC_FLAGS = {
0x0001: "SCRIPT",
0x0002: "ACCOUNTDISABLE",
0x0008: "HOMEDIR_REQUIRED",
0x0010: "LOCKOUT",
0x0020: "PASSWD_NOTREQD",
0x0040: "PASSWD_CANT_CHANGE",
0x0080: "ENCRYPTED_TEXT_PWD_ALLOWED",
0x0100: "TEMP_DUPLICATE_ACCOUNT",
0x0200: "NORMAL_ACCOUNT",
0x0800: "INTERDOMAIN_TRUST_ACCOUNT",
0x1000: "WORKSTATION_TRUST_ACCOUNT",
0x2000: "SERVER_TRUST_ACCOUNT",
0x10000: "DONT_EXPIRE_PASSWORD",
0x20000: "MNS_LOGON_ACCOUNT",
0x40000: "SMARTCARD_REQUIRED",
0x80000: "TRUSTED_FOR_DELEGATION",
0x100000: "NOT_DELEGATED",
0x200000: "USE_DES_KEY_ONLY",
0x400000: "DONT_REQ_PREAUTH",
0x800000: "PASSWORD_EXPIRED",
0x1000000: "TRUSTED_TO_AUTH_FOR_DELEGATION",
0x4000000: "PARTIAL_SECRETS_ACCOUNT",
}
# Kerberos encryption types
KERB_ENC_FLAGS = {
0x01: "DES_CBC_CRC",
0x02: "DES_CBC_MD5",
0x04: "RC4_HMAC",
0x08: "AES128_CTS_HMAC_SHA1_96",
0x10: "AES256_CTS_HMAC_SHA1_96",
}
# Trust directions
TRUST_DIRECTION = {
0: "Disabled",
1: "Inbound",
2: "Outbound",
3: "Bidirectional",
}
# Trust types
TRUST_TYPE = {
1: "Downlevel",
2: "Uplevel",
3: "MIT",
4: "DCE",
}
# Domain functional levels
DOMAIN_FUNCTIONAL_LEVELS = {
0: "Windows2000",
1: "Windows2003Mixed",
2: "Windows2003",
3: "Windows2008",
4: "Windows2008R2",
5: "Windows2012",
6: "Windows2012R2",
7: "Windows2016",
}
# Group types
GROUP_TYPE = {
2: "Global Distribution",
4: "Domain Local Distribution",
8: "Universal Distribution",
-2147483646: "Global Security",
-2147483644: "Domain Local Security",
-2147483640: "Universal Security",
}
# Logging setup
logging.basicConfig(
level=logging.INFO,
format='[%(levelname)s] %(message)s'
)
logger = logging.getLogger('PyADRecon')
def windows_timestamp_to_datetime(timestamp: int) -> Optional[datetime]:
"""Convert Windows FILETIME to Python datetime."""
if timestamp is None or timestamp == 0 or timestamp == 9223372036854775807:
return None
try:
# Windows FILETIME is 100-nanosecond intervals since January 1, 1601
return datetime(1601, 1, 1) + timedelta(microseconds=timestamp // 10)
except (ValueError, OverflowError):
return None
def generalized_time_to_datetime(time_str: str) -> Optional[datetime]:
"""Convert LDAP Generalized Time to Python datetime."""
if not time_str:
return None
try:
# Handle various formats
if time_str.endswith('Z'):
time_str = time_str[:-1]
if '.' in time_str:
return datetime.strptime(time_str, "%Y%m%d%H%M%S.%f")
return datetime.strptime(time_str, "%Y%m%d%H%M%S")
except ValueError:
return None
def format_datetime(dt) -> str:
"""Format datetime in UTC (M/D/YYYY H:MM:SS AM/PM).
All timestamps are displayed in UTC for consistency and timezone independence.
ldap3 returns datetime objects in UTC, which we format as-is.
"""
if dt is None:
return ""
if isinstance(dt, datetime):
# Linux/macOS support %-m etc. Windows does not.
if os.name == "nt":
# Windows: %# removes leading zeros on most builds.
try:
return dt.strftime("%#m/%#d/%Y %#I:%M:%S %p")
except ValueError:
# Fallback: build without platform-specific flags
m = dt.month
d = dt.day
y = dt.year
hour12 = dt.hour % 12 or 12
ampm = "AM" if dt.hour < 12 else "PM"
return f"{m}/{d}/{y} {hour12}:{dt.minute:02d}:{dt.second:02d} {ampm}"
else:
return dt.strftime("%-m/%-d/%Y %-I:%M:%S %p")
return ""
def _extract_ldap_value(attr):
"""Extract primitive value from ldap3 Attribute object."""
# ldap3 Attribute objects have 'raw_values' attribute - use this to detect them
if hasattr(attr, 'raw_values'):
# It's an ldap3 Attribute object
return attr.value
return attr
def safe_int(val, default=0):
"""Safely convert a value to int, handling ldap3 Attribute objects."""
if val is None:
return default
# Handle ldap3 Attribute objects
if hasattr(val, 'raw_values'):
val = val.value
if val is None:
return default
try:
return int(val)
except (ValueError, TypeError):
return default
def safe_str(val, default=''):
"""Safely convert a value to string, handling ldap3 Attribute objects."""
if val is None:
return default
# Handle ldap3 Attribute objects
if hasattr(val, 'raw_values'):
val = val.value
if val is None:
return default
return str(val)
def get_attr(entry, attr_name: str, default=None):
"""Safely get attribute value from LDAP entry."""
try:
if hasattr(entry, attr_name):
attr = getattr(entry, attr_name)
if attr is not None:
# Extract value from ldap3 Attribute if needed
val = _extract_ldap_value(attr)
if val is not None:
if isinstance(val, list):
return val[0] if len(val) == 1 else val
return val
except (IndexError, KeyError, AttributeError):
pass
return default
def get_attr_list(entry, attr_name: str) -> List:
"""Get attribute as a list."""
try:
if hasattr(entry, attr_name):
attr = getattr(entry, attr_name)
if attr is not None:
# ldap3 Attribute objects have 'raw_values' attribute
if hasattr(attr, 'raw_values'):
vals = attr.values
if vals:
return list(vals)
return []
elif isinstance(attr, list):
return attr
else:
return [attr]
except (IndexError, KeyError, AttributeError):
pass
return []
def dn_to_fqdn(dn: str) -> str:
"""Convert Distinguished Name to FQDN."""
if not dn:
return ""
parts = []
for part in dn.split(','):
if part.upper().startswith('DC='):
parts.append(part[3:])
return '.'.join(parts)
def parse_uac(uac) -> Dict[str, bool]:
"""Parse UserAccountControl value into individual flags."""
if uac is None:
return {}
uac = safe_int(uac, 0)
result = {}
result['Enabled'] = not bool(uac & 0x0002)
result['PasswordNotRequired'] = bool(uac & 0x0020)
result['PasswordCantChange'] = bool(uac & 0x0040)
result['ReversibleEncryption'] = bool(uac & 0x0080)
result['PasswordNeverExpires'] = bool(uac & 0x10000)
result['SmartcardRequired'] = bool(uac & 0x40000)
result['TrustedForDelegation'] = bool(uac & 0x80000)
result['NotDelegated'] = bool(uac & 0x100000)
result['UseDESKeyOnly'] = bool(uac & 0x200000)
result['DoesNotRequirePreAuth'] = bool(uac & 0x400000)
result['PasswordExpired'] = bool(uac & 0x800000)
result['TrustedToAuthForDelegation'] = bool(uac & 0x1000000)
result['AccountLockedOut'] = bool(uac & 0x0010)
return result
def parse_kerb_enc_types(enc_types) -> Dict[str, str]:
"""Parse msDS-SupportedEncryptionTypes into individual encryption types.
If msDS-SupportedEncryptionTypes is not set (None/0), the DC uses defaults:
- Windows Server 2008+: RC4, AES128, AES256 (all supported)
- Older versions: RC4, DES (deprecated)
Returns dict with 'Supported', 'Not Supported', or 'Default' for each type.
"""
if enc_types is None or safe_int(enc_types, 0) == 0:
# Attribute not set - system uses defaults (typically all modern algorithms)
return {
'RC4': 'Default',
'AES128': 'Default',
'AES256': 'Default',
}
enc_types = safe_int(enc_types, 0)
return {
'RC4': 'Supported' if (enc_types & 0x04) else 'Not Supported',
'AES128': 'Supported' if (enc_types & 0x08) else 'Not Supported',
'AES256': 'Supported' if (enc_types & 0x10) else 'Not Supported',
}
def check_cannot_change_password(entry) -> bool:
"""
Check if user cannot change password by examining ACL.
This checks if SELF and Everyone are denied the 'Change Password' right.
Change Password GUID: ab721a53-1e2f-11d0-9819-00aa0040529b (user-Change-Password)
Access mask for ExtendedRight: 0x00000100 (ADS_RIGHT_DS_CONTROL_ACCESS)
"""
try:
# Get the security descriptor
sd_attr = None
if hasattr(entry, 'ntSecurityDescriptor'):
if hasattr(entry.ntSecurityDescriptor, 'raw_values'):
if entry.ntSecurityDescriptor.raw_values:
sd_attr = entry.ntSecurityDescriptor.raw_values[0]
if not sd_attr or not isinstance(sd_attr, bytes) or len(sd_attr) < 20:
return False
# Parse security descriptor structure
control = struct.unpack('<H', sd_attr[2:4])[0]
dacl_offset = struct.unpack('<I', sd_attr[16:20])[0]
# Check if DACL is present (SE_DACL_PRESENT = 0x0004)
if dacl_offset == 0 or (control & 0x0004) == 0:
return False
if dacl_offset >= len(sd_attr):
return False
# Parse DACL
dacl = sd_attr[dacl_offset:]
if len(dacl) < 8:
return False
# DACL header: AclRevision(1) + Sbz1(1) + AclSize(2) + AceCount(2) + Sbz2(2)
ace_count = struct.unpack('<H', dacl[4:6])[0]
# Change Password GUID (user-Change-Password extended right)
change_pwd_guid = bytes.fromhex('531a72ab2f1ed011981900aa0040529b') # Little-endian format
# Well-known SIDs in binary format
self_sid = b'\x01\x01\x00\x00\x00\x00\x00\x05\x0a\x00\x00\x00' # S-1-5-10 (SELF)
everyone_sid = b'\x01\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00' # S-1-1-0 (Everyone)
# Parse ACEs
offset = 8 # Start after DACL header
for _ in range(ace_count):
if offset + 4 > len(dacl):
break
ace_type = dacl[offset]
ace_size = struct.unpack('<H', dacl[offset+2:offset+4])[0]
if offset + ace_size > len(dacl) or ace_size < 16:
break
# Check for ACCESS_DENIED_OBJECT_ACE_TYPE (0x06) or ACCESS_DENIED_ACE_TYPE (0x01)
if ace_type == 0x06: # ACCESS_DENIED_OBJECT_ACE_TYPE
# Parse ACCESS_DENIED_OBJECT_ACE
if ace_size < 36:
offset += ace_size
continue
access_mask = struct.unpack('<I', dacl[offset+4:offset+8])[0]
flags = struct.unpack('<I', dacl[offset+8:offset+12])[0]
# Check if this ACE applies to the Change Password extended right
# ACE_OBJECT_TYPE_PRESENT = 0x1
if flags & 0x1:
object_type = dacl[offset+12:offset+28]
# Check if this is for Change Password permission
if object_type == change_pwd_guid:
# Find the SID offset
sid_offset = offset + 12 + 16
if flags & 0x2: # ACE_INHERITED_OBJECT_TYPE_PRESENT
sid_offset += 16
if sid_offset + 12 <= offset + ace_size:
sid = dacl[sid_offset:offset+ace_size]
# Check if SID is SELF or Everyone
if len(sid) >= 12:
if sid[:12] == self_sid or sid[:12] == everyone_sid:
return True
offset += ace_size
return False
except Exception as e:
# If we can't parse the security descriptor, return False
return False
def sid_to_string(sid_bytes) -> str:
"""Convert binary SID to string representation."""
if sid_bytes is None:
return ""
if isinstance(sid_bytes, str):
return sid_bytes
try:
if isinstance(sid_bytes, bytes):
revision = sid_bytes[0]
sub_auth_count = sid_bytes[1]
authority = int.from_bytes(sid_bytes[2:8], byteorder='big')
sub_auths = []
for i in range(sub_auth_count):
sub_auth = struct.unpack('<I', sid_bytes[8 + 4*i:12 + 4*i])[0]
sub_auths.append(str(sub_auth))
return f"S-{revision}-{authority}-" + '-'.join(sub_auths)
except Exception:
pass
return str(sid_bytes)
def calculate_user_stats(users_data: List[Dict], password_age_days: int = 180, dormant_days: int = 90) -> Dict[str, Any]:
"""Calculate user account statistics for the User Stats tab."""
if not users_data:
return {}
stats = {
'enabled_count': 0,
'disabled_count': 0,
'total_count': len(users_data),
'categories': {},
'password_age_days': password_age_days,
'dormant_days': dormant_days
}
# Initialize category counters with dynamic thresholds
categories = [
'Must Change Password at Logon',
'Cannot Change Password',
'Password Never Expires',
'Reversible Password Encryption',
'Smartcard Logon Required',
'Delegation Permitted',
'Kerberos DES Only',
'Kerberos RC4',
'Does Not Require Pre Auth',
f'Password Age (> {password_age_days} days)',
'Account Locked Out',
'Never Logged in',
f'Dormant (> {dormant_days} days)',
'Password Not Required',
'Unconstrained Delegation',
'SIDHistory'
]
for cat in categories:
stats['categories'][cat] = {
'enabled_count': 0,
'disabled_count': 0,
'total_count': 0
}
# Count statistics
for user in users_data:
is_enabled = user.get('Enabled', False)
if is_enabled:
stats['enabled_count'] += 1
else:
stats['disabled_count'] += 1
# Check each category
for cat in categories:
is_match = False
if cat == 'Must Change Password at Logon':
is_match = user.get('Must Change Password at Logon', False) is True
elif cat == 'Cannot Change Password':
is_match = user.get('Cannot Change Password', False) is True
elif cat == 'Password Never Expires':
is_match = user.get('Password Never Expires', False) is True
elif cat == 'Reversible Password Encryption':
is_match = user.get('Reversible Password Encryption', False) is True
elif cat == 'Smartcard Logon Required':
is_match = user.get('Smartcard Logon Required', False) is True
elif cat == 'Delegation Permitted':
is_match = user.get('Delegation Permitted', False) is True
elif cat == 'Kerberos DES Only':
is_match = user.get('Kerberos DES Only', False) is True
elif cat == 'Kerberos RC4':
is_match = bool(user.get('Kerberos RC4', ''))
elif cat == 'Does Not Require Pre Auth':
is_match = user.get('Does Not Require Pre Auth', False) is True
elif cat.startswith('Password Age (>'):
pwd_age = user.get('Password Age (days)', '')
is_match = isinstance(pwd_age, (int, float)) and pwd_age > password_age_days
elif cat == 'Account Locked Out':
is_match = user.get('Account Locked Out', False) is True
elif cat == 'Never Logged in':
is_match = user.get('Never Logged in', False) is True
elif cat.startswith('Dormant (>'):
# Check for dormant field - it might have different keys based on config
for key in user.keys():
if 'Dormant' in key:
is_match = user.get(key, False) is True
break
elif cat == 'Password Not Required':
is_match = user.get('Password Not Required', False) is True
elif cat == 'Unconstrained Delegation':
is_match = user.get('Delegation Type', '') == 'Unconstrained'
elif cat == 'SIDHistory':
is_match = bool(user.get('SIDHistory', ''))
if is_match:
stats['categories'][cat]['total_count'] += 1
if is_enabled:
stats['categories'][cat]['enabled_count'] += 1
else:
stats['categories'][cat]['disabled_count'] += 1
return stats
def calculate_computer_stats(computers_data: List[Dict], laps_data: List[Dict] = None, password_age_days: int = 30, dormant_days: int = 90) -> Dict[str, Any]:
"""Calculate computer account statistics for the Computer Stats tab."""
if not computers_data:
return {}
# Build a set of computer names that have LAPS
laps_computers = set()
if laps_data:
for laps_entry in laps_data:
hostname = laps_entry.get('Hostname', '')
stored = laps_entry.get('Stored', False)
if hostname and stored:
# Normalize hostname (remove domain suffix if present)
hostname_parts = hostname.split('.')
laps_computers.add(hostname_parts[0].lower())
stats = {
'enabled_count': 0,
'disabled_count': 0,
'total_count': len(computers_data),
'categories': {},
'password_age_days': password_age_days,
'dormant_days': dormant_days
}
# Initialize category counters with dynamic thresholds
categories = [
'Unconstrained Delegation',
'Constrained Delegation',
'SIDHistory',
f'Dormant (> {dormant_days} days)',
f'Password Age (> {password_age_days} days)',
'ms-ds-CreatorSid',
'LAPS'
]
for cat in categories:
stats['categories'][cat] = {
'enabled_count': 0,
'disabled_count': 0,
'total_count': 0
}
# Count statistics
for computer in computers_data:
is_enabled = computer.get('Enabled', False)
if is_enabled:
stats['enabled_count'] += 1
else:
stats['disabled_count'] += 1
# Check each category
for cat in categories:
is_match = False
if cat == 'Unconstrained Delegation':
is_match = computer.get('Delegation Type', '') == 'Unconstrained'
elif cat == 'Constrained Delegation':
is_match = computer.get('Delegation Type', '') == 'Constrained'
elif cat == 'SIDHistory':
is_match = bool(computer.get('SIDHistory', ''))
elif cat.startswith('Dormant (>'):
# Check for dormant field - it might have different keys based on config
for key in computer.keys():
if 'Dormant' in key:
is_match = computer.get(key, False) is True
break
elif cat.startswith('Password Age (>'):
pwd_age = computer.get('Password Age (days)', '')
is_match = isinstance(pwd_age, (int, float)) and pwd_age > password_age_days
elif cat == 'ms-ds-CreatorSid':
is_match = bool(computer.get('ms-ds-CreatorSid', ''))
elif cat == 'LAPS':
# Check if computer has LAPS by comparing hostname
hostname = computer.get('DNSHostName', '') or computer.get('Name', '')
if hostname:
hostname_parts = hostname.split('.')
is_match = hostname_parts[0].lower() in laps_computers
if is_match:
stats['categories'][cat]['total_count'] += 1
if is_enabled:
stats['categories'][cat]['enabled_count'] += 1
else:
stats['categories'][cat]['disabled_count'] += 1
return stats
@dataclass
class ADReconConfig:
"""Configuration for AD reconnaissance."""
domain_controller: str
domain: str = ""
username: str = ""
password: str = ""
auth_method: str = "ntlm" # ntlm, kerberos
use_ssl: bool = False
port: int = 389
page_size: int = 500
dormant_days: int = 90
password_age_days: int = 180
output_dir: str = ""
only_enabled: bool = False
tgt_file: str = "" # Path to TGT ccache file
tgt_base64: str = "" # Base64-encoded TGT ccache
workstation: str = "" # Spoof workstation name for NTLM (bypasses userWorkstations restrictions)
# Collection flags
collect_forest: bool = True
collect_domain: bool = True
collect_trusts: bool = True
collect_sites: bool = True
collect_subnets: bool = True
collect_schema: bool = True
collect_password_policy: bool = True
collect_fgpp: bool = True
collect_dcs: bool = True
collect_users: bool = True
collect_user_spns: bool = True
collect_groups: bool = True
collect_group_members: bool = True
collect_ous: bool = True
collect_gpos: bool = True
collect_gplinks: bool = True
collect_dns_zones: bool = True
collect_dns_records: bool = True
collect_printers: bool = True
collect_computers: bool = True
collect_computer_spns: bool = True
collect_laps: bool = True
collect_bitlocker: bool = True
collect_gmsa: bool = True
collect_dmsa: bool = True
collect_adcs: bool = True
collect_protected_groups: bool = True
collect_krbtgt: bool = True
collect_asrep_roastable: bool = True
collect_kerberoastable: bool = True
class PyADRecon:
"""Main AD Reconnaissance class."""
def __init__(self, config: ADReconConfig):
self.config = config
self.conn: Optional[Connection] = None
self.base_dn: str = ""
self.config_dn: str = ""
self.schema_dn: str = ""
self.forest_root_dn: str = ""
self.domain_sid: str = ""
self.results: Dict[str, List] = {}
self.start_time: datetime = datetime.now()
self._sid_cache: Dict[str, str] = {} # Cache for SID-to-name resolution
self.domain_sid_to_name: Dict[str, str] = {} # Mapping of domain SIDs to domain names from trusts
def connect(self) -> bool:
"""Establish LDAP connection. Try LDAPS first, fall back to LDAP if it fails."""
# Determine which protocols to try
protocols_to_try = []
if self.config.use_ssl:
# User explicitly requested SSL only
protocols_to_try = [(True, 636)]
else:
# Try LDAPS first, then fall back to LDAP
protocols_to_try = [(True, 636), (False, self.config.port)]
last_error = None
for use_ssl, port in protocols_to_try:
try:
protocol = "LDAPS" if use_ssl else "LDAP"
logger.info(f"Attempting connection via {protocol} on port {port}...")
# Configure TLS to handle channel binding issues
tls_config = None
if use_ssl:
tls_config = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
server = Server(
self.config.domain_controller,
port=port,
use_ssl=use_ssl,
tls=tls_config,
get_info=ALL
)
if self.config.auth_method.lower() == 'kerberos':
if not KERBEROS_AVAILABLE:
logger.error("Kerberos authentication requested but gssapi/winkerberos not installed")
logger.error("Install with: pip install gssapi (Linux) or pip install winkerberos (Windows)")
return False
logger.info("Using Kerberos authentication...")
# Format user principal for Kerberos
user_principal = self.config.username
if '@' not in user_principal and self.config.domain:
user_principal = f"{self.config.username}@{self.config.domain.upper()}"
# Handle TGT token input (file or base64 string)
if self.config.tgt_file or self.config.tgt_base64:
logger.info("Using provided TGT token...")
try:
import base64
ccache_data = None
if self.config.tgt_file:
logger.info(f"Loading TGT from file: {self.config.tgt_file}")
with open(self.config.tgt_file, 'rb') as f:
ccache_data = f.read()
elif self.config.tgt_base64:
logger.info("Loading TGT from base64 string...")
ccache_data = base64.b64decode(self.config.tgt_base64)
if ccache_data:
# Write to temporary ccache file
ccache_path = tempfile.NamedTemporaryFile(delete=False, prefix='krb5cc_').name
with open(ccache_path, 'wb') as f:
f.write(ccache_data)
# Set KRB5CCNAME environment variable
os.environ['KRB5CCNAME'] = ccache_path
logger.info(f"TGT loaded successfully, ccache set to: {ccache_path}")
# Verify the ticket if impacket is available
if IMPACKET_AVAILABLE:
try:
ccache = CCache.loadFile(ccache_path)
principal = ccache.principal.prettyPrint()
logger.info(f"TGT principal: {principal}")
except Exception as e:
logger.warning(f"Could not parse ccache file: {e}")
except FileNotFoundError:
logger.error(f"TGT file not found: {self.config.tgt_file}")
return False
except Exception as e:
logger.error(f"Error loading TGT: {e}")
return False
# Obtain Kerberos ticket using kinit if password provided
elif self.config.password:
if sys.platform == "win32":
# Windows does not ship kinit; rely on SSPI / existing tickets
logger.info("Windows detected: skipping kinit. Kerberos on Windows uses existing logon-session tickets (SSPI).")
logger.info("Run `klist` to verify you have a ticket. If not, log on to the domain or use `runas /netonly` and run PyADRecon from that shell.")
logger.info("Note: Kerberos requires a hostname (SPN). Use the DC hostname/FQDN instead of an IP with -dc.")
# Do not return False here; proceed to SASL bind and let it fail with a useful error if no creds/SPN
else:
logger.info(f"Obtaining Kerberos ticket for {user_principal}...")
try:
kinit_proc = subprocess.Popen(
['kinit', user_principal],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = kinit_proc.communicate(input=self.config.password + '\n', timeout=10)
if kinit_proc.returncode != 0:
logger.error(f"Failed to obtain Kerberos ticket: {stderr.strip()}")
logger.error("Make sure Kerberos is configured (/etc/krb5.conf) and KDC is reachable")
return False
logger.info("Successfully obtained Kerberos ticket")
except FileNotFoundError:
logger.error("kinit command not found. Install Kerberos client: apt install krb5-user (Debian/Ubuntu) or yum install krb5-workstation (RHEL/CentOS)")
return False
except subprocess.TimeoutExpired:
logger.error("kinit timed out. Kerberos port (88/TCP) may be blocked by firewall")
logger.error(f"Check with: nmap -p 88 {self.config.domain_controller}")
logger.error("Use NTLM authentication instead: remove --auth kerberos")
return False
except Exception as e:
logger.error(f"Error obtaining Kerberos ticket: {e}")
return False
self.conn = Connection(
server,
user=user_principal,
authentication=SASL,
sasl_mechanism=KERBEROS,
auto_bind=True,
auto_referrals=False
)
else:
# NTLM authentication
# Always patch workstation name to match Impacket behavior:
# - Empty string (default) = bypasses userWorkstations restriction
# - Specific name = spoofs that workstation
import socket
original_gethostname = socket.gethostname
socket.gethostname = lambda: self.config.workstation
if self.config.workstation:
logger.info(f"Using NTLM authentication with workstation spoofing: {self.config.workstation}")
else:
logger.info("Using NTLM authentication with empty workstation name (bypasses userWorkstations restriction)")
user = self.config.username
if '\\' not in user and '@' not in user:
if self.config.domain:
user = f"{self.config.domain}\\{user}"
try:
self.conn = Connection(
server,
user=user,
password=self.config.password,
authentication=NTLM,
auto_bind=True,
auto_referrals=False
)
finally:
# Restore original gethostname
socket.gethostname = original_gethostname
if self.conn.bound:
logger.info(f"Successfully connected via {protocol} on port {port}")
self._get_root_dse()
return True
else:
logger.warning(f"{protocol} bind failed: {self.conn.result}")
last_error = self.conn.result
except (LDAPBindError, LDAPException) as e:
error_msg = str(e)
logger.warning(f"{protocol} connection failed: {e}")
last_error = e
# Provide helpful guidance for common Kerberos errors
if self.config.auth_method.lower() == 'kerberos':
if 'No Kerberos credentials available' in error_msg or 'No credentials were supplied' in error_msg:
logger.error("No Kerberos ticket available.")
logger.error(f"Obtain a ticket first with: kinit {self.config.username}@{self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}")
logger.error("Or use NTLM authentication: remove --auth kerberos")
return False
elif 'does not specify default realm' in error_msg or 'Configuration file' in error_msg:
logger.error("Kerberos is not configured on this system.")
logger.error("Create /etc/krb5.conf with the following content:")
logger.error(f"""
[libdefaults]
default_realm = {self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}
dns_lookup_kdc = true
dns_lookup_realm = true
[realms]
{self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'} = {{
kdc = {self.config.domain_controller}
admin_server = {self.config.domain_controller}
}}
[domain_realm]
.{self.config.domain.lower() if self.config.domain else 'domain.local'} = {self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}
{self.config.domain.lower() if self.config.domain else 'domain.local'} = {self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}
""")
logger.error("\nOr use NTLM authentication: remove --auth kerberos")
return False
elif 'Cannot find KDC' in error_msg or 'Cannot contact' in error_msg:
logger.error("Cannot contact Kerberos KDC. Check network connectivity and DNS resolution.")
return False
# Continue to next protocol
continue
except Exception as e:
error_msg = str(e)
logger.warning(f"{protocol} connection error: {e}")
last_error = e
# Provide helpful guidance for common Kerberos errors
if self.config.auth_method.lower() == 'kerberos':
if 'Server not found in Kerberos database' in error_msg:
logger.error("Kerberos SPN lookup failed. Kerberos requires a hostname, not an IP address.")
logger.error(f"Use the DC hostname instead: -dc dc1.{self.config.domain.lower() if self.config.domain else 'domain.local'}")
logger.error("Or use NTLM authentication: remove --auth kerberos")
return False
elif 'No Kerberos credentials available' in error_msg or 'No credentials were supplied' in error_msg:
logger.error("No Kerberos ticket available.")
logger.error(f"Obtain a ticket first with: kinit {self.config.username}@{self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}")
logger.error("Or use NTLM authentication: remove --auth kerberos")
return False
elif 'does not specify default realm' in error_msg or 'Configuration file' in error_msg:
logger.error("Kerberos is not configured on this system.")
logger.error("Create /etc/krb5.conf with:")
logger.error(f" [libdefaults]")
logger.error(f" default_realm = {self.config.domain.upper() if self.config.domain else 'DOMAIN.LOCAL'}")
logger.error("Or use NTLM authentication: remove --auth kerberos")
return False
# Continue to next protocol
continue