-
Notifications
You must be signed in to change notification settings - Fork 66
/
keimpx.py
executable file
·1036 lines (783 loc) · 32.9 KB
/
keimpx.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 python
# -*- coding: iso-8859-15 -*-
# -*- Mode: python -*-
'''
keimpx is an open source tool, released under the Apache
License 2.0. It is developed in Python using SecureAuth Corporations's
Impacket library, https://github.com/SecureAuthCorp/impacket.
It can be used to quickly check for the usefulness of credentials across a
network over SMB.
Homepage: https://nccgroup.github.io/keimpx/
Usage: https://github.com/nccgroup/keimpx#usage
Examples: https://github.com/nccgroup/keimpx/wiki/Examples
Frequently Asked Questions: https://github.com/nccgroup/keimpx/wiki/FAQ
Contributors: https://github.com/nccgroup/keimpx#contributors
License:
Copyright 2009-2020 Bernardo Damele A. G. [email protected]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
'''
from __future__ import print_function
__author__ = 'Bernardo Damele A. G. <[email protected]>'
__version__ = '0.5.1-rc'
import binascii
import os
import re
import socket
import sys
import threading
import warnings
from optparse import OptionError, OptionParser
from threading import Thread
from six.moves import input as input
from six.moves import range as range
from lib.common import remove_comments, set_verbosity, read_input
from lib.exceptions import keimpxError, credentialsError, targetError
from lib.interactiveshell import InteractiveShell
from lib.logger import logger
from lib.smbshell import SMBShell
try:
import pyreadline as readline
have_readline = True
except ImportError:
try:
import readline
have_readline = True
except ImportError:
have_readline = False
try:
from impacket.nmb import NetBIOSTimeout
from impacket.dcerpc.v5 import rpcrt
from impacket.dcerpc.v5 import scmr
from impacket.dcerpc.v5 import transport
from impacket.smbconnection import SMBConnection, SessionError
except ImportError:
sys.stderr.write('keimpx: Impacket import error')
sys.stderr.write(
'keimpx: Impacket by SecureAuth Corporation is required for this tool to work. Please download it using:'
'\npip: pip install -r requirements.txt\nOr through your package manager:\npython-impacket.')
sys.exit(255)
# Python 2: unicode is a built-in; Python 3: unicode built-in replaced by str
try:
unicode
except NameError:
unicode = str
conf = {}
pool_thread = None
successes = 0
stop_threads = [False]
if hasattr(sys, 'frozen'):
keimpx_path = os.path.dirname(unicode(sys.executable))
else:
keimpx_path = os.path.dirname(os.path.realpath(__file__))
class test_login(Thread):
def __init__(self, target):
Thread.__init__(self)
self.__target = target
self.__credentials = self.__target.get_credentials()
self.__domains = self.__target.get_domains()
self.__dstip = self.__target.get_host()
self.__dstport = self.__target.get_port()
self.__target_id = self.__target.get_identity()
self.__destfile = '*SMBSERVER' if self.__dstport == 139 else self.__dstip
self.__srcfile = conf.name
self.__timeout = 3
def connect(self):
self.smb = SMBConnection(self.__destfile, self.__dstip, self.__srcfile, self.__dstport, self.__timeout)
def login(self, user, password, lmhash, nthash, domain):
self.smb.login(user, password, domain, lmhash, nthash)
def logoff(self):
self.smb.logoff()
def check_admin(self):
try:
self.__trans = transport.SMBTransport(remoteName=self.__dstip, dstport=self.__dstport, filename='svcctl',
smb_connection=self.smb, remote_host=self.__dstip)
self.__trans.connect()
self.__dce = self.__trans.get_dce_rpc()
self.__dce.bind(scmr.MSRPC_UUID_SCMR)
self.__resp = scmr.hROpenSCManagerW(self.__dce, dwDesiredAccess=scmr.SC_MANAGER_CREATE_SERVICE)
self.__mgr_handle = self.__resp['lpScHandle']
scmr.hRCloseServiceHandle(self.__dce, self.__mgr_handle)
self.__dce.disconnect()
return True
except rpcrt.DCERPCException as e:
pass
except Exception as e:
logger.error('Check admin error: %s' % str(e))
return False
def run(self):
global pool_thread
global successes
try:
logger.info('Assessing host %s' % self.__target_id)
for credential in self.__credentials:
user, password, lmhash, nthash = credential.get_credential()
password_str = None
if password != '' or (password == '' and lmhash == '' and nthash == ''):
password_str = password or 'BLANK'
elif lmhash != '' and nthash != '':
password_str = '%s:%s' % (lmhash, nthash)
for domain in self.__domains:
if stop_threads[0]:
break
status = False
error_code = None
is_admin = None
if domain:
user_str = '%s\\%s' % (domain, user)
else:
user_str = user
try:
self.connect()
self.login(user, password, lmhash, nthash, domain)
if self.smb.isGuestSession() > 0:
logger.warn(
'%s allows guest sessions with any credentials, skipping further login attempts'
% self.__target_id)
return
else:
credential.is_admin = self.check_admin()
if (self.smb.getServerDomain().upper() != domain.upper()
and self.smb.getServerName().upper() != domain.upper()):
domain = ''
user_str = user
credential.domain = domain
logger.info('Successful login for %s with %s on %s %s'
% (user_str, password_str, self.__target_id,
"(admin user)" if is_admin else ""))
self.logoff()
status = True
successes += 1
credential.is_valid = True
except SessionError as e:
logger.debug('Failed login for %s with %s on %s %s' % (
user_str, password_str, self.__target_id, e.getErrorString()))
error_code = e.getErrorCode()
if e.getErrorString()[0] == "STATUS_PASSWORD_MUST_CHANGE":
credential.is_valid = True
credential.password_change_required = True
status = True
elif e.getErrorString()[0] == "STATUS_ACCOUNT_LOCKED_OUT":
credential.is_valid = True
credential.is_locked_out = True
status = True
elif e.getErrorString()[0] == "STATUS_ACCOUNT_DISABLED":
credential.is_valid = True
credential.account_disabled = True
status = True
elif e.getErrorString()[0] == "STATUS_INVALID_LOGON_HOURS":
credential.is_valid = True
credential.outside_logon_hours = True
status = True
else:
credential.is_valid = False
if status is True:
break
logger.info('Assessment on host %s finished' % self.__target.get_identity())
except (socket.error, socket.herror, socket.gaierror, socket.timeout, NetBIOSTimeout) as e:
if not stop_threads[0]:
logger.warn('Connection to host %s failed (%s)' % (self.__target.get_identity(), str(e)))
self.__target.update_credentials(self.__credentials)
pool_thread.release()
class Credential:
def __init__(self, user, password='', lmhash='', nthash='', domain='', account_status='', is_admin=False,
is_locked_out=False, password_change_required=False, account_disabled=False,
outside_logon_hours=False, is_valid=False):
self.user = user
self.password = password
self.lmhash = lmhash
self.nthash = nthash
self.domain = domain
self.is_admin = is_admin
self.account_status = account_status
self.is_locked_out = is_locked_out
self.password_change_required = password_change_required
self.account_disabled = account_disabled
self.outside_logon_hours = outside_logon_hours
self.is_valid = is_valid
def get_user(self):
return self.user
def get_password(self):
return self.password
def get_domain(self):
return self.domain
def get_lm_hash(self):
return self.lmhash
def get_nt_hash(self):
return self.nthash
def get_is_admin(self):
return self.is_admin
def get_account_status(self):
return self.account_status
def get_is_locked_out(self):
return self.is_locked_out
def get_password_change_required(self):
return self.password_change_required
def get_is_valid(self):
return self.is_valid
def get_identity(self, account_details=True):
identity = ""
if self.lmhash != '' and self.nthash != '':
if self.domain != '':
identity = '%s\\%s/%s:%s' % (self.domain, self.user, self.lmhash, self.nthash)
else:
identity = '%s/%s:%s' % (self.user, self.lmhash, self.nthash)
else:
if self.domain != '':
identity = '%s\\%s/%s' % (self.domain, self.user, self.password or 'BLANK')
else:
identity = '%s/%s' % (self.user, self.password or 'BLANK')
if self.is_admin and account_details:
identity += " (Administrator)"
if self.is_locked_out and account_details:
identity += " (Locked out)"
if self.account_disabled and account_details:
identity += " (Account disabled)"
if self.password_change_required and account_details:
identity += " (Password change required)"
if self.outside_logon_hours and account_details:
identity += " (Outside logon hours)"
return identity
def get_credential(self):
if self.lmhash != '' and self.nthash != '':
return self.user, self.password, self.lmhash, self.nthash
else:
return self.user, self.password, '', ''
class Target:
def __init__(self, host, port):
self.host = host
self.port = int(port)
self.credentials = []
self.domains = []
def get_host(self):
return self.host
def get_port(self):
return self.port
def get_identity(self):
return '%s:%d' % (self.host, self.port)
def add_credential(self, credential):
self.credentials.append(credential)
def update_credentials(self, credentials):
self.credentials = None
self.credentials = credentials
def update_domains(self, domains):
self.domains = domains
def get_domains(self):
return self.domains
def get_credentials(self):
return self.credentials
def get_valid_credentials(self):
valid_credentials = []
for credential in self.credentials:
if credential.get_is_valid() is True:
valid_credentials.append(credential)
return valid_credentials
def add_command(cmd):
# if cmd is not None and len(cmd) > 0 and cmd not in commands:
if cmd is not None and len(cmd) > 0:
return cmd
def parse_list_file(filename):
commands = []
try:
fp = open(filename, 'r')
file_lines = fp.read().splitlines()
fp.close()
except IOError as _:
logger.error('Could not open commands file %s' % filename)
return
file_lines = remove_comments(file_lines)
for line in file_lines:
commands.append(add_command(line))
return commands
def get_admin_credentials(target):
valid_credentials = target.get_valid_credentials()
admin_credentials = []
for credential in valid_credentials:
if credential.get_is_admin() is True:
admin_credentials.append(credential)
if len(admin_credentials) > 0:
return admin_credentials
else:
return False
def os_cmd_list(targets):
commands = parse_list_file(conf.oscmdlist)
targets_tuple = ()
for target in targets:
admin_credentials = None
if len(target.get_valid_credentials()) == 0:
continue
else:
admin_credentials = get_admin_credentials(target)
if admin_credentials is False:
admin_credentials = target.get_valid_credentials()[0]
logger.warn('No admin user identified for target %s, some commands will not work' % target.get_identity())
logger.info('Executing OS commands on %s with user %s' % (target.get_identity(), admin_credentials.getUser()))
smb_shell = SMBShell(target, admin_credentials, conf.name)
if len(commands) > 0:
logger.info('Executing OS commands from provided file')
for command in commands:
print('OS command \'%s\' output:' % command)
try:
smb_shell.svcexec(command, 'SHARE')
except SessionError as e:
# traceback.print_exc()
logger.error('SMB error: %s' % (e.getErrorString(),))
except NetBIOSTimeout as e:
logger.error('SMB connection timed out')
except keimpxError as e:
logger.error(e)
except KeyboardInterrupt as _:
print()
logger.info('User aborted')
exit()
except Exception as e:
# traceback.print_exc()
logger.error(str(e))
print('----------8<----------')
def smb_cmd_list(targets):
commands = parse_list_file(conf.smbcmdlist)
targets_tuple = ()
for target in targets:
if len(target.get_valid_credentials()) == 0:
continue
else:
admin_credentials = get_admin_credentials(target)
if admin_credentials is False:
admin_credentials = target.get_valid_credentials()[0]
logger.warn('No admin user identified for target %s, some commands will not work' % target.get_identity())
logger.info('Executing SMB commands on %s with user %s' % (target.get_identity(), admin_credentials.getUser()))
shell = InteractiveShell(target, admin_credentials, conf.name)
if len(commands) > 0:
logger.info('Executing SMB commands from provided file')
for command in commands:
print('SMB command \'%s\' output:' % command)
try:
shell.onecmd(command)
except SessionError as e:
# traceback.print_exc()
logger.error('SMB error: %s' % (e.getErrorString(),))
except NetBIOSTimeout as e:
logger.error('SMB connection timed out')
except keimpxError as e:
logger.error(e)
except KeyboardInterrupt as _:
print()
logger.info('User aborted')
shell.do_exit('')
except Exception as e:
# traceback.print_exc()
logger.error(str(e))
print('----------8<----------')
###############
# Set domains #
###############
def parse_domains_file(filename):
parsed_domains = []
try:
fp = open(filename, 'r')
file_lines = fp.read().splitlines()
fp.close()
except IOError as _:
logger.error('Could not open domains file %s' % filename)
return
file_lines = remove_comments(file_lines)
for line in file_lines:
added_domains = add_domain(line)
for domain in added_domains:
parsed_domains.append(domain)
return parsed_domains
def add_domain(line):
added_domains = []
_ = str(line).replace(' ', '').split(',')
for d in _:
d = d.upper().split('.')[0]
added_domains.append(d)
logger.debug('Parsed domain%s: %s' % ('(s)' if len(_) > 1 else '', ', '.join([d for d in _])))
return added_domains
def set_domains():
domains = ['']
logger.info('Loading domains')
if conf.domain is not None:
logger.debug('Loading domains from command line')
added_domains = add_domain(conf.domain)
for domain in added_domains:
domains.append(domain)
if conf.domainsfile is not None:
logger.debug('Loading domains from file %s' % conf.domainsfile)
parsed_domains = parse_domains_file(conf.domainsfile)
for domain in parsed_domains:
if domain is not None:
domains.append(domain)
unique_domains = []
for domain in domains:
if domain not in unique_domains:
unique_domains.append(domain)
if len(unique_domains) == 0:
return domains
elif len(domains) > 0:
return unique_domains
###################
# Set credentials #
###################
def parse_credentials_file(filename):
parsed_credentials = []
try:
fp = open(filename, 'r')
file_lines = fp.read().splitlines()
fp.close()
except IOError as _:
logger.error('Could not open credentials file %s' % filename)
return
file_lines = remove_comments(file_lines)
for line in file_lines:
parsed_credentials.append(add_credentials(line=line))
if len(parsed_credentials) > 0:
return parsed_credentials
else:
return False
def parse_credentials(credentials_line):
credentials_line = credentials_line.replace('NO PASSWORD*********************', '00000000000000000000000000000000')
fgdumpmatch = re.compile(r'^(\S+?):(.*?:?)([0-9a-fA-F]{32}):([0-9a-fA-F]{32}):.*?:.*?:\s*$')
fgdump = fgdumpmatch.match(credentials_line)
wcematch = re.compile(r'^(\S+?):.*?:([0-9a-fA-F]{32}):([0-9a-fA-F]{32})\s*$')
wce = wcematch.match(credentials_line)
cainmatch = re.compile(r'^(\S+?):.*?:.*?:([0-9a-fA-F]{32}):([0-9a-fA-F]{32})\s*$')
cain = cainmatch.match(credentials_line)
plaintextpassmatch = re.compile(r'^(\S+?)\s+(\S*?)$')
plain = plaintextpassmatch.match(credentials_line)
# Credentials with hashes (pwdump/pwdumpx/fgdump/pass-the-hash output format)
if fgdump:
try:
binascii.a2b_hex(fgdump.group(3))
binascii.a2b_hex(fgdump.group(4))
return fgdump.group(1), '', fgdump.group(3), fgdump.group(4)
except Exception as _:
raise credentialsError('credentials error')
# Credentials with hashes (wce output format)
elif wce:
try:
binascii.a2b_hex(wce.group(2))
binascii.a2b_hex(wce.group(3))
return wce.group(1), '', wce.group(2), wce.group(3)
except Exception as _:
raise credentialsError('credentials error')
# Credentials with hashes (cain/l0phtcrack output format)
elif cain:
try:
binascii.a2b_hex(cain.group(2))
binascii.a2b_hex(cain.group(3))
return cain.group(1), '', cain.group(2), cain.group(3)
except Exception as _:
raise credentialsError('credentials error')
# Credentials with password (added by user manually divided by a space)
elif plain:
return plain.group(1), plain.group(2), '', ''
else:
raise credentialsError('credentials error')
def add_credentials(user=None, password='', lmhash='', nthash='', domain='', line=None):
if line is not None:
try:
user, password, lmhash, nthash = parse_credentials(line)
if user.count('\\') == 1:
_, user = user.split('\\')
domain = _
except credentialsError as _:
logger.warn('Bad line in credentials file %s: %s' % (conf.credsfile, line))
return
if user is not None:
credential = Credential(user, password, lmhash, nthash, domain)
logger.debug('Parsed credentials: %s' % credential.get_identity())
return credential
def set_credentials():
credentials = []
logger.info('Loading credentials')
if conf.user is not None:
logger.debug('Loading credentials from command line')
credentials.append(add_credentials(conf.user, conf.password or '', conf.lmhash or '',
conf.nthash or '', conf.domain or ''))
if conf.credsfile is not None:
logger.debug('Loading credentials from file %s' % conf.credsfile)
parsed_credentials = parse_credentials_file(conf.credsfile)
for credential in parsed_credentials:
if credential is not None:
credentials.append(credential)
unique_credentials = []
for credential in credentials:
if credential not in unique_credentials:
unique_credentials.append(credential)
if len(unique_credentials) < 1:
logger.error('No valid credentials loaded')
sys.exit(1)
logger.info('Loaded %s unique credential%s' % (len(credentials), 's' if len(credentials) > 1 else ''))
return unique_credentials
###############
# Set targets #
###############
def parse_targets_file(filename):
parsed_targets = []
try:
fp = open(filename, 'r')
file_lines = fp.read().splitlines()
fp.close()
except IOError as _:
logger.error('Could not open targets file %s' % filename)
return
file_lines = remove_comments(file_lines)
for line in file_lines:
parsed_targets.append(add_target(line))
if len(parsed_targets) > 0:
return parsed_targets
else:
return False
def parse_target(target_line):
targetmatch = re.compile(r'^([0-9a-zA-Z\-_.]+)(:(\d+))?')
h = targetmatch.match(str(target_line))
if h and h.group(3):
host = h.group(1)
port = h.group(3)
if port.isdigit() and 0 < int(port) <= 65535:
return host, int(port)
else:
return host, conf.port
elif h:
host = h.group(1)
return host, conf.port
else:
raise targetError('target error')
def add_target(line):
try:
host, port = parse_target(line)
except targetError as _:
logger.warn('Bad line in targets file %s: %s' % (conf.list, line))
return
target = Target(host, port)
logger.debug('Parsed target: %s' % target.get_identity())
return target
def addr_to_int(value):
_ = value.split('.')
return (int(_[0]) << 24) + (int(_[1]) << 16) + (int(_[2]) << 8) + int(_[3])
def int_to_addr(value):
return '.'.join(str(value >> n & 0xFF) for n in (24, 16, 8, 0))
def set_targets():
targets = []
logger.info('Loading targets')
if conf.target is not None:
if '/' not in conf.target:
logger.debug('Loading targets from command line')
targets.append(add_target(conf.target))
else:
address, mask = re.search(r"([\d.]+)/(\d+)", conf.target).groups()
logger.debug('Expanding targets from command line')
start_int = addr_to_int(address) & ~((1 << 32 - int(mask)) - 1)
end_int = start_int | ((1 << 32 - int(mask)) - 1)
for _ in range(start_int, end_int):
targets.append(add_target(int_to_addr(_)))
if conf.list is not None:
logger.debug('Loading targets from file %s' % conf.list)
parsed_targets = parse_targets_file(conf.list)
if parsed_targets is not False:
for target in parsed_targets:
if target is not None:
targets.append(target)
unique_targets = []
for target in targets:
if target not in unique_targets:
unique_targets.append(target)
if len(unique_targets) < 1:
logger.error('No valid targets loaded')
sys.exit(1)
logger.info('Loaded %s unique target%s' % (len(targets), 's' if len(targets) > 1 else ''))
return unique_targets
def check_conf():
global conf
set_verbosity(conf.verbose)
if conf.name is None:
conf.name = socket.gethostname()
conf.name = str(conf.name)
if conf.port is None:
conf.port = 445
logger.debug('Using %s as local NetBIOS hostname' % conf.name)
if conf.threads < 3:
conf.threads = 3
logger.info('Forcing number of threads to 3')
targets = set_targets()
credentials = set_credentials()
domains = set_domains()
for credential in credentials:
if credential.domain is not None:
if credential.domain not in domains:
domains.append(credential.domain)
if len(domains) == 0:
logger.info('No domains specified, using a blank domain')
elif len(domains) > 0:
logger.info('Loaded %s unique domain%s' % (len(domains), 's' if len(domains) > 1 else ''))
return targets, credentials, domains
def cmdline_parser():
'''
This function parses the command line parameters and arguments
'''
usage = '%s [options]' % sys.argv[0]
parser = OptionParser(usage=usage, version=__version__)
try:
parser.add_option('-v', dest='verbose', type='int', default=0,
help='Verbosity level: 0-2 (default: 0)')
parser.add_option('-t', dest='target', help='Target address')
parser.add_option('-l', dest='list', help='File with list of targets')
parser.add_option('-U', dest='user', help='User')
parser.add_option('-P', dest='password', help='Password')
parser.add_option('--nt', dest='nthash', help='NT hash')
parser.add_option('--lm', dest='lmhash', help='LM hash')
parser.add_option('-c', dest='credsfile', help='File with list of credentials')
parser.add_option('-D', dest='domain', help='Domain')
parser.add_option('-d', dest='domainsfile', help='File with list of domains')
parser.add_option('-p', dest='port', type='int', default=445,
help='SMB port: 139 or 445 (default: 445)')
parser.add_option('-n', dest='name', help='Local NetBIOS hostname')
parser.add_option('-T', dest='threads', type='int', default=10,
help='Maximum simultaneous connections (default: 10)')
parser.add_option('-b', '--batch', dest='batch', action='store_true', default=False,
help='Batch mode: do not prompt for an interactive SMB shell')
parser.add_option('-x', dest='smbcmdlist', help='Execute a list of SMB '
'commands against all hosts')
parser.add_option('-X', dest='oscmdlist', help='Execute a list of OS '
'commands against all hosts')
(args, _) = parser.parse_args()
if not args.target and not args.list:
errMsg = 'missing a mandatory parameter (-t or -l), '
errMsg += '-h for help'
parser.error(errMsg)
return args
except (OptionError, TypeError) as e:
parser.error(e)
debugMsg = 'Parsing command line'
logger.debug(debugMsg)
def banner():
print('''
keimpx %s
by %s
''' % (__version__, __author__))
def main():
global conf
global have_readline
global pool_thread
banner()
conf = cmdline_parser()
targets, credentials, domains = check_conf()
pool_thread = threading.BoundedSemaphore(conf.threads)
try:
for target in targets:
target.update_credentials(credentials)
target.update_domains(domains)
pool_thread.acquire()
current = test_login(target)
current.daemon = True
current.start()
while threading.activeCount() > 1:
a = 'Caughtit'
pass
except KeyboardInterrupt:
print()
try:
logger.warn('Test interrupted')
a = 'Caughtit'
stop_threads[0] = True
except KeyboardInterrupt:
print()
logger.info('User aborted')
exit(1)
if successes == 0:
print('\nNo credentials worked on any target\n')
exit(0)
print('\nThe credentials worked in total %d times\n' % successes)
print('TARGET SORTED RESULTS:\n')
for target in targets:
valid_credentials = target.get_valid_credentials()
if len(valid_credentials) > 0:
print(target.get_identity())
for valid_credential in valid_credentials:
print(' %s' % valid_credential.get_identity())
print()
print('\nUSER SORTED RESULTS:\n')
credentials_valid_targets = {}
for target in targets:
valid_credentials = target.get_valid_credentials()
for credential in valid_credentials:
if credential in credentials_valid_targets:
credentials_valid_targets[credential].append(target)
else:
credentials_valid_targets[credential] = [target]
for credential, targets in credentials_valid_targets.items():
print(credential.get_identity(account_details=False))
for target in targets:
print(' %s' % target.get_identity())
print()
if conf.smbcmdlist is not None:
smb_cmd_list(targets)
if conf.oscmdlist is not None:
os_cmd_list(targets)
if conf.batch or conf.smbcmdlist or conf.oscmdlist:
return
while True:
msg = 'Do you want to establish a SMB shell from any of the targets? [Y/n] '
choice = input(msg)
if choice and choice[0].lower() != 'y':
return
counter = 0
targets_dict = {}
msg = 'Which target do you want to connect to?'
for target in targets:
valid_credentials = target.get_valid_credentials()
if len(valid_credentials) > 0:
counter += 1
msg += '\n[%d] %s%s' % (counter, target.get_identity(), ' (default)' if counter == 1 else '')
targets_dict[counter] = (target, valid_credentials)
msg += '\n> '
choice = read_input(msg, counter)
user_target, valid_credentials = targets_dict[int(choice)]
counter = 0
credentials_dict = {}
msg = 'Which credentials do you want to use to connect?'
for credential in valid_credentials:
counter += 1
msg += '\n[%d] %s%s' % (counter, credential.get_identity(), ' (default)' if counter == 1 else '')
credentials_dict[counter] = credential
msg += '\n> '
choice = read_input(msg, counter)
user_credentials = credentials_dict[int(choice)]
if sys.platform.lower() == 'win32' and have_readline:
try:
_outputfile = readline.GetOutputFile()
except AttributeError:
logger.debug('Failed GetOutputFile when using platform\'s readline library')
have_readline = False
uses_libedit = False