import io import logging import struct import random from .extract import extract_file_based_on_header_info from .headers import ZipEntry from .helpers import escape_xml_entities logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d -> %(funcName)s : %(message)s' ) class ResChunkHeader: """ Chunk header used throughout the axml. This header is essential as it contains information about the header size but also the total size of the chunk the header belongs to. """ def __init__(self, header_type, header_size, total_size, data): self.type = header_type self.header_size = header_size self.total_size = total_size self.data = data @classmethod def parse(cls, file): """ Read the header type (2 bytes), header size (2 bytes), and entry size (4 bytes). :param file: the xml file e.g. with open('/path/AndroidManifest.xml', 'rb') as file :type file: bytesIO :return: Returns an instance of itself :rtype: ResChunkHeader """ header_data = file.read(8) if len(header_data) < 8: # End of file return None header_type, header_size, total_size = struct.unpack(' end_stringpool_offset: return "" # TODO:a check for non null-terminated strings should be here as well content = file.read(real_length * 2).decode('utf-16le') else: # Handle UTF-8 encoded strings u16len = struct.unpack('B', file.read(1))[0] file.read(1) u8len = u16len content = file.read(u8len).decode('utf-8', errors='replace') # TODO: fixup is needed here as well, like for the utf16 case return content @classmethod def read_strings(cls, file, string_offsets, strings_start, is_utf8): """ Gets the actual strings based on the offsets retrieved from read_string_offsets(). :param file: the xml file right after the string pool offsets have been read :type file: bytesIO :param string_offsets: see -> read_string_offsets() :type string_offsets: list :param strings_start: the offset at which the string data starts :type strings_start: int :param is_utf8: boolean to check if a utf8 string is expected :type is_utf8: bool :return: Returns a list of the string data :rtype: list """ strings = [] for offset in string_offsets: # Calculate the absolute offset within the string data +8 for the file header absolute_offset = strings_start + offset + 8 # TODO: update this to get the file header size # Move the file pointer to the start of the string file.seek(absolute_offset) # Read the length of the string (in bytes) content = cls.decode_stringpool_mixed_string(file, is_utf8, strings_start + string_offsets[-1]) strings.append(content) return strings @classmethod def read_string(cls, file, string_offset, strings_start, is_utf8, end_stringpool_offset): """ Read a string from the string pool when the offset of it is known already. :param file: the string pool data parsed as bytes :type file: io.bytesIO :param string_offset: the offset at which the string is located in the string pool :type string_offset: int :param strings_start: the offset at which the string data starts :type strings_start: int :param is_utf8: boolean to check if a utf8 string is expected :type is_utf8: bool :param end_stringpool_offset: the offset at which the string pool ends :type end_stringpool_offset: int :return: Returns the string or None :rtype: str or None """ absolute_offset = strings_start + string_offset - 28 if file.getbuffer().nbytes < absolute_offset: return None file.seek(absolute_offset) string = cls.decode_stringpool_mixed_string(file, is_utf8, end_stringpool_offset) return string @classmethod def get_string_from_pool(cls, position, string_pool_data, end_stringpool_offset, strings_start, is_utf8): """ Retrieve a single string from the String Pool, given its position. It first gets the correct offset of the string and then reads the string. :param position: The position of the string to be retrieved :type position: int :param string_pool_data: the string pool data parsed as bytes :type string_pool_data: io.BytesIO :param end_stringpool_offset: the offset at which the string pool ends :type end_stringpool_offset: int :param strings_start: the offset at which the string data starts :type strings_start: int :param is_utf8: boolean to check if a utf8 string is expected :type is_utf8: bool :return: Returns the string or None :rtype: str or None """ try: string_offset = cls.read_string_offset(string_pool_data, position) if string_offset is None: return None return cls.read_string(string_pool_data, string_offset, strings_start, is_utf8, end_stringpool_offset) except Exception as e: logging.exception(f"Exception while retrieving string from pool: {e}") return None @classmethod def parse_lite(cls, file): """ A 'lite' parser that gets the header and then reads the rest of the chunk as a blob of bytes. :param file: the AndroidManifest.xml file :type file: bytesIO :return: returns the header and the chunk data :rtype: tuple(ResStringPoolHeader, bytes) """ ResStringPool_header = ResStringPoolHeader.parse(file) string_pool_data = read_remaining(file, ResStringPool_header.header) while True: # read any null bytes remaining cur_pos = file.tell() if file.read(2) == b'\x80\x01': file.seek(cur_pos) break file.seek(cur_pos) file.read(1) return ResStringPool_header, string_pool_data @classmethod def parse(cls, file): """ Parse the string pool to acquire the strings used within the axml. :param file: the xml file right after the file header is read :type file: bytesIO :return: Returns an instance of itself :rtype: StringPoolType """ string_pool_header = ResStringPoolHeader.parse(file) string_pool_start = file.tell() size_of_strings_offsets = string_pool_header.strings_start - 28 # it should be divisible by 4, as 4 bytes are per offset, so we can get accurately the # of strings num_of_strings = size_of_strings_offsets // 4 if not (size_of_strings_offsets / 4).is_integer(): logging.warning(f"The number of strings in the string pool is not a integer number.") string_offsets = cls.read_string_offsets(file, num_of_strings, string_pool_header.strings_start + 8) is_utf8 = bool(string_pool_header.flags & (1 << 8)) string_list = cls.read_strings(file, string_offsets, string_pool_header.strings_start, is_utf8) while True: # read any null bytes remaining cur_pos = file.tell() if file.read(2) == b'\x80\x01': file.seek(cur_pos) break file.seek(cur_pos) file.read(1) if file.getbuffer().nbytes < file.tell() + 8: raise ValueError("Resource Map header was not detected.") string_pool_end = file.tell() file.seek(string_pool_start) string_pool_data = file.read(string_pool_end - string_pool_start) return cls( string_pool_header, string_offsets, string_list, string_pool_data ) class XmlResourceMapType: """ Resource map class, with the header and the resource IDs. """ def __init__(self, header, resids, resids_data): self.header = header self.resids = resids self.data = resids_data @classmethod def parse_lite(cls, file): """ A 'lite' parser that gets the header and then reads the rest of the chunk as a blob of bytes. :param file: the AndroidManifest.xml file :type file: bytesIO :return: returns the header and the chunk data :rtype: tuple(ResChunkHeader, bytes) """ resource_map_header = ResChunkHeader.parse(file) resource_map_data = read_remaining(file, resource_map_header) return resource_map_header, resource_map_data @classmethod def parse(cls, file): """ Parse the resource map and get the resource IDs. :param file: the xml file right after the string pool is read :type file: bytesIO :return: Returns an instance of itself :rtype: XmlResourceMapType """ header = ResChunkHeader.parse(file) num_resids = (header.total_size - header.header_size) // 4 resids_data = file.read(num_resids * 4) chunks = [resids_data[i:i + 4] for i in range(0, len(resids_data), 4)] resids = [struct.unpack(' 8: header_data = file.read(header.header_size - 8) return cls(header, header_data) class XmlStartNamespace: """ The actual start of the xml, after this the elements of the xml will be found. """ def __init__(self, header: ResXMLHeader, ext, ext_data): self.header = header self.ext = ext # [prefix_index, uri_index] self.data = ext_data @classmethod def parse(cls, file, header_t: ResXMLHeader): """ Parse the starting element of a Namespace :param file: the axml already pointing at the right offset :type file: bytesIO :param header_t: the already read header of the chunk :type header_t: ResXMLHeader :return: an instance of itself :rtype: XmlStartNamespace """ num_exts = (header_t.header.total_size - header_t.header.header_size) // 4 ext_data = file.read(num_exts * 4) chunks = [ext_data[i:i + 4] for i in range(0, len(ext_data), 4)] ext = [struct.unpack('\n" if attributes else f"<{string_list[element.attrext[1]]}>\n" else: tag_line = f"<{string_list[element.attrext[1]]} {attributes}>\n" if attributes else f"<{string_list[element.attrext[1]]}>\n" android_manifest_xml.append(tag_line) elif isinstance(element, XmlcDataElement): if android_manifest_xml[-1][-1] == '\n': android_manifest_xml[-1] = android_manifest_xml[-1].replace('\n', string_list[element.data_index]) elif isinstance(element, XmlEndElement): name = string_list[element.attrext[1]] closing_tag = f"" if name == "manifest" else f"\n" android_manifest_xml.append(closing_tag) return ''.join(android_manifest_xml) def get_manifest(raw_manifest): """ Helper method to directly return the AndroidManifest file as created by create_manifest() :param raw_manifest: expects the encoded AndroidManifest.xml file as a file-like object :type raw_manifest: bytesIO :return: returns the decoded AndroidManifest file :rtype: str """ manifest_object = ManifestStruct.parse(raw_manifest) return manifest_object.get_manifest() def parse_apk_for_manifest(inc_apk, raw: bool = False, lite: bool = False, num_of_elements: int = 3): """ Helper method to retrieve the AndroidManifest directly from an APK, either by providing the APK itself or the path. :param inc_apk: The path of the APK file or the APK itself :type inc_apk: str :param raw: Boolean parameter to define whether the manifest is provided as string or bytes :type raw: bool :param lite: Boolean parameter to define whether the lite parsing would occur or not :type lite: bool :param num_of_elements: Number of elements to parse from the APK :type num_of_elements: int :return: Returns the AndroidManifest.xml as string :rtype: str """ if raw: apk_file = inc_apk else: with open(inc_apk, 'rb') as apk: apk_file = io.BytesIO(apk.read()) entry_manifest = ZipEntry.parse_single(apk_file, "AndroidManifest.xml") manifest_local = entry_manifest.local_headers["AndroidManifest.xml"].to_dict() manifest_bytes = extract_file_based_on_header_info(apk_file, manifest_local, entry_manifest.central_directory.entries[ "AndroidManifest.xml"].to_dict())[0] if lite: manifest = get_manifest_lite(io.BytesIO(manifest_bytes), num_of_elements=num_of_elements) else: manifest = get_manifest(io.BytesIO(manifest_bytes)) return manifest def get_manifest_lite(manifest: io.BytesIO, num_of_elements: int): """ A method to provide 'lite' parsing of the AndroidManifest in order to retrieve a few details as fast as possible. Based on the integer 'num_of_elements' being passed as a parameter, it will attempt to fetch this many chunks right after the 'resource map' chunk and will get the attributes values of these elements if they are of instance XmlStartElement :param manifest: The manifest to be processed :type manifest: io.BytesIO :param num_of_elements: :type num_of_elements: int :return: Returns a dictionary of the attributes discovered :rtype: dict """ (ResChunkHeader_init, [string_pool_ResChunkHeader, string_pool_data], [resource_map_header, resource_map_data], elements) = ManifestStruct.parse_lite(manifest, num_of_elements=num_of_elements) end_stringpool_offset = string_pool_ResChunkHeader.header.total_size + 8 strings_start = string_pool_ResChunkHeader.strings_start is_utf8 = bool(string_pool_ResChunkHeader.flags & (1 << 8)) attributes_dict = {} for element in elements: if isinstance(element, XmlStartElement): for attr in element.attributes: if isinstance(attr, XmlAttributeElement): attr_name = StringPoolType.get_string_from_pool(attr.name_index, io.BytesIO(string_pool_data), end_stringpool_offset, strings_start, is_utf8) attribute_value = get_attribute_value(attr_name, attr, end_stringpool_offset, strings_start, is_utf8, io.BytesIO(string_pool_data)) attributes_dict[attr_name] = attribute_value return attributes_dict def get_attribute_value(attr_name, attribute, end_stringpool_offset, strings_start, is_utf8, string_pool_data): """ Gets the value for a single attribute :param attr_name: The attribute name as it has been retrieved by the string pool :type attr_name: str :param attribute: the parsed attribute itself :type attribute: XmlAttributeElement :param end_stringpool_offset: The end of string pool offset :type end_stringpool_offset: int :param strings_start: the strings start offset for the string pool :type strings_start: int :param is_utf8: boolean to check if a utf8 string is expected :type is_utf8: bool :param string_pool_data: The string pool data as io.BytesIO :type string_pool_data: io.BytesIO :return: returns the attribute value :rtype: str """ try: if attribute.typed_value_datatype == 1: # reference type return f"@{attribute.typed_value_data}" elif attribute.typed_value_datatype == 3: # string type str_pool_loc = StringPoolType.get_string_from_pool(attribute.typed_value_data, string_pool_data, end_stringpool_offset, strings_start, is_utf8) return escape_xml_entities(str_pool_loc) if str_pool_loc else str(attribute.typed_value_data) elif attribute.typed_value_datatype == 4: # float type str_pool_loc = StringPoolType.get_string_from_pool(attribute.typed_value_data, string_pool_data, end_stringpool_offset, strings_start, is_utf8) if not str_pool_loc: str_pool_loc = StringPoolType.get_string_from_pool(attribute.raw_value_index, string_pool_data, end_stringpool_offset, strings_start, is_utf8) return str_pool_loc if str_pool_loc else str(attribute.typed_value_data) elif attribute.typed_value_datatype == 17: # int-hex type return f"0x{attribute.typed_value_data:08X}" elif attribute.typed_value_datatype == 18: # boolean type return "true" if attribute.typed_value_data else "false" else: return str(attribute.typed_value_data) except Exception as e: logging.exception(f"Exception processing attribute {attr_name}: {e}") return str(attribute.typed_value_data)