-
Notifications
You must be signed in to change notification settings - Fork 0
/
mass_static_analysis.py
executable file
·161 lines (137 loc) · 5.27 KB
/
mass_static_analysis.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
#!/usr/bin/env python
# Mass Static Analysis
import argparse
import logging
import os
import urllib.error
import urllib.parse
import urllib.request
import requests
import shutil
import glob
# logger = logging.getLogger(__name__)
# logging.basicConfig(filename='/opt/massa/log/test.log',
# format="[%(asctime)s] %(levelname)s %(message)s",
# datefmt="%Y-%m-%d,%H:%M:%S",
# level=logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s',datefmt="%Y-%m-%d,%H:%M:%S")
def setup_logger(name, log_file, level=logging.INFO):
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
#first logger
logger = setup_logger('first_logger', '/opt/massa/log/test.log')
# second file logger
logger2 = setup_logger('second_logger', '/opt/massa/log/test2.log')
def is_server_up(url):
try:
urllib.request.urlopen(url, timeout=5)
return True
except urllib.error.URLError:
pass
return False
def start_scan(directory, server_url, apikey, rescan='0'):
print('\nLooking for Android/iOS/'
'Windows binaries or source code in : ' + directory)
logger.info('Uploading to MobSF Server')
uploaded = []
mimes = {
'.apk': 'application/octet-stream',
# '.ipa': 'application/octet-stream',
# '.appx': 'application/octet-stream',
# '.zip': 'application/zip',
}
for filename in os.listdir(directory):
fpath = os.path.join(directory, filename)
_, ext = os.path.splitext(fpath)
if ext in mimes:
files = {'file': (filename, open(fpath, 'rb'),
mimes[ext], {'Expires': '0'})}
response = requests.post(
server_url + '/api/v1/upload',
files=files,
headers={'AUTHORIZATION': apikey})
if response.status_code == 200 and 'hash' in response.json():
logger.info('[OK] Upload OK: %s', filename)
uploaded.append(response.json())
try:
# move files
toDirectory = "/opt/massa/uploaded_mobsf"
shutil.move(fpath,toDirectory)
logger2.info('%s moved successfully',filename)
# end move files
except:
logger2.error('Failed to move %s',filename)
elif response.status_code == 500:
logger.error('500 Internal Server Error')
elif response.status_code == 405:
logger.error('405 Method Not Allowed')
elif response.status_code == 422:
logger.error('422 Unprocessable Entity')
elif response.status_code == 401:
logger.error('401 Unauthorized')
else:
logger.error('Performing Upload: %s', filename)
else:
logger.warning('%s is not an APK file', filename)
logger.info('Running Static Analysis')
# try:
# # delete remaining files
# files = glob.glob('/opt/massa/uploads/*')
# for f in files:
# os.remove(f)
# logger2.info('%s deleted succesfully', f)
#
# except:
# logger2.error('%s failed to delete', f)
files = glob.glob('/opt/massa/uploads/*')
for f in files:
try:
os.remove(f)
logger2.info('%s deleted succesfully', f)
except:
logger2.error('%s failed to delete', f)
for upl in uploaded:
logger.info('Started Static Analysis on: %s', upl['file_name'])
if rescan == '1':
upl['re_scan'] = 1
response = requests.post(
server_url + '/api/v1/scan',
data=upl,
headers={'AUTHORIZATION': apikey})
if response.status_code == 200:
logger.info('[OK] Static Analysis Complete: %s', upl['file_name'])
else:
logger.error('Performing Static Analysis: %s', upl['file_name'])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory',
help='Path to the directory that contains '
'mobile app binary/zipped source code')
parser.add_argument(
'-s', '--ipport', help='IP address and Port number '
'of a running MobSF Server. '
'(ex: 127.0.0.1:8000)')
parser.add_argument(
'-k', '--apikey', help='MobSF REST API Key')
parser.add_argument(
'-r', '--rescan', help='Run a fresh scan. '
'Value can be 1 or 0 (Default: 0)')
args = parser.parse_args()
if args.directory and args.ipport and args.apikey:
server = args.ipport
directory = args.directory
server_url = 'http://' + server
apikey = args.apikey
rescan = args.rescan
if not is_server_up(server_url):
print('MobSF REST API Server is not running at ' + server_url)
print('Exiting!')
exit(0)
# MobSF is running, start scan
start_scan(directory, server_url, apikey, rescan)
else:
parser.print_help()