import io import logging import os import struct from typing import Dict from .extract import extract_file_based_on_header_info, extract_all_files_from_central_directory from .helpers import pretty_print_header, save_to_json, save_data_to_file class EndOfCentralDirectoryRecord: """ A class to provide details about the end of central directory record. """ def __init__(self, signature, number_of_this_disk, disk_where_central_directory_starts, number_of_central_directory_records_on_this_disk, total_number_of_central_directory_records, size_of_central_directory, offset_of_start_of_central_directory, comment_length, comment): self.signature = signature self.number_of_this_disk = number_of_this_disk self.disk_where_central_directory_starts = disk_where_central_directory_starts self.number_of_central_directory_records_on_this_disk = number_of_central_directory_records_on_this_disk self.total_number_of_central_directory_records = total_number_of_central_directory_records self.size_of_central_directory = size_of_central_directory self.offset_of_start_of_central_directory = offset_of_start_of_central_directory self.comment_length = comment_length self.comment = comment @classmethod def parse(cls, apk_file): """ Method to locate the "end of central directory record signature" as the first step of the correct process of reading a ZIP archive. Should be noted that certain APKs do not follow the zip specification and declare multiple "end of central directory records". For this reason the search for the corresponding signature of the eocd starts from the end of the apk. :param apk_file: The already read/loaded data of the APK file e.g. with open('test.apk', 'rb') as apk_file :type apk_file: bytesIO :return: Returns the end of central directory record with all the information available if the corresponding signature is found. If not, then it returns None. :rtype: EndOfCentralDirectoryRecord or None """ chunk_size = 1024 offset = 0 signature_offset = -1 file_size = apk_file.seek(0, 2) while offset < file_size: position = max(0, file_size - offset - chunk_size) apk_file.seek(position) chunk = apk_file.read(chunk_size) if not chunk: break signature_offset = chunk.rfind(b'\x50\x4b\x05\x06') # EOCD signature if signature_offset != -1: eo_central_directory_offset = position + signature_offset break # Found EOCD signature # Adjust offset to overlap by 4 bytes offset += chunk_size - 4 if signature_offset == -1: raise ValueError("End of central directory record (EOCD) signature not found") apk_file.seek(eo_central_directory_offset) signature = apk_file.read(4) number_of_this_disk = struct.unpack(' Dict[str, CentralDirectoryEntry]: """ List of information about the entries in the central directory. :return: returns a dictionary where the keys are the filenames and the values are each an instance of the CentralDirectoryEntry :rtype: dict """ return self.central_directory.entries def namelist(self): """ List of the filenames included in the central directory. :return: returns the list of the filenames :rtype: list """ return [vl for vl in self.central_directory.to_dict()] def extract_all(self, extract_path, apk_name): """ Extracts all the contents of the APK. :param extract_path: where to extract it :type extract_path: str :param apk_name: the name of the apk :type apk_name: str """ output_path = os.path.join(extract_path, apk_name) if not extract_all_files_from_central_directory(self.zip, self.to_dict()["central_directory"], self.to_dict()["local_headers"], output_path): logging.info(f"Extraction successful for: {apk_name}") def print_headers_of_filename(cd_h_of_file, local_header_of_file): """ Prints out the details for both the central directory header and the local file header. Useful for the CLI. :param cd_h_of_file: central directory header of a filename as it may be retrieved from headers_of_filename :type cd_h_of_file: dict :param local_header_of_file: local header dictionary of a filename as it may be retrieved from headers_of_filename :type local_header_of_file: dict """ if not cd_h_of_file or not local_header_of_file: logging.info("Are you sure the filename exists?") return pretty_print_header("CENTRAL DIRECTORY") for k in cd_h_of_file: if k == 'Relative offset of local file header' or k == 'Offset in the central directory header': print(f"{k:40} : {hex(int(cd_h_of_file[k]))} | {cd_h_of_file[k]}") else: print(f"{k:40} : {cd_h_of_file[k]}") pretty_print_header("LOCAL HEADER") for k in local_header_of_file: print(f"{k:40} : {local_header_of_file[k]}") def show_and_save_info_of_headers(entries, apk_name, header_type: str, export: bool, show: bool): """ Print information for each entry for the central directory header and allow to possibly export to JSON. :param entries: The dictionary with all the entries for the central directory :type entries: dict :param apk_name: String with the name of the APK, so it can be used for the export. :type apk_name: str :param header_type: What type of header that is, either central_directory or local, to be used for the export :type header_type: str :param export: Boolean for exporting or not to JSON :type export: bool :param show: Boolean for printing or not the entries :type show: bool """ if show: for entry in entries: pretty_print_header(entry) print(entries[entry]) if export: save_to_json(f"{apk_name}_{header_type}_header.json", entries)