Debian Codegraph @

apkInspector/indicators.py

raw symbols SCIP
1 import io
2 import logging
3 import struct
4
5 from .extract import extract_file_based_on_header_info
6 from .headers import ZipEntry
7 from .axml import ResChunkHeader, StringPoolType, XmlResourceMapType, XmlStartElement, ManifestStruct, ResXMLHeader, \
8 read_remaining
9
10
11 def count_eocd(apk_file):
12 """
13 Counter for the number of time the end of central directory record was found.
14
15 :param apk_file: The APK file e.g. with open('test.apk', 'rb') as apk_file
16 :type apk_file: bytesIO
17 :return: The count of how many times the end of central directory record was found
18 :rtype: int
19 """
20 apk_file.seek(0)
21 content = apk_file.read()
22 return content.count(b'\x50\x4b\x05\x06')
23
24
25 def detect_path_collisions(central_directory_entries):
26 """
27 Detects file/directory path collisions in ZIP entries.
28
29 :param central_directory_entries: Dictionary of central directory entries
30 :type central_directory_entries: dict
31 :return: Count of entries that would cause path collisions
32 :rtype: int
33 """
34 files_set = set()
35 collision_entries = []
36
37 # Sort entries to process files before their potential "subdirectories"
38 sorted_entries = sorted(central_directory_entries.keys(), key=lambda x: x.count('/'))
39
40 for filename in sorted_entries:
41 if not filename:
42 continue
43
44 # Check if any parent path component is already registered as a file
45 path_components = filename.split('/')
46 for i in range(1, len(path_components)):
47 partial_path = '/'.join(path_components[:i])
48 if partial_path in files_set:
49 # Collision detected: trying to use a file as a directory
50 collision_entries.append(filename)
51 break
52 else:
53 # No collision, register this as a file
54 files_set.add(filename)
55
56 return collision_entries
57
58
59 def zip_tampering_indicators(apk_file, strict: bool):
60 """
61 Method to check the for indicators of tampering in the ZIP structure of the APK. These tamperings in the ZIP
62 structure, serve as a method of evasion against static analysis tools.
63
64 :param apk_file: The APK file e.g. with open('test.apk', 'rb') as apk_file
65 :type apk_file: bytesIO
66 :param strict: Whether to be checking strictly or not. Utilizing the application set that was used also for the tests here https://github.com/erev0s/apkInspector/tree/main/tests/top_apps, we tested what kind of indicators would be returned. It turns out that in some cases the local header and the central directory entry for the same file do not have the same values for some keys. So the strict checking was added, to be able to exclude these rare but possible occasions.
67 :type strict: bool
68 :return: Returns a dictionary with the detected indicators.
69 :rtype: dict
70 """
71 zip_tampering_indicators_dict = {}
72 if strict:
73 # This is added as strict as a few legitimate APKs do have it for some reason
74 count = count_eocd(apk_file)
75 if count > 1:
76 zip_tampering_indicators_dict['eocd_count'] = count
77 zipentry_dict = ZipEntry.parse(apk_file).to_dict()
78 empty_keys = any(k == "" or k is None for k in zipentry_dict["central_directory"].keys())
79 if empty_keys:
80 zip_tampering_indicators_dict['empty_keys'] = empty_keys
81 unique_keys = list(zipentry_dict["central_directory"].keys() ^ zipentry_dict["local_headers"].keys())
82 common_keys = list(set(zipentry_dict["central_directory"].keys()) & set(zipentry_dict["local_headers"].keys()))
83 if unique_keys:
84 zip_tampering_indicators_dict['unique_entries'] = unique_keys
85
86 # Check for file/directory collisions
87 collision_count = detect_path_collisions(zipentry_dict["central_directory"])
88 if len(collision_count) > 0:
89 zip_tampering_indicators_dict['path_collisions'] = len(collision_count)
90
91 for key in common_keys:
92 cd_entry = zipentry_dict["central_directory"][key]
93 lh_entry = zipentry_dict["local_headers"][key]
94 temp = {}
95 if cd_entry['compression_method'] not in [0, 8]:
96 temp['central compression method'] = cd_entry['compression_method']
97 if lh_entry['compression_method'] not in [0, 8]:
98 temp['local compression method'] = lh_entry['compression_method']
99 if cd_entry['compression_method'] not in [0, 8] or lh_entry['compression_method'] not in [0, 8]:
100 indicator = \
101 extract_file_based_on_header_info(apk_file, lh_entry, cd_entry)[
102 1]
103 temp['actual compression method'] = indicator
104 df_keys = local_and_central_header_discrepancies(cd_entry, lh_entry, strict)
105 if df_keys:
106 temp['differing headers'] = df_keys
107 if not temp:
108 continue
109 zip_tampering_indicators_dict[key] = temp
110 return zip_tampering_indicators_dict
111
112
113 def local_and_central_header_discrepancies(dict1, dict2, strict: bool):
114 """
115 Checking discrepancies between local header values and central directory values
116
117 :param dict1: the central directory dictionary
118 :type dict1: dict
119 :param dict2: the local headers dictionary
120 :type dict2: dict
121 :param strict: Boolean for strict checking the headers or not
122 :type strict: bool
123 :return: Returns a list with the common keys between the dictionaries that have different values.
124 :rtype: list
125 """
126 common_keys = set(dict1.keys()) & set(dict2.keys())
127 differences = {key: (dict1[key], dict2[key]) for key in common_keys if dict1[key] != dict2[key]}
128 # Display the keys with differing values
129 keys = []
130 for key, values in dict(sorted(differences.items())).items():
131 # strict checking or not: excluding these as they differ often
132 if not strict and key in ['extra_field', 'extra_field_length', 'crc32_of_uncompressed_data', 'compressed_size',
133 'uncompressed_size']:
134 continue
135 keys.append(key)
136 return keys
137
138
139 def process_elements_indicators(file):
140 """
141 It starts processing the remaining chunks **after** the resource map chunk.
142 It also returns whether dummy data have been found between the elements, so it can be reported that the apk employed
143 this evasion technique. The difference between the process_elements method found in the axml module is that in this
144 case it does not take into account the total size of the element as stated in the header, but tries to parse the
145 contents regardless. This means that it will detect any dummy data injected after the actual data.
146
147 :param file: the axml that will be processed
148 :type file: BytesIO
149 :return: Returns all the elements found as their corresponding classes and whether dummy data were found in between.
150 :rtype: set(list, set(bool, bool))
151 """
152 elements = []
153 dummy_data_between_elements = False
154 wrong_end_namespace_size = False
155 unknown_chunk_type = False
156 min_size = 8
157 while True:
158 cur_pos = file.tell()
159 if file.getbuffer().nbytes < cur_pos + min_size:
160 # we reached the end of the file
161 break
162 _type, _header_size, _size = struct.unpack('<HHL', file.read(8))
163 file.seek(cur_pos)
164 if not (min_size <= _header_size <= _size):
165 if _type == 257 and _size < min_size:
166 wrong_end_namespace_size = True
167 file.read(24)
168 continue
169 file.seek(cur_pos + 1)
170 dummy_data_between_elements = True
171 continue
172 res_node = ResXMLHeader.parse(file)
173 if res_node.header is None:
174 break
175 tail = read_remaining(file, res_node.header)
176 raw_chunk = res_node.header.data + res_node.data + tail
177 elem = ManifestStruct.parse_next_header(io.BytesIO(raw_chunk))
178 if isinstance(elem, dict) and "raw" in elem:
179 unknown_chunk_type = True
180 continue
181
182 elements.append(elem)
183 return elements, (dummy_data_between_elements, wrong_end_namespace_size, unknown_chunk_type)
184
185
186 def manifest_tampering_indicators(manifest):
187 """
188 Method to check for indicators of tampering in the AndroidManifest.xml
189
190 :param manifest: The AndroidManifest file to check
191 :type manifest: bytesIO
192 :return: Returns a dictionary with the indicators of tampering for the AndroidManifest
193 :rtype: dict
194 """
195 chunkHeader = ResChunkHeader.parse(manifest)
196 manifest_tampering_indicators_dict = {}
197 if chunkHeader.type != 3:
198 manifest_tampering_indicators_dict['unexpected_starting_signature_of_androidmanifest'] = hex(chunkHeader.type)
199 string_pool = StringPoolType.parse(manifest)
200 if len(string_pool.string_offsets) != string_pool.str_header.string_count:
201 manifest_tampering_indicators_dict['string_pool'] = {'string_count': string_pool.str_header.string_count,
202 'real_string_count': len(string_pool.string_offsets)}
203 XmlResourceMapType.parse(manifest)
204 elements, dummy = process_elements_indicators(manifest)
205 for element in elements:
206 if isinstance(element, XmlStartElement):
207 for attr in element.attributes:
208 if element.attrext[3] != 20:
209 manifest_tampering_indicators_dict['unexpected_attribute_size'] = True
210 if element.attrext[2] != 20:
211 manifest_tampering_indicators_dict['unexpected_attribute_start'] = True
212 if 0 <= attr.name_index < len(string_pool.string_list):
213 if string_pool.string_list[attr.name_index] == "":
214 manifest_tampering_indicators_dict['unexpected_attribute_names'] = True
215 if dummy[0]:
216 manifest_tampering_indicators_dict['invalid_data_between_elements'] = True
217 if dummy[1]:
218 manifest_tampering_indicators_dict['zero_size_header_for_namespace_end_nodes'] = True
219 if dummy[2]:
220 manifest_tampering_indicators_dict['unknown_chunk_type'] = True
221 return manifest_tampering_indicators_dict
222
223
224 def apk_tampering_check(apk_file, strict: bool):
225 """
226 Method to combine the check for tampering in the zip structure and in the AndroidManifest and return the results.
227
228 :param apk_file: The apk file to check
229 :type apk_file: bytesIO
230 :param strict: A boolean to strictly check all fields or not. Suggested value: False
231 :type strict: bool
232 :return: Returns a combined dictionary with the results from the zip_tampering_indicators and the manifest_tampering_indicators
233 :rtype: dict
234 """
235 zip_tampering_indicators_dict = zip_tampering_indicators(apk_file, strict)
236 zipentry = ZipEntry.parse(apk_file)
237 cd_h_of_file = zipentry.get_central_directory_entry_dict("AndroidManifest.xml")
238 local_header_of_file = zipentry.get_local_header_dict("AndroidManifest.xml")
239 manifest = io.BytesIO(extract_file_based_on_header_info(apk_file, local_header_of_file, cd_h_of_file)[0])
240 manifest_tampering_indicators_dict = manifest_tampering_indicators(manifest)
241 return {'zip tampering': zip_tampering_indicators_dict, 'manifest tampering': manifest_tampering_indicators_dict}