-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmenu.py
399 lines (354 loc) · 16.6 KB
/
menu.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
#!/usr/bin/env python
# Menu of the BIFUZ project.
#
# Copyright (C) 2015 Intel Corporation
# Author: Andreea Brindusa Proca <andreea.brindusa.proca@intel.com>
# Author: Razvan-Costin Ionescu <razvan.ionescu@intel.com>
# Author: Cristina Stefania Popescu <cristina.popescu@intel.com>
#
# Licensed under the MIT license, see COPYING.MIT for details
import os
import re
from intent_bifuz import *
from broadcast_bifuz import *
from common import *
from time import time
import random
from commands import *
import fileinput
import sys
def replaceLine(file,linestart,replaceline):
for line in fileinput.input(file, inplace=1):
if linestart in line:
line = line.replace(line,replaceline)
sys.stdout.write(line)
def get_root_path(intents_file):
'''
Get the root path of the intent file.
Used for running intents from the seed files.
'''
if intents_file[-1] == '/':
intents_file = intents_file[:-1]
intents_file = intents_file[:intents_file.rfind('/')]
return intents_file
def get_intent_type(generated_intents_file):
'''
Verify if the seed file contains fuzzed intents or broadcast intents.
Used for running intents from the seed fiels.
'''
if not os.path.isfile(generated_intents_file):
print "This file does not exist: %s" % (generated_intents_file)
return False
ip = ''
root_path = get_root_path(generated_intents_file)
with open(generated_intents_file, 'r') as f:
intent = f.readline()
#regex to be reviewed
try:
ip_r = re.search("adb -s ([^ ]+) .*", intent)
except:
ip = ip_r.group(1)
#quick fix until regex is reviewed for setting the IP
ip = str(intent).split(" ")[2]
if intent.startswith('adb'):
if "-a" in intent:
start_intent_fuzzer(ip, root_path, generated_intents_file)
else:
start_broadcast_fuzzer(ip, root_path, generated_intents_file)
return True
def print_menu():
os.system("clear")
k = 15
print("\n")
print((k - 4) * " " + (2 * k + 2) * "=")
print(k * " " + "### # #### # # ####")
print(k * " " + "# # # # # # ##")
print(k * " " + "### # #### # # ## ")
print(k * " " + "# # # # # # # ")
print(k * " " + "### # # #### ####")
print((k - 4) * " " + (2 * k + 2) * "=")
print("\n\n")
print(k / 2 * " " + "Select one option from below\n")
print(k / 2 * " " + "1. Select Devices Under Test")
print(k / 2 * " " + "2. Generate Broadcast Intent calls for the DUT(s)")
print(k / 2 * " " + "3. Generate Fuzzed Intent calls")
print(k / 2 * " " + "4. Generate a delta report between 2 \
fuzzing sessions")
print(k / 2 * " " + "5. Run existing generated intents from file")
print(k / 2 * " " + "6. SQL injections for specific apk.")
print(k / 2 * " " + "7. (Future) Generate apks for specific Intent calls")
print(k / 2 * " " + "8. Buffer overflow against Activity Manager - requires userdebug image")
print(k / 2 * " " + "9. (WIP) Smart fuzzing - using a template - test gms package")
print(k / 2 * " " + "Q. Quit")
print("\n\n")
if __name__ == '__main__':
print_menu()
choice = str(raw_input("Insert your choice: "))
loop = True
devices_list = []
while loop:
#option 1
if (choice == "1"):
print("\nYou have selected option 1. Select Devices Under Test")
devices_list = get_devices_list()
if not devices_list:
print "*ERROR* unavailable devices"
loop = False
continue
for i in range(len(devices_list)):
print str(i + 1) + ". " + devices_list[i]
duts = str(raw_input("Select the DUT number(s) separated by \
comma or type 'all': "))
for d in duts.split(','):
if d.isdigit():
duts_list = re.split(r'[,. ]+', duts)
devices_list = [devices_list[int(x) - 1] \
for x in duts_list if int(x) > 0 \
and int(x) <= len(devices_list)]
if len(devices_list) > 0:
print ("Selected DUT(s): " + ', '.join(devices_list))
choice = str(raw_input("Insert your choice: "))
#option 2
elif (choice == "2"):
if len(devices_list) == 0:
devices_list = get_devices_list()
if devices_list is not False:
devices_list = [devices_list[0]]
print("\nGenerate broadcast intent calls for the \
following DUT(s): " + ', '.join(devices_list) \
if devices_list else 'Stop. Unavailable DUT')
if not devices_list:
loop = False
continue
packages = str(raw_input("Insert the packages wanted \
or type 'all' for all packages: "))
if not packages:
print_menu()
else:
generate_broadcast_intent(devices_list, packages.strip())
loop = False
#option 3
elif (choice == "3"):
if len(devices_list) == 0:
devices_list = get_devices_list()
if devices_list is not False:
devices_list = [devices_list[0]]
print("\nGenerate fuzzed intent calls \
for the following DUT(s): " + \
''.join(devices_list[0]) if devices_list \
else 'Stop. Unavailable DUT')
if not devices_list:
loop = False
continue
packages = str(raw_input("Insert the wanted packages \
or type 'all' for all packages: "))
if not packages:
print_menu()
else:
generate_fuzzed_intent(devices_list, packages.strip())
loop = False
#option 4
elif (choice == "4"):
print("\nYou have selected option 4. Generate a delta report\
between 2 fuzzing sessions")
session_one = str(raw_input("Insert the absolute path \
for session one: "))
session_two = str(raw_input("Insert the absolute path \
for session two: "))
# testing reasons - to be deleted
#session_one = '/home/andreeab/negative/bifuz/LOGS_6173B162_0115_17-13_broadcast'
#session_two = '/home/andreeab/negative/bifuz/LOGS_6173B162_0115_17-34_broadcast'
if not session_one or not session_two:
continue
delta_reports(session_one.strip(), session_two.strip())
loop = False
#option 5
elif (choice == "5"):
print("\nYou have selected option 5. Run existing generated \
intents from file.")
intents_file = str(raw_input("Insert the absolute path of the \
file containing the intents: "))
#for testing reasons, to be deleted
#intents_file = "/home/andreeab/negative/bifuz/LOGS_6173B162_0126_19-37_broadcast/all_broadcasts_6173B162.sh"
if not intents_file:
print_menu()
else:
get_intent_type(intents_file.strip())
loop = False
#option 6
elif (choice == "6"):
print("\nYou have selected option 6. SQL injections for specific apk.")
if len(devices_list) == 0:
devices_list = get_devices_list()
if devices_list is not False:
devices_list = [devices_list[0]]
print("\nGenerate sql injection for specific apk: " + ', '.join(devices_list) if devices_list else 'Stop. Unavailable DUT')
if not devices_list:
loop = False
continue
packages = str(raw_input("Insert the wanted package "))
if not packages:
print_menu()
else:
#get all contents providers
#com.mwr.example.sieve-1
contents=get_apks(devices_list, packages.strip())
print "CONTENTS"
print contents
table=contents[0].split("/")
table_path_name=table[len(table)-1]
print "\n"+"PROJECTION" +"\n"
projection_query="shell content query --uri " + contents[0] + " --projection " + '"' "* FROM sqlite_master WHERE type='table';--" + '"'
print "adb " + projection_query + "\n"
print run_inadb(devices_list[0],projection_query) + "\n"
query="shell content query --uri " + contents[0] + " --projection '* FROM "+table_path_name +";--'"
print run_inadb(devices_list[0],query)+ "\n"
print "TRY INSERT"+"\n"
insert=insert_query(devices_list[0],contents[0],table_path_name)
if insert:
print "INSERT VALUE FAILED" + "\n"
else:
print "INSERT VALUE SUCCEEDED" + "\n"
query="shell content query --uri " + contents[0] + " --projection '* FROM "+table_path_name +";--'"
print run_inadb(devices_list[0],query)+"\n"
print "TRY DELETE"+"\n"
delete=delete_query(devices_list[0],contents[0],table_path_name)
if delete:
print "DELETE TABLE SUCCEEDED" + "\n"
else:
print "DELETE TABLE FAILED" + "\n"
loop = False
#option 7
elif (choice == "7"):
print("\nYou have selected option 7.Generate apks for specific Intent calls")
#give the test folder with the seed files with intents
seed_folder= str(raw_input("Insert the absolute path for the log folder: "))
if not seed_folder:
print_menu()
else:
devices_list = get_devices_list()
if not devices_list:
print "*ERROR* unavailable devices"
loop = False
continue
#change path for buidlozer spec
sdk=getoutput('printenv ANDROIDSDK')
ndk=getoutput('printenv ANDROIDNDK')
replaceLine('kivy-android/buildozer.spec','android.ndk_path','android.ndk_path = '+ ndk + "\n")
replaceLine('kivy-android/buildozer.spec','android.sdk_path','android.sdk_path = '+ sdk + "\n")
pyforandroid_dir=getoutput("find /home -type d -name python-for-android")
paths=pyforandroid_dir.split('\n')
for line in paths:
if (line.find('denied')==-1):
replaceLine('kivy-android/buildozer.spec','android.p4a_dir','android.p4a_dir = '+ line + "\n")
print "Settings for Buildozer are ready"
#put seed folder on device
copy_txts_file_command='push ' + 'txts' +' /data/local/tmp/txts/'
print copy_txts_file_command
print run_inadb(devices_list[0], copy_txts_file_command)
copy_file_command='push ' + seed_folder +' /sdcard/'
print copy_file_command
print run_inadb(devices_list[0], copy_file_command)
#uninstall old apk if exists
uninstall_command='shell pm uninstall -k ' +'org.test.bifuz'
print run_inadb(devices_list[0], uninstall_command)
#install apk
install_command='-d install ' +'Bifuz-1.0.0-debug.apk'
print run_inadb(devices_list[0], install_command)
#start Bifuz
run_command='shell am start -n org.test.bifuz/org.renpy.android.PythonActivity'
print run_inadb(devices_list[0], run_command)
loop = False
#option 8
elif (choice == "8"):
#buffer overflow against Activity Manager run on the first device in the list
if len(devices_list) == 0:
devices_list = get_devices_list()
if devices_list is not False:
devices_list = [devices_list[0]]
repetitions = str(raw_input("How many large intents would like to send? (enter an int larger than 0) "))
ip = str(devices_list[0])
for i in range(int(repetitions)):
buffer_overflow(ip)
loop = False
#option 9
elif (choice == "9"):
print ("\nYou have selected option 9")
#smart fuzzing - based on templates
if len(devices_list) == 0:
devices_list = get_devices_list()
if devices_list is not False:
devices_list = [devices_list[0]]
#WIP - IP is set for the first connected device
ip = str(devices_list[0])
template_edited = str(raw_input("Do you have created a template file? [y/n]: "))
if str(template_edited) in ['y','Y']:
pass
else:
os.system("python create_templates.py")
#to be implemented - test for multiple packages
'''
test_pack = str(raw_input("Insert testing package: "))
list_test_pack = []
look_for_test_pack = getoutput("adb -s %s shell pm list packages | grep %s"%(ip,test_pack))
for tp in look_for_test_pack.strip().split("package:"):
if tp!="":
list_test_pack.append(tp.strip())
'''
#test_pack - activity to be tested - for testing purposes we use all gms Activities
with open(os.getcwd()+"/txts/gms_activities.txt","r") as f:
gms_acts = f.readlines()
template_path = str(raw_input("Insert full path to the template file(s): "))
if not (os.path.isdir("intents_from_%s"%(template_path.split("/")[-2]))):
os.mkdir("intents_from_%s"%(template_path.split("/")[-2]))
tem = getoutput("ls %s/*.tem"%template_path)
list_tem_files = tem.split()
i=0
for tem_file in list_tem_files:
fuzzy_items = parse_template(tem_file)
for test_p in gms_acts:
test_pack = test_p.strip()
fuzzy_intents = parse_string_for_lists("am start -n "+test_pack+" "+str(fuzzy_items),ip)
os.chdir("intents_from_%s"%(template_path.split("/")[-2]))
intent_from_template_folder = str(random.randint(1,10000)+i)+"_"+test_pack.split("/")[0]+"_"+test_pack.split(".")[-1]+"_"+tem_file.split("/")[-1].split(".tem")[0]
while (os.path.isdir(intent_from_template_folder)):
intent_from_template_folder = str(random.randint(1,10000)+i)+"_"+test_pack.split("/")[0]+"_"+test_pack.split(".")[-1]+"_"+tem_file.split("/")[-1].split(".tem")[0]
i+=1
previous_location = os.getcwd()
os.mkdir(intent_from_template_folder)
os.chdir(intent_from_template_folder)
for i in range(len(fuzzy_intents)):
filename = "intent_from_template"+str(i)
with open(filename,"w") as f:
f.write("adb -s %s shell "%(ip)+fuzzy_intents[i])
os.system("chmod 777 "+filename)
#os.system("adb -s %s push "% (ip)+" "+filename+" /data/data/")
# os.system("adb -s %s push "% (ip)+" "+filename+" /sdcard/")
#os.system("adb -s %s shell sh /data/data/%s"%(ip,filename))
# os.system("adb -s %s shell sh /sdcard/%s"%(ip,filename))
# os.system("adb -s %s shell log -p f -t %s" % (ip, str(fuzzy_intents[i])))
os.chdir(previous_location)
os.chdir("..")
aggregate_path=os.getcwd()+"/intents_from_%s"%(template_path.split("/")[-2])+"/"
#os.system("echo %s"%aggregate_path)
os.system('for i in `find %s -name "intent_from_template*"`; do cat $i ; echo ""; done >> %s/intents_all.sh'%(aggregate_path,aggregate_path))
#start_intent_fuzzer(ip, log_dir, generated_intents_file=None):
run_intents_or_not = str(raw_input("Do you want to run the generated intents? [y/n] "))
if str(run_intents_or_not) in ['y','Y']:
print "Running the intents from file: "+str(aggregate_path)+"intents_all.sh"
print "IP "+str(ip)
logging_dir = str(aggregate_path)+"LOGS"
os.mkdir(logging_dir)
print "log_dir - "+logging_dir
start_intent_fuzzer(ip, logging_dir, str(aggregate_path)+"intents_all.sh")
else:
continue
loop = False
#quit
elif (str(choice) in ['q', 'Q']):
print("\nThank you for using BIFUZ!")
loop = False
elif (choice != ""):
print("\nYour option is invalid. Please type any number \
between 1 and 9, or Q for Quit")
choice = str(raw_input("Insert your choice: "))