-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathDeepExploit.py
More file actions
executable file
·2374 lines (2092 loc) · 110 KB
/
DeepExploit.py
File metadata and controls
executable file
·2374 lines (2092 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/env python
import copy
from datetime import datetime
import sys
import os
import time
import re
import copy
import json
import csv
import codecs
import random
import ipaddress
import configparser
import msgpack
import http.client
import threading
import numpy as np
import pandas as pd
import tensorflow as tf
from bs4 import BeautifulSoup
from docopt import docopt
from keras.models import *
from keras.layers import *
from keras import backend as K
from util import Utilty
from modules.VersionChecker import VersionChecker
from modules.VersionCheckerML import VersionCheckerML
from modules.ContentExplorer import ContentExplorer
from CreateReport import CreateReport
# Warnning for TensorFlow acceleration is not shown.
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Index of target host's state (s).
ST_OS_TYPE = 0 # OS types (unix, linux, windows, osx..).
ST_SERV_NAME = 1 # Product name on Port.
ST_SERV_VER = 2 # Product version.
ST_MODULE = 3 # Exploit module types.
ST_TARGET = 4 # target types (0, 1, 2..).
# ST_STAGE = 5 # exploit's stage (normal, exploitation, post-exploitation).
NUM_STATES = 5 # Size of state.
NONE_STATE = None
NUM_ACTIONS = 0
# Reward
R_GREAT = 100 # Successful of Stager/Stage payload.
R_GOOD = 1 # Successful of Single payload.
R_BAD = -1 # Failure of payload.
# Stage of exploitation
S_NORMAL = -1
S_EXPLOIT = 0
S_PEXPLOIT = 1
# Label type of printing.
OK = 'ok' # [*]
NOTE = 'note' # [+]
FAIL = 'fail' # [-]
WARNING = 'warn' # [!]
NONE = 'none' # No label.
# Metasploit interface.
class Msgrpc:
def __init__(self, option=[]):
self.host = option.get('host') or "127.0.0.1"
self.port = option.get('port') or 55552
self.uri = option.get('uri') or "/api/"
self.ssl = option.get('ssl') or False
self.authenticated = False
self.token = False
self.headers = {"Content-type": "binary/message-pack"}
if self.ssl:
self.client = http.client.HTTPSConnection(self.host, self.port)
else:
self.client = http.client.HTTPConnection(self.host, self.port)
self.util = Utilty()
# Read config.ini.
full_path = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
try:
config.read(os.path.join(full_path, 'config.ini'))
except FileExistsError as err:
self.util.print_message(FAIL, 'File exists error: {}'.format(err))
sys.exit(1)
# Common setting value.
self.msgrpc_user = config['Common']['msgrpc_user']
self.msgrpc_pass = config['Common']['msgrpc_pass']
self.timeout = int(config['Common']['timeout'])
self.con_retry = int(config['Common']['con_retry'])
self.retry_count = 0
self.console_id = 0
# Call RPC API.
def call(self, meth, origin_option):
# Set API option.
option = copy.deepcopy(origin_option)
option = self.set_api_option(meth, option)
# Send request.
resp = self.send_request(meth, option, origin_option)
return msgpack.unpackb(resp.read())
def set_api_option(self, meth, option):
if meth != 'auth.login':
if not self.authenticated:
self.util.print_message(FAIL, 'MsfRPC: Not Authenticated.')
exit(1)
if meth != 'auth.login':
option.insert(0, self.token)
option.insert(0, meth)
return option
# Send HTTP request.
def send_request(self, meth, option, origin_option):
params = msgpack.packb(option)
resp = ''
try:
self.client.request("POST", self.uri, params, self.headers)
resp = self.client.getresponse()
self.retry_count = 0
except Exception as err:
while True:
self.retry_count += 1
if self.retry_count == self.con_retry:
self.util.print_exception(err, 'Retry count is over.')
exit(1)
else:
# Retry.
self.util.print_message(WARNING, '{}/{} Retry "{}" call. reason: {}'.format(
self.retry_count, self.con_retry, option[0], err))
time.sleep(1.0)
if self.ssl:
self.client = http.client.HTTPSConnection(self.host, self.port)
else:
self.client = http.client.HTTPConnection(self.host, self.port)
if meth != 'auth.login':
self.login(self.msgrpc_user, self.msgrpc_pass)
option = self.set_api_option(meth, origin_option)
self.get_console()
resp = self.send_request(meth, option, origin_option)
break
return resp
# Log in to RPC Server.
def login(self, user, password):
ret = self.call('auth.login', [user, password])
try:
if ret.get(b'result') == b'success':
self.authenticated = True
self.token = ret.get(b'token')
return True
else:
self.util.print_message(FAIL, 'MsfRPC: Authentication failed.')
exit(1)
except Exception as e:
self.util.print_exception(e, 'Failed: auth.login')
exit(1)
# Keep alive.
def keep_alive(self):
self.util.print_message(OK, 'Executing keep_alive..')
_ = self.send_command(self.console_id, 'version\n', False)
# Create MSFconsole.
def get_console(self):
# Create a console.
ret = self.call('console.create', [])
try:
self.console_id = ret.get(b'id')
_ = self.call('console.read', [self.console_id])
except Exception as err:
self.util.print_exception(err, 'Failed: console.create')
exit(1)
# Send Metasploit command.
def send_command(self, console_id, command, visualization, sleep=0.1):
_ = self.call('console.write', [console_id, command])
time.sleep(0.5)
ret = self.call('console.read', [console_id])
time.sleep(sleep)
result = ''
try:
result = ret.get(b'data').decode('utf-8')
if visualization:
self.util.print_message(OK, 'Result of "{}":\n{}'.format(command, result))
except Exception as e:
self.util.print_exception(e, 'Failed: {}'.format(command))
return result
# Get all modules.
def get_module_list(self, module_type):
ret = {}
if module_type == 'exploit':
ret = self.call('module.exploits', [])
elif module_type == 'auxiliary':
ret = self.call('module.auxiliary', [])
elif module_type == 'post':
ret = self.call('module.post', [])
elif module_type == 'payload':
ret = self.call('module.payloads', [])
elif module_type == 'encoder':
ret = self.call('module.encoders', [])
elif module_type == 'nop':
ret = self.call('module.nops', [])
try:
byte_list = ret[b'modules']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
except Exception as e:
self.util.print_exception(e, 'Failed: Getting {} module list.'.format(module_type))
exit(1)
# Get module detail information.
def get_module_info(self, module_type, module_name):
return self.call('module.info', [module_type, module_name])
# Get payload that compatible module.
def get_compatible_payload_list(self, module_name):
ret = self.call('module.compatible_payloads', [module_name])
try:
byte_list = ret[b'payloads']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
except Exception as e:
self.util.print_exception(e, 'Failed: module.compatible_payloads.')
return []
# Get payload that compatible target.
def get_target_compatible_payload_list(self, module_name, target_num):
ret = self.call('module.target_compatible_payloads', [module_name, target_num])
try:
byte_list = ret[b'payloads']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
except Exception as e:
self.util.print_exception(e, 'Failed: module.target_compatible_payloads.')
return []
# Get module options.
def get_module_options(self, module_type, module_name):
return self.call('module.options', [module_type, module_name])
# Execute module.
def execute_module(self, module_type, module_name, options):
ret = self.call('module.execute', [module_type, module_name, options])
try:
job_id = ret[b'job_id']
uuid = ret[b'uuid'].decode('utf-8')
return job_id, uuid
except Exception as e:
if ret[b'error_code'] == 401:
self.login(self.msgrpc_user, self.msgrpc_pass)
else:
self.util.print_exception(e, 'Failed: module.execute.')
exit(1)
# Get job list.
def get_job_list(self):
jobs = self.call('job.list', [])
try:
byte_list = jobs.keys()
job_list = []
for job_id in byte_list:
job_list.append(int(job_id.decode('utf-8')))
return job_list
except Exception as e:
self.util.print_exception(e, 'Failed: job.list.')
return []
# Get job detail information.
def get_job_info(self, job_id):
return self.call('job.info', [job_id])
# Stop job.
def stop_job(self, job_id):
return self.call('job.stop', [job_id])
# Get session list.
def get_session_list(self):
return self.call('session.list', [])
# Stop session.
def stop_session(self, session_id):
_ = self.call('session.stop', [str(session_id)])
# Stop meterpreter session.
def stop_meterpreter_session(self, session_id):
_ = self.call('session.meterpreter_session_detach', [str(session_id)])
# Execute shell.
def execute_shell(self, session_id, cmd):
ret = self.call('session.shell_write', [str(session_id), cmd])
try:
return ret[b'write_count'].decode('utf-8')
except Exception as e:
self.util.print_exception(e, 'Failed: {}'.format(cmd))
return 'Failed'
# Get executing shell result.
def get_shell_result(self, session_id, read_pointer):
ret = self.call('session.shell_read', [str(session_id), read_pointer])
try:
seq = ret[b'seq'].decode('utf-8')
data = ret[b'data'].decode('utf-8')
return seq, data
except Exception as e:
self.util.print_exception(e, 'Failed: session.shell_read.')
return 0, 'Failed'
# Execute meterpreter.
def execute_meterpreter(self, session_id, cmd):
ret = self.call('session.meterpreter_write', [str(session_id), cmd])
try:
return ret[b'result'].decode('utf-8')
except Exception as e:
self.util.print_exception(e, 'Failed: {}'.format(cmd))
return 'Failed'
# Execute single meterpreter.
def execute_meterpreter_run_single(self, session_id, cmd):
ret = self.call('session.meterpreter_run_single', [str(session_id), cmd])
try:
return ret[b'result'].decode('utf-8')
except Exception as e:
self.util.print_exception(e, 'Failed: {}'.format(cmd))
return 'Failed'
# Get executing meterpreter result.
def get_meterpreter_result(self, session_id):
ret = self.call('session.meterpreter_read', [str(session_id)])
try:
return ret[b'data'].decode('utf-8')
except Exception as e:
self.util.print_exception(e, 'Failed: session.meterpreter_read')
return None
# Upgrade shell session to meterpreter.
def upgrade_shell_session(self, session_id, lhost, lport):
ret = self.call('session.shell_upgrade', [str(session_id), lhost, lport])
try:
return ret[b'result'].decode('utf-8')
except Exception as e:
self.util.print_exception(e, 'Failed: session.shell_upgrade')
return 'Failed'
# Log out from RPC Server.
def logout(self):
ret = self.call('auth.logout', [self.token])
try:
if ret.get(b'result') == b'success':
self.authenticated = False
self.token = ''
return True
else:
self.util.print_message(FAIL, 'MsfRPC: Authentication failed.')
exit(1)
except Exception as e:
self.util.print_exception(e, 'Failed: auth.logout')
exit(1)
# Disconnection.
def termination(self, console_id):
# Kill a console and Log out.
_ = self.call('console.session_kill', [console_id])
_ = self.logout()
# Metasploit's environment.
class Metasploit:
def __init__(self, target_ip='127.0.0.1'):
self.util = Utilty()
self.rhost = target_ip
# Read config.ini.
full_path = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
try:
config.read(os.path.join(full_path, 'config.ini'))
except FileExistsError as err:
self.util.print_message(FAIL, 'File exists error: {}'.format(err))
sys.exit(1)
# Common setting value.
server_host = config['Common']['server_host']
server_port = int(config['Common']['server_port'])
self.msgrpc_user = config['Common']['msgrpc_user']
self.msgrpc_pass = config['Common']['msgrpc_pass']
self.timeout = int(config['Common']['timeout'])
self.max_attempt = int(config['Common']['max_attempt'])
self.save_path = os.path.join(full_path, config['Common']['save_path'])
self.save_file = os.path.join(self.save_path, config['Common']['save_file'])
self.data_path = os.path.join(full_path, config['Common']['data_path'])
if os.path.exists(self.data_path) is False:
os.mkdir(self.data_path)
self.plot_file = os.path.join(self.data_path, config['Common']['plot_file'])
self.port_div_symbol = config['Common']['port_div']
# Metasploit options setting value.
self.lhost = server_host
self.lport = int(config['Metasploit']['lport'])
self.proxy_host = config['Metasploit']['proxy_host']
self.proxy_port = int(config['Metasploit']['proxy_port'])
self.prohibited_list = str(config['Metasploit']['prohibited_list']).split('@')
self.path_collection = str(config['Metasploit']['path_collection']).split('@')
# Nmap options setting value.
self.nmap_command = config['Nmap']['command']
self.nmap_timeout = config['Nmap']['timeout']
self.nmap_2nd_command = config['Nmap']['second_command']
self.nmap_2nd_timeout = config['Nmap']['second_timeout']
# A3C setting value.
self.train_worker_num = int(config['A3C']['train_worker_num'])
self.train_max_num = int(config['A3C']['train_max_num'])
self.train_max_steps = int(config['A3C']['train_max_steps'])
self.train_tmax = int(config['A3C']['train_tmax'])
self.test_worker_num = int(config['A3C']['test_worker_num'])
self.greedy_rate = float(config['A3C']['greedy_rate'])
self.eps_steps = int(self.train_max_num * self.greedy_rate)
# State setting value.
self.state = [] # Deep Exploit's state(s).
self.os_type = str(config['State']['os_type']).split('@') # OS type.
self.os_real = len(self.os_type) - 1
self.service_list = str(config['State']['services']).split('@') # Product name.
# Report setting value.
self.report_test_path = os.path.join(full_path, config['Report']['report_test'])
self.report_train_path = os.path.join(self.report_test_path, config['Report']['report_train'])
if os.path.exists(self.report_train_path) is False:
os.mkdir(self.report_train_path)
self.scan_start_time = self.util.get_current_date()
self.source_host= server_host
self.client = Msgrpc({'host': server_host, 'port': server_port}) # Create Msgrpc instance.
self.client.login(self.msgrpc_user, self.msgrpc_pass) # Log in to RPC Server.
self.client.get_console() # Get MSFconsole ID.
self.buffer_seq = 0
self.isPostExploit = False # Executing Post-Exploiting True/False.
# Create exploit tree.
def get_exploit_tree(self):
self.util.print_message(NOTE, 'Get exploit tree.')
exploit_tree = {}
if os.path.exists(os.path.join(self.data_path, 'exploit_tree.json')) is False:
for idx, exploit in enumerate(com_exploit_list):
temp_target_tree = {'targets': []}
temp_tree = {}
# Set exploit module.
use_cmd = 'use exploit/' + exploit + '\n'
_ = self.client.send_command(self.client.console_id, use_cmd, False)
# Get target.
show_cmd = 'show targets\n'
target_info = ''
time_count = 0
while True:
target_info = self.client.send_command(self.client.console_id, show_cmd, False)
if 'Exploit targets' in target_info:
break
if time_count == 5:
self.util.print_message(OK, 'Timeout: {0}'.format(show_cmd))
self.util.print_message(OK, 'No exist Targets.')
break
time.sleep(1.0)
time_count += 1
target_list = self.cutting_strings(r'\s*([0-9]{1,3}) .*[a-z|A-Z|0-9].*[\r\n]', target_info)
for target in target_list:
# Get payload list.
payload_list = self.client.get_target_compatible_payload_list(exploit, int(target))
temp_tree[target] = payload_list
# Get options.
options = self.client.get_module_options('exploit', exploit)
key_list = options.keys()
option = {}
for key in key_list:
sub_option = {}
sub_key_list = options[key].keys()
for sub_key in sub_key_list:
if isinstance(options[key][sub_key], list):
end_option = []
for end_key in options[key][sub_key]:
end_option.append(end_key.decode('utf-8'))
sub_option[sub_key.decode('utf-8')] = end_option
else:
end_option = {}
if isinstance(options[key][sub_key], bytes):
sub_option[sub_key.decode('utf-8')] = options[key][sub_key].decode('utf-8')
else:
sub_option[sub_key.decode('utf-8')] = options[key][sub_key]
# User specify.
sub_option['user_specify'] = ""
option[key.decode('utf-8')] = sub_option
# Add payloads and targets to exploit tree.
temp_target_tree['target_list'] = target_list
temp_target_tree['targets'] = temp_tree
temp_target_tree['options'] = option
exploit_tree[exploit] = temp_target_tree
# Output processing status to console.
self.util.print_message(OK, '{}/{} exploit:{}, targets:{}'.format(str(idx + 1),
len(com_exploit_list),
exploit,
len(target_list)))
# Save exploit tree to local file.
fout = codecs.open(os.path.join(self.data_path, 'exploit_tree.json'), 'w', 'utf-8')
json.dump(exploit_tree, fout, indent=4)
fout.close()
self.util.print_message(OK, 'Saved exploit tree.')
else:
# Get exploit tree from local file.
local_file = os.path.join(self.data_path, 'exploit_tree.json')
self.util.print_message(OK, 'Loaded exploit tree from : {}'.format(local_file))
fin = codecs.open(local_file, 'r', 'utf-8')
exploit_tree = json.loads(fin.read().replace('\0', ''))
fin.close()
return exploit_tree
# Get target host information.
def get_target_info(self, rhost, proto_list, port_info):
self.util.print_message(NOTE, 'Get target info.')
target_tree = {}
if os.path.exists(os.path.join(self.data_path, 'target_info_' + rhost + '.json')) is False:
# Examination product and version on the Web ports.
path_list = ['' for idx in range(len(com_port_list))]
# TODO: Crawling on the Post-Exploitation phase.
if self.isPostExploit is False:
# Create instances.
version_checker = VersionChecker(self.util)
version_checker_ml = VersionCheckerML(self.util)
content_explorer = ContentExplorer(self.util)
# Check web port.
web_port_list = self.util.check_web_port(rhost, com_port_list, self.client)
# Gather target url using Spider.
web_target_info = self.util.run_spider(rhost, web_port_list, self.client)
# Get HTTP responses and check products per web port.
uniq_product = []
for idx_target, target in enumerate(web_target_info):
web_prod_list = []
# Scramble.
target_list = target[2]
if self.util.is_scramble is True:
self.util.print_message(WARNING, 'Scramble target list.')
target_list = random.sample(target[2], len(target[2]))
# Cutting target url counts.
if self.util.max_target_url != 0 and self.util.max_target_url < len(target_list):
self.util.print_message(WARNING, 'Cutting target list {} to {}.'
.format(len(target[2]), self.util.max_target_url))
target_list = target_list[:self.util.max_target_url]
# Identify product name/version per target url.
for count, target_url in enumerate(target_list):
self.util.print_message(NOTE, '{}/{} Start analyzing: {}'
.format(count + 1, len(target_list), target_url))
self.client.keep_alive()
# Check target url.
parsed = util.parse_url(target_url)
if parsed is None:
continue
# Get HTTP response (header + body).
_, res_header, res_body = self.util.send_request('GET', target_url)
copy_of_response = copy.copy( res_body )
soup = BeautifulSoup( res_body, 'lxml' )
attrs = []
for elm in soup():
attrs += list(elm.attrs.values())
for a in attrs:
if a and len(a) > 256:
copy_of_response = copy_of_response.replace( a, a[0:255] )
soup.decompose()
# Cutting response byte.
if self.util.max_target_byte != 0 and (self.util.max_target_byte < len(res_body)):
self.util.print_message(WARNING, 'Cutting response byte {} to {}.'
.format(len(res_body), self.util.max_target_byte))
res_body = res_body[:self.util.max_target_byte]
# Check product name/version using signature.
web_prod_list.extend(version_checker.get_product_name(parsed,
res_header + copy_of_response,
self.client))
# Check product name/version using Machine Learning.
web_prod_list.extend(version_checker_ml.get_product_name(parsed,
res_header + copy_of_response,
self.client))
# Check product name/version using default contents.
parsed = None
try:
parsed = util.parse_url(target[0])
except Exception as e:
self.util.print_exception(e, 'Parsed error : {}'.format(target[0]))
continue
web_prod_list.extend(content_explorer.content_explorer(parsed, target[0], self.client))
# Delete duplication.
tmp_list = []
for item in list(set(web_prod_list)):
tmp_item = item.split('@')
tmp = tmp_item[0] + ' ' + tmp_item[1] + ' ' + tmp_item[2]
if tmp not in tmp_list:
tmp_list.append(tmp)
uniq_product.append(item)
# Assemble web product information.
for idx, web_prod in enumerate(uniq_product):
web_item = web_prod.split('@')
proto_list.append('tcp')
port_info.append(web_item[0] + ' ' + web_item[1])
com_port_list.append(web_item[2] + self.port_div_symbol + str(idx))
path_list.append(web_item[3])
# Create target info.
target_tree = {'rhost': rhost, 'os_type': self.os_real}
for port_idx, port_num in enumerate(com_port_list):
temp_tree = {'prod_name': '', 'version': 0.0, 'protocol': '', 'target_path': '', 'exploit': []}
# Get product name.
service_name = 'unknown'
for (idx, service) in enumerate(self.service_list):
try:
if service in port_info[port_idx].lower():
service_name = service
break
except:
pass
temp_tree['prod_name'] = service_name
# Get product version.
# idx=1 2.3.4, idx=2 4.7p1, idx=3 1.0.1f, idx4 2.0 or v1.3 idx5 3.X
regex_list = [r'.*\s(\d{1,3}\.\d{1,3}\.\d{1,3}).*',
r'.*\s[a-z]?(\d{1,3}\.\d{1,3}[a-z]\d{1,3}).*',
r'.*\s[\w]?(\d{1,3}\.\d{1,3}\.\d[a-z]{1,3}).*',
r'.*\s[a-z]?(\d\.\d).*',
r'.*\s(\d\.[xX|\*]).*']
version = 0.0
output_version = 0.0
for (idx, regex) in enumerate(regex_list):
try:
version_raw = self.cutting_strings(regex, port_info[port_idx])
if len(version_raw) == 0:
continue
if idx == 0:
index = version_raw[0].rfind('.')
version = version_raw[0][:index] + version_raw[0][index + 1:]
output_version = version_raw[0]
break
elif idx == 1:
index = re.search(r'[a-z]', version_raw[0]).start()
version = version_raw[0][:index] + str(ord(version_raw[0][index])) + version_raw[0][index + 1:]
output_version = version_raw[0]
break
elif idx == 2:
index = re.search(r'[a-z]', version_raw[0]).start()
version = version_raw[0][:index] + str(ord(version_raw[0][index])) + version_raw[0][index + 1:]
index = version.rfind('.')
version = version_raw[0][:index] + version_raw[0][index:]
output_version = version_raw[0]
break
elif idx == 3:
version = self.cutting_strings(r'[a-z]?(\d\.\d)', version_raw[0])
version = version[0]
output_version = version_raw[0]
break
elif idx == 4:
version = version_raw[0].replace('X', '0').replace('x', '0').replace('*', '0')
version = version[0]
output_version = version_raw[0]
except:
pass
temp_tree['version'] = float(version)
# Get protocol type.
temp_tree['protocol'] = proto_list[port_idx]
if path_list is not None:
temp_tree['target_path'] = path_list[port_idx]
# Get exploit module.
module_list = []
raw_module_info = ''
idx = 0
search_cmd = 'search name:' + service_name + ' type:exploit app:server\n'
raw_module_info = self.client.send_command(self.client.console_id, search_cmd, False, 3.0)
module_list = self.extract_osmatch_module(self.cutting_strings(r'(exploit/.*)', raw_module_info))
if service_name != 'unknown' and len(module_list) == 0:
self.util.print_message(WARNING, 'Can\'t load exploit module: {}'.format(service_name))
temp_tree['prod_name'] = 'unknown'
for module in module_list:
if module[1] in {'excellent', 'great', 'good'}:
temp_tree['exploit'].append(module[0])
target_tree[str(port_num)] = temp_tree
# Output processing status to console.
self.util.print_message(OK, 'Analyzing port {}/{}, {}/{}, '
'Available exploit modules:{}'.format(port_num,
temp_tree['protocol'],
temp_tree['prod_name'],
output_version,
len(temp_tree['exploit'])))
# Save target host information to local file.
fout = codecs.open(os.path.join(self.data_path, 'target_info_' + rhost + '.json'), 'w', 'utf-8')
json.dump(target_tree, fout, indent=4)
fout.close()
self.util.print_message(OK, 'Saved target tree.')
else:
# Get target host information from local file.
saved_file = os.path.join(self.data_path, 'target_info_' + rhost + '.json')
self.util.print_message(OK, 'Loaded target tree from : {}'.format(saved_file))
fin = codecs.open(saved_file, 'r', 'utf-8')
target_tree = json.loads(fin.read().replace('\0', ''))
fin.close()
return target_tree
# Get target host information for indicate port number.
def get_target_info_indicate(self, rhost, proto_list, port_info, port=None, prod_name=None):
self.util.print_message(NOTE, 'Get target info for indicate port number.')
target_tree = {'origin_port': port}
# Update "com_port_list".
com_port_list = []
for prod in prod_name.split('@'):
temp_tree = {'prod_name': '', 'version': 0.0, 'protocol': '', 'exploit': []}
virtual_port = str(np.random.randint(999999999))
com_port_list.append(virtual_port)
# Get product name.
service_name = 'unknown'
for (idx, service) in enumerate(self.service_list):
if service == prod.lower():
service_name = service
break
temp_tree['prod_name'] = service_name
# Get product version.
temp_tree['version'] = float(0.0)
# Get protocol type.
temp_tree['protocol'] = 'tcp'
# Get exploit module.
module_list = []
raw_module_info = ''
idx = 0
search_cmd = 'search name:' + service_name + ' type:exploit app:server\n'
raw_module_info = self.client.send_command(self.client.console_id, search_cmd, False, 3.0)
module_list = self.cutting_strings(r'(exploit/.*)', raw_module_info)
if service_name != 'unknown' and len(module_list) == 0:
continue
for exploit in module_list:
raw_exploit_info = exploit.split(' ')
exploit_info = list(filter(lambda s: s != '', raw_exploit_info))
if exploit_info[2] in {'excellent', 'great', 'good'}:
temp_tree['exploit'].append(exploit_info[0])
target_tree[virtual_port] = temp_tree
# Output processing status to console.
self.util.print_message(OK, 'Analyzing port {}/{}, {}, '
'Available exploit modules:{}'.format(port,
temp_tree['protocol'],
temp_tree['prod_name'],
len(temp_tree['exploit'])))
# Save target host information to local file.
with codecs.open(os.path.join(self.data_path, 'target_info_indicate_' + rhost + '.json'), 'w', 'utf-8') as fout:
json.dump(target_tree, fout, indent=4)
return target_tree, com_port_list
# Get target OS name.
def extract_osmatch_module(self, module_list):
osmatch_module_list = []
for module in module_list:
raw_exploit_info = module.split(' ')
exploit_info = list(filter(lambda s: s != '', raw_exploit_info))
os_type = exploit_info[0].split('/')[1]
if self.os_real == 0 and os_type in ['windows', 'multi']:
try:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
except:
pass
elif self.os_real == 1 and os_type in ['unix', 'freebsd', 'bsdi', 'linux', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 2 and os_type in ['solaris', 'unix', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 3 and os_type in ['osx', 'unix', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 4 and os_type in ['netware', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 5 and os_type in ['linux', 'unix', 'multi']:
try:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
except:
pass
elif self.os_real == 6 and os_type in ['irix', 'unix', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 7 and os_type in ['hpux', 'unix', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 8 and os_type in ['freebsd', 'unix', 'bsdi', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 9 and os_type in ['firefox', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 10 and os_type in ['dialup', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 11 and os_type in ['bsdi', 'unix', 'freebsd', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 12 and os_type in ['apple_ios', 'unix', 'osx', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 13 and os_type in ['android', 'linux', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 14 and os_type in ['aix', 'unix', 'multi']:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
elif self.os_real == 15:
try:
osmatch_module_list.append([exploit_info[0], exploit_info[2]])
except:
pass
return osmatch_module_list
# Parse.
def cutting_strings(self, pattern, target):
return re.findall(pattern, target)
# Normalization.
def normalization(self, target_idx):
if target_idx == ST_OS_TYPE:
os_num = int(self.state[ST_OS_TYPE])
os_num_mean = len(self.os_type) / 2
self.state[ST_OS_TYPE] = (os_num - os_num_mean) / os_num_mean
if target_idx == ST_SERV_NAME:
try:
service_num = self.state[ST_SERV_NAME]
service_num_mean = len(self.service_list) / 2
self.state[ST_SERV_NAME] = (service_num - service_num_mean) / service_num_mean
except:
pass
elif target_idx == ST_MODULE:
prompt_num = self.state[ST_MODULE]
prompt_num_mean = len(com_exploit_list) / 2
self.state[ST_MODULE] = (prompt_num - prompt_num_mean) / prompt_num_mean
# Execute Nmap.
def execute_nmap( self, rhost, command, timeout, nmap_output_file = None ):
self.util.print_message(NOTE, 'Execute Nmap against {}'.format(rhost))
if nmap_output_file and os.path.exists( nmap_output_file ):
return
target_json_path = os.path.join(self.data_path, 'target_info_' + rhost + '.json')
if os.path.exists( target_json_path ) is False:
# Execute Nmap.
self.util.print_message(OK, '{}'.format(command))
self.util.print_message(OK, 'Start time: {}'.format(self.util.get_current_date()))
_ = self.client.call('console.write', [self.client.console_id, command])
time.sleep(3.0)
time_count = 0
while True:
# Judgement of Nmap finishing.
ret = self.client.call('console.read', [self.client.console_id])
# show nmap execution outputs, comment this out when not debugggggging
self.util.print_message(NOTE, '{}'.format(ret))
try:
if (time_count % 5) == 0:
self.util.print_message(OK, 'Port scanning: {} [Elapsed time: {} s]'.format(rhost, time_count))
self.client.keep_alive()
if timeout == time_count:
self.client.termination(self.client.console_id)
self.util.print_message(OK, 'Timeout : {}'.format(command))
self.util.print_message(OK, 'End time : {}'.format(self.util.get_current_date()))
break
status = ret.get(b'busy')
if status is False:
self.util.print_message(OK, 'End time : {}'.format(self.util.get_current_date()))
time.sleep(5.0)
break
except Exception as e:
self.util.print_exception(e, 'Failed: {}'.format(command))
time.sleep(1.0)
time_count += 1
_ = self.client.call('console.destroy', [self.client.console_id])
ret = self.client.call('console.create', [])
try:
self.client.console_id = ret.get(b'id')
except Exception as e:
self.util.print_exception(e, 'Failed: console.create')
exit(1)
_ = self.client.call('console.read', [self.client.console_id])
else:
self.util.print_message(OK, 'Nmap already scanned.')
# Get port list from Nmap's XML result.
def get_port_list(self, nmap_result_file, rhost, ignore_empty_host=False):
self.util.print_message(NOTE, 'Get port list from {}.'.format(nmap_result_file))
global com_port_list
port_list = []
proto_list = []
info_list = []
if os.path.exists(os.path.join(self.data_path, 'target_info_' + rhost + '.json')) is False:
nmap_result = ''
cat_cmd = 'cat ' + nmap_result_file + '\n'
_ = self.client.call('console.write', [self.client.console_id, cat_cmd])
time.sleep(3.0)
time_count = 0
while True:
# Judgement of 'services' command finishing.
ret = self.client.call('console.read', [self.client.console_id])
try:
if self.timeout == time_count:
self.client.termination(self.client.console_id)
self.util.print_message(OK, 'Timeout: "{}"'.format(cat_cmd))
break
nmap_result += ret.get(b'data').decode('utf-8')
status = ret.get(b'busy')
if status is False:
break
except Exception as e:
self.util.print_exception(e, 'Failed: console.read')
time.sleep(1.0)
time_count += 1
# Get port, protocol, information from XML file.
port_list = []
proto_list = []
info_list = []
bs = BeautifulSoup(nmap_result, 'lxml')
ports = bs.find_all('port')
for idx, port in enumerate(ports):
port_list.append(str(port.attrs['portid']))
proto_list.append(port.attrs['protocol'])
for obj_child in port.contents:
if obj_child.name == 'service':
temp_info = ''
if 'product' in obj_child.attrs:
temp_info += obj_child.attrs['product'] + ' '
if 'version' in obj_child.attrs:
temp_info += obj_child.attrs['version'] + ' '
if 'extrainfo' in obj_child.attrs:
temp_info += obj_child.attrs['extrainfo']
if temp_info != '':
info_list.append(temp_info)
else:
info_list.append('unknown')
# Display getting port information.
try:
self.util.print_message(OK, 'Getting {}/{} info: {}'.format(str(port.attrs['portid']),
port.attrs['protocol'],
info_list[idx]))
except:
pass
if not ignore_empty_host and len(port_list) == 0:
self.util.print_message(WARNING, 'No open port.')
self.util.print_message(WARNING, 'Shutdown Deep Exploit...')
self.client.termination(self.client.console_id)
exit(1)
# Update com_port_list.
com_port_list = port_list
# Get OS name from XML file.
some_os = bs.find_all('osmatch')
os_name = 'unknown'
for obj_os in some_os:
for obj_child in obj_os.contents:
if obj_child.name == 'osclass' and 'osfamily' in obj_child.attrs:
os_name = (obj_child.attrs['osfamily']).lower()
break