| 1 |
import logging |
| 2 |
import zlib |
| 3 |
import os |
| 4 |
import random |
| 5 |
|
| 6 |
|
| 7 |
def extract_file_based_on_header_info(apk_file, local_header_info, central_directory_info): |
| 8 |
""" |
| 9 |
Extracts a single file from the apk_file based on the information provided from the offset and the header_info. |
| 10 |
It takes into account that the compression method provided might not be STORED or DEFLATED! The returned |
| 11 |
'indicator', shows what compression method was used. Besides the standard STORED/DEFLATE it may return |
| 12 |
'DEFLATED_TAMPERED', which means that the compression method found was not DEFLATED(8) but it should have been, |
| 13 |
and 'STORED_TAMPERED' which means that the compression method found was not STORED(0) but should have been. |
| 14 |
|
| 15 |
:param apk_file: The APK file e.g. with open('test.apk', 'rb') as apk_file |
| 16 |
:type apk_file: bytesIO |
| 17 |
:param local_header_info: The local header dictionary info for that specific filename |
| 18 |
:type local_header_info: dict |
| 19 |
:param central_directory_info: The central directory entry for that specific filename |
| 20 |
:type central_directory_info: dict |
| 21 |
:return: Returns the actual extracted data for that file along with an indication of whether a static analysis evasion technique was used or not. |
| 22 |
:rtype: set(bytes, str) |
| 23 |
""" |
| 24 |
filename_length = local_header_info["file_name_length"] |
| 25 |
if local_header_info["compressed_size"] == 0 or local_header_info["uncompressed_size"] == 0: |
| 26 |
compressed_size = central_directory_info["compressed_size"] |
| 27 |
uncompressed_size = central_directory_info["uncompressed_size"] |
| 28 |
else: |
| 29 |
compressed_size = local_header_info["compressed_size"] |
| 30 |
uncompressed_size = local_header_info["uncompressed_size"] |
| 31 |
|
| 32 |
extra_field_length = local_header_info["extra_field_length"] |
| 33 |
compression_method = local_header_info["compression_method"] |
| 34 |
|
| 35 |
local_header_size = 30 |
| 36 |
offset = central_directory_info["relative_offset_of_local_file_header"] |
| 37 |
apk_file.seek(offset + local_header_size + filename_length + extra_field_length) |
| 38 |
if compression_method == 0: |
| 39 |
uncompressed_data = apk_file.read(uncompressed_size) |
| 40 |
extracted_data = uncompressed_data |
| 41 |
indicator = 'STORED' |
| 42 |
elif compression_method == 8: |
| 43 |
compressed_data = apk_file.read(compressed_size) |
| 44 |
|
| 45 |
extracted_data = zlib.decompress(compressed_data, -15) |
| 46 |
indicator = 'DEFLATED' |
| 47 |
elif compressed_size == uncompressed_size: |
| 48 |
compressed_data = apk_file.read(uncompressed_size) |
| 49 |
extracted_data = compressed_data |
| 50 |
indicator = 'STORED_TAMPERED' |
| 51 |
else: |
| 52 |
cur_loc = apk_file.tell() |
| 53 |
try: |
| 54 |
compressed_data = apk_file.read(compressed_size) |
| 55 |
c_obj = zlib.decompressobj(-15) |
| 56 |
extracted_data = c_obj.decompress(compressed_data) |
| 57 |
if not c_obj.eof or c_obj.unused_data or c_obj.unconsumed_tail: |
| 58 |
raise ValueError("Invalid or non-pure deflate") |
| 59 |
indicator = 'DEFLATED_TAMPERED' |
| 60 |
except Exception as e: |
| 61 |
logging.debug(e) |
| 62 |
apk_file.seek(cur_loc) |
| 63 |
compressed_data = apk_file.read(uncompressed_size) |
| 64 |
extracted_data = compressed_data |
| 65 |
indicator = 'STORED_TAMPERED' |
| 66 |
return extracted_data, indicator |
| 67 |
|
| 68 |
|
| 69 |
def extract_all_files_from_central_directory(apk_file, central_directory_entries, local_header_entries, output_dir, retain_collisions=False): |
| 70 |
""" |
| 71 |
Extracts all files from an APK based on the entries detected in the central_directory_entries. |
| 72 |
|
| 73 |
:param apk_file: The APK file e.g. with open('test.apk', 'rb') as apk_file |
| 74 |
:type apk_file: bytesIO |
| 75 |
:param central_directory_entries: The dictionary with all the entries for the central directory |
| 76 |
:type central_directory_entries: dict |
| 77 |
:param local_header_entries: The dictionary with all the local header entries |
| 78 |
:type local_header_entries: dict |
| 79 |
:param output_dir: The output directory where to save the files. |
| 80 |
:type output_dir: str |
| 81 |
:param retain_collisions: If True, rename and retain entries that cause file/directory collisions. If False, skip them. |
| 82 |
:type retain_collisions: bool |
| 83 |
:return: Returns 0 if no errors, 1 if an exception and 2 if the output directory already exists |
| 84 |
:rtype: int |
| 85 |
""" |
| 86 |
try: |
| 87 |
|
| 88 |
if os.path.exists(output_dir): |
| 89 |
print("Extraction aborted. Output directory already exists.") |
| 90 |
return 2 |
| 91 |
|
| 92 |
os.makedirs(output_dir, exist_ok=True) |
| 93 |
|
| 94 |
for filename, cd_header_info in central_directory_entries.items(): |
| 95 |
if not filename: |
| 96 |
|
| 97 |
continue |
| 98 |
|
| 99 |
extracted_data = \ |
| 100 |
extract_file_based_on_header_info(apk_file, local_header_entries[filename], cd_header_info)[0] |
| 101 |
|
| 102 |
|
| 103 |
path_components = filename.split('/') |
| 104 |
modified_filename = filename |
| 105 |
collision_detected = False |
| 106 |
for i in range(1, len(path_components)): |
| 107 |
partial_path = os.path.join(output_dir, '/'.join(path_components[:i])) |
| 108 |
if os.path.exists(partial_path) and not os.path.isdir(partial_path): |
| 109 |
|
| 110 |
collision_detected = True |
| 111 |
if retain_collisions: |
| 112 |
collision_suffix = f"__collision__{random.randint(10000, 99999)}" |
| 113 |
path_components[i-1] += collision_suffix |
| 114 |
modified_filename = '/'.join(path_components) |
| 115 |
logging.warning(f"Collision detected for {filename}, renaming to {modified_filename}") |
| 116 |
else: |
| 117 |
logging.warning(f"Collision detected for {filename}, skipping entry") |
| 118 |
break |
| 119 |
|
| 120 |
|
| 121 |
if collision_detected and not retain_collisions: |
| 122 |
continue |
| 123 |
|
| 124 |
|
| 125 |
output_path = os.path.join(output_dir, modified_filename) |
| 126 |
|
| 127 |
os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| 128 |
|
| 129 |
with open(output_path, 'wb') as output_file: |
| 130 |
output_file.write(extracted_data) |
| 131 |
return 0 |
| 132 |
except Exception as e: |
| 133 |
print(f"Error extracting files: {e}") |
| 134 |
return 1 |