-
Notifications
You must be signed in to change notification settings - Fork 6
/
DISintegrity.py
401 lines (338 loc) · 16.4 KB
/
DISintegrity.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
import os
import re
import shutil
import subprocess
import webbrowser
import argparse
from jinja2 import Template
from tqdm import tqdm
root_detection_keywords = [
("SafetyNet", "Google Play SafetyNet"), # Google Play SafetyNet API for checking device integrity
("safetynet", "Google Play SafetyNet"), # Same as above, but with lowercase
("Safety Detect", "Huawei Safety Detect"), # Huawei's safety detection API for detecting rooted devices
("safetydetect", "Huawei Safety Detect"), # Same as above, but with lowercase
("RootBeer", "RootBeer"), # RootBeer library for detecting rooted devices
("rootbeer", "RootBeer"), # Same as above, but with lowercase
("isDeviceRooted", "Proprietary"), # Custom code to check if device is rooted
("isRooted", "Proprietary"), # Same as above, but shorter
("RootChecker", "Proprietary"), # Custom code for checking if device is rooted
("checkRoot", "Proprietary"), # Same as above, but shorter
("detectRoot", "Proprietary"), # Custom code for detecting rooted devices
("detectTamper", "Proprietary"), # Custom code for detecting if app has been tampered with
("tamperDetection", "Proprietary"), # Custom code for detecting if app has been tampered with
("detectEmulator", "Proprietary"), # Custom code for detecting if app is running on an emulator
("checkEmulator", "Proprietary"), # Same as above, but shorter
("isEmulator", "Proprietary"), # Same as above, but shorter
("rootCheck", "Proprietary"), # Custom code for checking if device is rooted
("rootDetection", "Proprietary"), # Custom code for detecting rooted devices
("rootedDevice", "Proprietary"), # Custom code for checking if device is rooted
("isDeviceCompromised", "Proprietary"), # Custom code for checking if device is compromised
("rootConfirmation", "Proprietary"), # Custom code for confirming if device is rooted
("rootStatus", "Proprietary"), # Custom code for checking root status
("isDeviceJailbroken", "Proprietary"), # Custom code for checking if device is jailbroken
("jailbreakDetection", "Proprietary"), # Custom code for detecting jailbroken devices
("checkJailbreak", "Proprietary"), # Same as above, but shorter
("detectJailbreak", "Proprietary"), # Same as above, but shorter
("isDeviceSecure", "Proprietary"), # Custom code for checking device security
("deviceIntegrity", "Proprietary"), # Custom code for checking device integrity
("integrityCheck", "Proprietary"), # Custom code for checking device integrity
("systemIntegrity", "Proprietary"), # Custom code for checking system integrity
("suBinary", "Proprietary"), # Custom code for checking if su binary is installed
("superuser", "Proprietary"), # Custom code for checking if Superuser app is installed
("magisk", "Magisk"), # Magisk root management tool
("MagiskHide", "Magisk"), # Magisk feature for hiding root from apps
("magiskhide", "Magisk"), # Magisk feature for hiding root from apps
("deviceRootStatus", "Proprietary"), # Custom code for checking device root status
("rootScanner", "Proprietary"), # Custom code for scanning device for root
("rootAnalyzer", "Proprietary"), # Custom code for analyzing device for root
("rootAssessment", "Proprietary"), # Custom code for assessing device for root
("rootGuard", "Proprietary"), # Custom code for guarding against root access
("rootValidator", "Proprietary"), # Custom code for validating root status
("jailbreakStatus", "Proprietary"), # Custom code for checking jailbreak status
("jailbreakCheck", "Proprietary"), # Custom code for checking if device is jailbroken
("jailbreakScanner", "Proprietary"), # Custom code for scanning device for jailbreak
("jailbreakGuard", "Proprietary"), # Custom code for guarding against jailbreak
("isRootPresent", "Proprietary"), # Custom code for checking if root is present
("rootPresence", "Proprietary"), # Custom code for checking root presence
("rootVerifier", "Proprietary"), # Custom code for verifying root status
("jailbreakVerifier", "Proprietary"), # Custom code for verifying jailbreak status
("rootRisk", "Proprietary"), # Custom code for assessing risk of root access
("jailbreakRisk", "Proprietary"), # Custom code for assessing risk of jailbreak
("rootProber", "Proprietary"), # Custom code for probing device for root
("rootTest", "Proprietary"), # Custom code for testing if device is rooted
("jailbreakTest", "Proprietary"), # Custom code for testing if device is jailbroken
("rootDetectionCheck", "Proprietary"), # Custom code for checking if root is detected
("rootcloak", "Proprietary"), # Custom code for cloaking root from apps
("rootcloakplus", "Proprietary"), # Custom code for cloaking root from apps
("daemonsu", "Proprietary"), # Custom code for managing su binary
("jailbreakDetectionCheck", "Proprietary"), # Custom code for checking if jailbreak is detected
]
def get_strings_from_binary(binary_file):
# Define a regular expression to match printable ASCII characters
printable_regex = re.compile(rb'[\x20-\x7E]{5,}')
# Read the binary file into memory
with open(binary_file, 'rb') as f:
binary_data = f.read()
# Search for printable strings in the binary data using the regular expression
printable_strings = printable_regex.findall(binary_data)
return [s.decode('ascii') for s in printable_strings]
def is_subpath(subpath, path):
'''
Simple function to identify if one path is a subpath of anouther. Used for only checking directories that are
part of the class path.
:return: boolean (True/ False)
'''
subpath = os.path.normpath(subpath)
path = os.path.normpath(path)
# Split subpath and path into components
subpath_parts = subpath.split(os.sep)
path_parts = path.split(os.sep)
return any(
path_parts[i : i + len(subpath_parts)] == subpath_parts
for i in range(len(path_parts) - len(subpath_parts) + 1)
)
def extract_apk(apk_file_path, output_dir, apk_tool_executable):
"""Use apktool to disassemble the APK file."""
print(f"Extracting APK at '{apk_file_path}'. This may take some time...")
if apk_tool_executable.endswith(".jar"):
apk_tool_executable = f"{apk_tool_executable}"
with subprocess.Popen(["java", "-jar", apk_tool_executable, "d", apk_file_path, "-o", output_dir, "-f"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) as process:
stdout, stderr = process.communicate(input="\n")
if process.returncode != 0:
print("An error occurred while running apktool for APK:")
print(stderr)
exit(1)
def check_apktool_on_path():
"""Check if apktool is on the path and return the executable name."""
if shutil.which("apktool.bat"):
return "apktool.bat"
elif shutil.which("apktool.sh"):
return "apktool.sh"
elif shutil.which("apktool"):
return "apktool"
else:
return None
def get_smali_files(apk_dir, allow_path):
"""Get a list of all SMALI files in the disassembled APK directory."""
smali_files = []
file_to_path_dict = {}
for dirpath, dirnames, filenames in tqdm(os.walk(apk_dir), desc="Finding SMALI files"):
if is_subpath(allow_path, dirpath):
for filename in filenames:
if filename.endswith(".smali"):
smali_files.append(os.path.join(dirpath, filename))
file_to_path_dict[filename] = dirpath
return smali_files, file_to_path_dict
def search_for_keywords(file_path, keywords):
results = []
with open(file_path, "r") as f:
content = f.readlines()
for i, line in enumerate(content):
results.extend(
(i + 1, line.strip(), keyword, check_type)
for keyword, check_type in keywords
if keyword in line
)
return results
def search_smali_files(smali_files, keywords):
detected_files = []
for smali_file in smali_files:
if keyword_results := search_for_keywords(smali_file, keywords):
detected_files.append((smali_file, keyword_results))
return detected_files
def search_binary_files(apk_dir, keywords):
detected_files = []
for root, dirs, files in os.walk(apk_dir):
for file in files:
if file.endswith(('.so', '.dat')):
file_path = os.path.join(root, file)
with open(file_path, "rb") as f:
content = f.read()
for keyword, check_type in keywords:
if keyword.encode() in content:
detected_files.append((file_path, keyword, check_type))
break
return detected_files
def create_html_file(detected_smali_files, detected_binary_files, output_dir):
template_str = '''
<!DOCTYPE html>
<html>
<head>
<title>DIS{integrity} - Root and Tamper Detection Checks</title>
<style>
.codeblock {
background-color: #f0f0f0;
padding: 10px;
border-radius: 5px;
margin: 5px;
}
.codeblock pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
.content {
display: none;
}
</style>
<script>
function toggle_visibility(content_id) {
let content = document.getElementById(content_id);
if (content.style.display === 'none') {
content.style.display = 'block';
} else {
content.style.display = 'none';
}
}
window.addEventListener('load', () => {
const clickableItems = document.querySelectorAll('.clickable');
clickableItems.forEach(item => {
const contentId = item.dataset.contentId;
const content = document.getElementById(contentId);
if (content.style.display === 'block') {
item.classList.add('active');
}
item.addEventListener('click', () => {
toggle_visibility(contentId);
item.classList.toggle('active');
});
});
});
</script>
<style>
.clickable {
cursor: pointer;
}
.clickable.active {
font-weight: bold;
}
.content.binary {
display: block;
}
</style>
</head>
<body style="font-family: Arial, sans-serif;">
<h1>DIS{integrity} - Root and Tamper Detection Checks</h1>
<h2>In SMALI files:</h2>
<ul>
{% for file, results in detected_smali_files.items() %}
<li>
<h3 class="clickable" data-content-id="{{ loop.index }}_content">{{ file }}</h3>
<div id="{{ loop.index }}_content" class="content">
{% for line_number, line, keyword, check_type, function_code in results %}
<div>
<p><strong>Keyword:</strong> {{ keyword }}<br><strong>Check Type:</strong> {{ check_type }}</p>
<p>Line {{ line_number }}: {{ line }}</p>
<div class="codeblock">
<pre>{{ function_code }}</pre>
</div>
</div>
{% endfor %}
</div>
</li>
{% endfor %}
</ul>
<h2>In binary files:</h2>
{% if detected_binary_files %}
<ul>
{% for file, keywords in detected_binary_files.items() %}
{% if keywords %}
<li>
<h3 class="clickable active" data-content-id="{{ loop.index }}_content">{{ file }}</h3>
<div id="{{ loop.index }}_content" class="content binary">
{% for keyword, (count, check_type) in keywords.items() %}
<div>
<p><strong>Keyword:</strong> {{ keyword }}<br><strong>Check Type:</strong> {{ check_type }}<br><strong>Match count:</strong> {{ count }}</p>
</div>
{% endfor %}
</div>
</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>No detections in binary files.</p>
{% endif %}
</body>
</html>
'''
template = Template(template_str)
html = template.render(detected_smali_files=detected_smali_files, detected_binary_files=detected_binary_files)
with open(os.path.join(output_dir, 'output.html'), 'w', encoding='utf-8') as f:
f.write(html)
webbrowser.open_new_tab(os.path.join(output_dir, 'output.html'))
print(f"Output file created at {os.path.join(output_dir, 'output.html')}")
def detect_checks_in_smali_files(file_paths, keywords):
detected_smali_files = {}
for file_path in tqdm(file_paths, desc="Searching SMALI files"):
with open(file_path, encoding='utf-8') as file:
lines = file.readlines()
current_function_code = []
in_function = False
for line_number, line in enumerate(lines, start=1):
line = line.strip()
if line.startswith(".method"):
in_function = True
current_function_code = [line]
elif line.startswith(".end method"):
in_function = False
current_function_code.append(line)
if in_function:
current_function_code.append(line)
for keyword, check_type in keywords:
if keyword in line:
if file_path not in detected_smali_files:
detected_smali_files[file_path] = []
detected_smali_files[file_path].append(
(line_number, line, keyword, check_type, "\n".join(current_function_code))
)
return detected_smali_files
def detect_checks_in_binary_files(binary_files, keywords):
detected_binary_files = {}
for binary_file in tqdm(binary_files, desc="Searching binary files"):
if binary_file.endswith(".smali") or binary_file.endswith(".html") or binary_file.endswith(".txt"):
continue
strings = get_strings_from_binary(binary_file)
file_keywords = {}
for keyword, check_type in keywords:
count = sum(keyword in string_in_binary for string_in_binary in strings)
if count > 0:
file_keywords[keyword] = (count, check_type)
if file_keywords:
detected_binary_files[binary_file] = file_keywords
return detected_binary_files
def main(args):
apk_tool_executable = args.apktool
apk_file_path = args.apk_file_path
output_dir = args.output_dir
if apk_file_path is None:
raise Exception("APK Path required, use '-apk'.")
if not output_dir:
output_dir = os.path.splitext(os.path.basename(apk_file_path))[0]
if not apk_tool_executable:
apk_tool_executable = check_apktool_on_path()
if not apk_tool_executable:
print("Apktool not found. Please provide the path to the apktool executable using --apktool.")
exit(1)
extract_apk(apk_file_path, output_dir, apk_tool_executable)
smali_files, file_to_path_dict = get_smali_files(output_dir, "smali")
# Search for checks in SMALI files
detected_smali_files = detect_checks_in_smali_files(smali_files, root_detection_keywords)
# Search for checks in binary files
binary_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(output_dir) for f in filenames]
detected_binary_files = detect_checks_in_binary_files(binary_files, root_detection_keywords)
# Print the results to the console
#print_results(detected_smali_files, detected_binary_files)
# Create the HTML file
create_html_file(detected_smali_files,detected_binary_files, output_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Detect root checks in Android APK files')
parser.add_argument("-apk",'--apk_file_path', metavar='APK_FILE_PATH', type=str, help='the path to the APK file to analyze')
parser.add_argument('-o', '--output-dir', metavar='OUTPUT_DIR', type=str,
help='the output directory to store the analysis results', required=False)
parser.add_argument('--apktool', metavar='APKTOOL', type=str, help='the path to the apktool executable', required=False)
args = parser.parse_args()
main(args)