-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmt_console.py
115 lines (99 loc) · 3.53 KB
/
mt_console.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
#!/usr/bin/env python
# -*- coding=utf-8 -*-
"""Usage:
mt_console start -F <apk_dir> [-v] [--config <config_file>]
mt_console stop
mt_console bash
mt_console (-h|--help)
Options:
-h --help Show this screen.
start: Start a scan.
-v Verbose log.
-d Debug log.
--skip-unpacker Skip unpacker (just for debug).
stop Stop a scan.
bash start a bash.
"""
import json
import logging
import os
import shutil
import subprocess
import time
from docopt import docopt
import core.controllers.controller as ctrl
def _format(dic):
"""
格式化返回格式,符合慕测要求
:param dic:
:return:
"""
# 修改一下reference的字段名
references = map(lambda ref: {'location': ref['location'], 'description': ref['detail']}, dic['reference'])
# 修改一个vuln的格式
return dict(name=dic['vulnerability']['i18n_name'],
updateTime=dic['update_time'],
description=dic['vulnerability']['description'],
vulType=0,
riskLevel=dic['vulnerability']['risk_level'],
targetTaskId=0,
solution=dic['vulnerability']['solution'],
source='android_apk',
extra={"category":dic['vulnerability']['category']},
vulReferences=references)
def start(path, log_level=logging.INFO, config_path=None):
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(filename)s : %(funcName)s() : %(message)s',
level=log_level)
res = ctrl.start(path, config_path)
res = filter(lambda vulns: vulns.reference, res)
res = map(lambda e: _format(e.to_dict()), res)
print json.dumps(res)
def stop():
files = os.listdir('.')
rmfiles = []
for filename in files:
if filename.endswith('.apksec'):
apk_name = filename.split('.')[0]
cmd = 'ps -ef|grep -E "start -F.*{}.apk|PID"'.format(apk_name)
ps_res = os.popen(cmd).readlines()
flags = ps_res[0].split()
pid_idx = flags.index("PID")
for each_line in ps_res[1:]:
pid = each_line.split()[pid_idx]
if 'grep' not in each_line:
cmd = "kill {}".format(pid)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode:
raise Exception(stderr)
rmfiles.append(filename)
for each in rmfiles:
if os.path.exists(os.path.join('.', each)):
failed = True
while failed:
try:
shutil.rmtree(os.path.join('.', each))
failed = False
except OSError as e:
logging.error(e)
time.sleep(1)
logging.error('Retry after 1 seconds.')
logging.info('Stop success.')
def main():
arguments = docopt(__doc__, version='1.0.0')
if arguments["start"]:
if arguments["-v"]:
log_level = logging.DEBUG
else:
log_level = logging.ERROR
if arguments["--config"]:
config_path = arguments["<config_file>"]
else:
config_path = None
start(arguments["<apk_dir>"], log_level=log_level, config_path=config_path)
elif arguments["stop"]:
stop()
elif arguments["bash"]:
os.system("bash")
if __name__ == '__main__':
main()