Debian Codegraph @

apkInspector/axml.py

raw symbols SCIP
1 import io
2 import logging
3 import struct
4 import random
5
6 from .extract import extract_file_based_on_header_info
7 from .headers import ZipEntry
8 from .helpers import escape_xml_entities
9
10 logging.basicConfig(
11 level=logging.DEBUG,
12 format='%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d -> %(funcName)s : %(message)s'
13 )
14
15
16 class ResChunkHeader:
17 """
18 Chunk header used throughout the axml.
19 This header is essential as it contains information about the header size but also the total size of the chunk
20 the header belongs to.
21 """
22
23 def __init__(self, header_type, header_size, total_size, data):
24 self.type = header_type
25 self.header_size = header_size
26 self.total_size = total_size
27 self.data = data
28
29 @classmethod
30 def parse(cls, file):
31 """
32 Read the header type (2 bytes), header size (2 bytes), and entry size (4 bytes).
33
34 :param file: the xml file e.g. with open('/path/AndroidManifest.xml', 'rb') as file
35 :type file: bytesIO
36 :return: Returns an instance of itself
37 :rtype: ResChunkHeader
38 """
39 header_data = file.read(8)
40 if len(header_data) < 8:
41 # End of file
42 return None
43 header_type, header_size, total_size = struct.unpack('<HHI', header_data)
44 return cls(header_type, header_size, total_size, header_data)
45
46
47 class ResStringPoolHeader:
48 """
49 It reads the string pool header which contains information about the StringPool.
50 """
51
52 def __init__(self, header: ResChunkHeader, string_count, style_count, flags, strings_start,
53 styles_start, data):
54 self.header = header
55 self.string_count = string_count
56 self.style_count = style_count
57 self.flags = flags
58 self.strings_start = strings_start
59 self.styles_start = styles_start
60 self.data = data
61
62 @classmethod
63 def parse(cls, file):
64 """
65 Read and parse ResStringPoolHeader from the file.
66
67 :param file: the xml file right after the header has been read.
68 :type file: bytesIO
69 :return: Returns an instance of itself
70 :rtype: ResStringPoolHeader
71 """
72 header = ResChunkHeader.parse(file)
73 string_pool_header_data = file.read(20)
74 string_count, style_count, flags, strings_start, styles_start = struct.unpack('<IIIII', string_pool_header_data)
75 return cls(header, string_count, style_count, flags, strings_start,
76 styles_start, string_pool_header_data)
77
78
79 class StringPoolType:
80 """
81 The stringPool class which is a composition of the ResStringPoolHeader
82 along with the string offsets and the string data.
83 """
84
85 def __init__(self, string_pool_header: ResStringPoolHeader, string_offsets, strings, string_pool_data):
86 self.str_header = string_pool_header
87 self.string_offsets = string_offsets
88 self.string_list = strings
89 self.data = string_pool_data
90
91 @classmethod
92 def read_string_offsets(cls, file, num_of_strings, end_absolute_offset):
93 """
94 Reads the offset available for each string. Requires to know the number of strings available beforehand.
95
96 :param file: the xml file right after the string pool header has been read.
97 :type file: bytesIO
98 :param num_of_strings: the calculated number of strings available
99 :type num_of_strings: int
100 :param end_absolute_offset: the absolute value of the offset where the offsets finish.
101 :type end_absolute_offset: int
102 :return: Returns a list of strings offsets.
103 :rtype: list
104 """
105 string_offsets = []
106 for i in range(0, num_of_strings):
107 string_offsets.append(struct.unpack('<I', file.read(4))[0])
108 # sanity check as after reading the last string we should be at the end offset as calculated
109 if file.tell() != end_absolute_offset:
110 logging.warning(
111 f"Current file read:{file.tell()} is not as expected to the start of the stringData:{end_absolute_offset})")
112 return string_offsets
113
114 @classmethod
115 def read_string_offset(cls, file, position):
116 try:
117 file.seek(position * 4)
118 string_offset = struct.unpack('<I', file.read(4))[0]
119 return string_offset
120 except Exception as e:
121 logging.error(f"String offset at position {position} failed to be read: {e}")
122 return None
123
124 @classmethod
125 def decode_stringpool_mixed_string(cls, file, is_utf8, end_stringpool_offset):
126 """
127 Handling the different encoding possibilities that can be met.
128
129 :param file: the xml file at the offset where the string is to be read
130 :type file: bytesIO
131 :param is_utf8: boolean to check if a utf8 string is expected
132 :type is_utf8: bool
133 :param end_stringpool_offset:
134 :type end_stringpool_offset: int
135 :return: Returns the decoded string
136 :rtype: str
137 """
138 if not is_utf8:
139 # Handle UTF-16 encoded strings
140 u16len = struct.unpack('<H', file.read(2))[0]
141 if u16len & 0x8000 == 0:
142 # Regular UTF-16 string
143 content = file.read(u16len * 2).decode('utf-16le')
144 else:
145 # UTF-16 string with fixup
146 u16len_fix = struct.unpack('<H', file.read(2))[0]
147 real_length = ((u16len & 0x7FFF) << 16) | u16len_fix
148 if real_length > end_stringpool_offset:
149 return ""
150 # TODO:a check for non null-terminated strings should be here as well
151 content = file.read(real_length * 2).decode('utf-16le')
152 else:
153 # Handle UTF-8 encoded strings
154 u16len = struct.unpack('B', file.read(1))[0]
155 file.read(1)
156 u8len = u16len
157 content = file.read(u8len).decode('utf-8', errors='replace')
158 # TODO: fixup is needed here as well, like for the utf16 case
159
160 return content
161
162 @classmethod
163 def read_strings(cls, file, string_offsets, strings_start, is_utf8):
164 """
165 Gets the actual strings based on the offsets retrieved from read_string_offsets().
166
167 :param file: the xml file right after the string pool offsets have been read
168 :type file: bytesIO
169 :param string_offsets: see -> read_string_offsets()
170 :type string_offsets: list
171 :param strings_start: the offset at which the string data starts
172 :type strings_start: int
173 :param is_utf8: boolean to check if a utf8 string is expected
174 :type is_utf8: bool
175 :return: Returns a list of the string data
176 :rtype: list
177 """
178 strings = []
179 for offset in string_offsets:
180 # Calculate the absolute offset within the string data +8 for the file header
181 absolute_offset = strings_start + offset + 8 # TODO: update this to get the file header size
182 # Move the file pointer to the start of the string
183 file.seek(absolute_offset)
184 # Read the length of the string (in bytes)
185 content = cls.decode_stringpool_mixed_string(file, is_utf8, strings_start + string_offsets[-1])
186 strings.append(content)
187 return strings
188
189 @classmethod
190 def read_string(cls, file, string_offset, strings_start, is_utf8, end_stringpool_offset):
191 """
192 Read a string from the string pool when the offset of it is known already.
193
194 :param file: the string pool data parsed as bytes
195 :type file: io.bytesIO
196 :param string_offset: the offset at which the string is located in the string pool
197 :type string_offset: int
198 :param strings_start: the offset at which the string data starts
199 :type strings_start: int
200 :param is_utf8: boolean to check if a utf8 string is expected
201 :type is_utf8: bool
202 :param end_stringpool_offset: the offset at which the string pool ends
203 :type end_stringpool_offset: int
204 :return: Returns the string or None
205 :rtype: str or None
206 """
207 absolute_offset = strings_start + string_offset - 28
208 if file.getbuffer().nbytes < absolute_offset:
209 return None
210 file.seek(absolute_offset)
211 string = cls.decode_stringpool_mixed_string(file, is_utf8, end_stringpool_offset)
212 return string
213
214 @classmethod
215 def get_string_from_pool(cls, position, string_pool_data, end_stringpool_offset, strings_start, is_utf8):
216 """
217 Retrieve a single string from the String Pool, given its position. It first gets the correct offset of the
218 string and then reads the string.
219
220 :param position: The position of the string to be retrieved
221 :type position: int
222 :param string_pool_data: the string pool data parsed as bytes
223 :type string_pool_data: io.BytesIO
224 :param end_stringpool_offset: the offset at which the string pool ends
225 :type end_stringpool_offset: int
226 :param strings_start: the offset at which the string data starts
227 :type strings_start: int
228 :param is_utf8: boolean to check if a utf8 string is expected
229 :type is_utf8: bool
230 :return: Returns the string or None
231 :rtype: str or None
232 """
233 try:
234 string_offset = cls.read_string_offset(string_pool_data, position)
235 if string_offset is None:
236 return None
237 return cls.read_string(string_pool_data, string_offset, strings_start, is_utf8, end_stringpool_offset)
238 except Exception as e:
239 logging.exception(f"Exception while retrieving string from pool: {e}")
240 return None
241
242 @classmethod
243 def parse_lite(cls, file):
244 """
245 A 'lite' parser that gets the header and then reads the rest of the chunk as a blob of bytes.
246
247 :param file: the AndroidManifest.xml file
248 :type file: bytesIO
249 :return: returns the header and the chunk data
250 :rtype: tuple(ResStringPoolHeader, bytes)
251 """
252 ResStringPool_header = ResStringPoolHeader.parse(file)
253 string_pool_data = read_remaining(file, ResStringPool_header.header)
254 while True: # read any null bytes remaining
255 cur_pos = file.tell()
256 if file.read(2) == b'\x80\x01':
257 file.seek(cur_pos)
258 break
259 file.seek(cur_pos)
260 file.read(1)
261 return ResStringPool_header, string_pool_data
262
263 @classmethod
264 def parse(cls, file):
265 """
266 Parse the string pool to acquire the strings used within the axml.
267
268 :param file: the xml file right after the file header is read
269 :type file: bytesIO
270 :return: Returns an instance of itself
271 :rtype: StringPoolType
272 """
273 string_pool_header = ResStringPoolHeader.parse(file)
274 string_pool_start = file.tell()
275 size_of_strings_offsets = string_pool_header.strings_start - 28
276 # it should be divisible by 4, as 4 bytes are per offset, so we can get accurately the # of strings
277 num_of_strings = size_of_strings_offsets // 4
278 if not (size_of_strings_offsets / 4).is_integer():
279 logging.warning(f"The number of strings in the string pool is not a integer number.")
280 string_offsets = cls.read_string_offsets(file, num_of_strings, string_pool_header.strings_start + 8)
281 is_utf8 = bool(string_pool_header.flags & (1 << 8))
282 string_list = cls.read_strings(file, string_offsets, string_pool_header.strings_start, is_utf8)
283 while True: # read any null bytes remaining
284 cur_pos = file.tell()
285 if file.read(2) == b'\x80\x01':
286 file.seek(cur_pos)
287 break
288 file.seek(cur_pos)
289 file.read(1)
290 if file.getbuffer().nbytes < file.tell() + 8:
291 raise ValueError("Resource Map header was not detected.")
292 string_pool_end = file.tell()
293 file.seek(string_pool_start)
294 string_pool_data = file.read(string_pool_end - string_pool_start)
295 return cls(
296 string_pool_header,
297 string_offsets,
298 string_list,
299 string_pool_data
300 )
301
302
303 class XmlResourceMapType:
304 """
305 Resource map class, with the header and the resource IDs.
306 """
307
308 def __init__(self, header, resids, resids_data):
309 self.header = header
310 self.resids = resids
311 self.data = resids_data
312
313 @classmethod
314 def parse_lite(cls, file):
315 """
316 A 'lite' parser that gets the header and then reads the rest of the chunk as a blob of bytes.
317
318 :param file: the AndroidManifest.xml file
319 :type file: bytesIO
320 :return: returns the header and the chunk data
321 :rtype: tuple(ResChunkHeader, bytes)
322 """
323 resource_map_header = ResChunkHeader.parse(file)
324 resource_map_data = read_remaining(file, resource_map_header)
325 return resource_map_header, resource_map_data
326
327 @classmethod
328 def parse(cls, file):
329 """
330 Parse the resource map and get the resource IDs.
331
332 :param file: the xml file right after the string pool is read
333 :type file: bytesIO
334 :return: Returns an instance of itself
335 :rtype: XmlResourceMapType
336 """
337 header = ResChunkHeader.parse(file)
338 num_resids = (header.total_size - header.header_size) // 4
339 resids_data = file.read(num_resids * 4)
340 chunks = [resids_data[i:i + 4] for i in range(0, len(resids_data), 4)]
341 resids = [struct.unpack('<I', chunk)[0] for chunk in chunks]
342
343 return cls(header, resids, resids_data)
344
345
346 class ResXMLHeader:
347 """
348 Chunk header used as a header for the elements.
349 This header represents the header for the rest of the elements besides the initial header, the string pool and
350 the resource map.
351 """
352
353 def __init__(self, header: ResChunkHeader, data):
354 self.header = header
355 # self.xml_header_line_number = header_line_number # not useful
356 # self.xml_header_comment = header_comment # not useful
357 self.data = data
358
359 @classmethod
360 def parse(cls, file):
361 """
362 Supporting header for the elements besides the initial header, the string pool and
363 the resource map.
364
365 :param file: the xml file e.g. with open('/path/AndroidManifest.xml', 'rb') as file
366 :type file: bytesIO
367 :return: Returns an instance of itself
368 :rtype: ResXMLHeader
369 """
370 header = ResChunkHeader.parse(file)
371 header_data = b''
372 if header.header_size > 8:
373 header_data = file.read(header.header_size - 8)
374 return cls(header, header_data)
375
376
377 class XmlStartNamespace:
378 """
379 The actual start of the xml, after this the elements of the xml will be found.
380 """
381
382 def __init__(self, header: ResXMLHeader, ext, ext_data):
383 self.header = header
384 self.ext = ext # [prefix_index, uri_index]
385 self.data = ext_data
386
387 @classmethod
388 def parse(cls, file, header_t: ResXMLHeader):
389 """
390 Parse the starting element of a Namespace
391 :param file: the axml already pointing at the right offset
392 :type file: bytesIO
393 :param header_t: the already read header of the chunk
394 :type header_t: ResXMLHeader
395 :return: an instance of itself
396 :rtype: XmlStartNamespace
397 """
398 num_exts = (header_t.header.total_size - header_t.header.header_size) // 4
399 ext_data = file.read(num_exts * 4)
400 chunks = [ext_data[i:i + 4] for i in range(0, len(ext_data), 4)]
401 ext = [struct.unpack('<I', chunk)[0] for chunk in chunks]
402 return cls(header_t, ext, ext_data)
403
404
405 class XmlEndNamespace:
406 """
407 Class to represent the end of a Namespace.
408 """
409
410 def __init__(self, header: ResXMLHeader, prefix_namespace_index, uri_index, end_namespace_data):
411 self.header = header
412 self.prefix_namespace_index = prefix_namespace_index
413 self.uri_index = uri_index
414 self.data = end_namespace_data
415
416 @classmethod
417 def parse(cls, file, header_t: ResXMLHeader):
418 """
419 Parse the ending element of a Namespace.
420
421 :param file: the axml already pointing at the right offset
422 :type file: bytesIO
423 :param header_t: the already read header of the chunk
424 :type header_t: ResXMLHeader
425 :return: an instance of itself
426 :rtype: XmlEndNamespace
427 """
428 end_namespace_data = file.read(8)
429 prefix_namespace_index, uri_index = struct.unpack('<II', end_namespace_data)
430 return cls(header_t, prefix_namespace_index, uri_index, end_namespace_data)
431
432
433 class XmlAttributeElement:
434 """
435 The attributes within each element within the axml, should be described by this class.
436 """
437
438 def __init__(self, full_namespace_index, name_index, raw_value_index, typed_value_size, typed_value_res0,
439 typed_value_datatype, typed_value_data):
440 self.full_namespace_index = full_namespace_index
441 self.name_index = name_index
442 self.raw_value_index = raw_value_index
443 self.typed_value_size = typed_value_size
444 self.typed_value_res0 = typed_value_res0
445 self.typed_value_datatype = typed_value_datatype
446 self.typed_value_data = typed_value_data
447
448 @classmethod
449 def parse(cls, file, attr_count, attr_size):
450 """
451 The method is responsible to parse and retrieve the attributes of an element based on the attribute count.
452 There are many datatypes that are not read according to the specification (at least for now), but that does
453 not affect the main goal of the tool, therefore it is not a priority. For the presentation of the values
454 another check is occurring in the process_attributes method.
455
456 :param file: the axml already pointing at the right offset
457 :type file: BytesIO
458 :param attr_count: The attribute count value part of XmlStartElement.attrext
459 :type attr_count: int
460 :param attr_size: The attribute size value part of XmlStartElement
461 :type attr_size: int
462 :return: List of attributes
463 :rtype: list
464 """
465 attrs = []
466 for _ in range(0, attr_count):
467 tn = file.tell()
468 full_namespace_index = struct.unpack('<I', file.read(4))[0]
469 name_index = struct.unpack('<I', file.read(4))[0]
470 raw_value_index = struct.unpack('<I', file.read(4))[0]
471 typed_value_size = struct.unpack('<H', file.read(2))[0]
472 typed_value_res0 = struct.unpack('<B', file.read(1))[0]
473 typed_value_datatype = struct.unpack('<B', file.read(1))[0]
474 if typed_value_datatype == 4:
475 typed_value_data = round(struct.unpack('<f', file.read(4))[0], 1)
476 elif typed_value_datatype == 5:
477 typed_value_data = struct.unpack('<I', file.read(4))[0]
478 elif typed_value_datatype == 16:
479 typed_value_data = struct.unpack('<i', file.read(4))[0]
480 else:
481 typed_value_data = struct.unpack('<I', file.read(4))[0]
482 attrs.append(cls(full_namespace_index, name_index, raw_value_index, typed_value_size, typed_value_res0,
483 typed_value_datatype, typed_value_data))
484 if file.tell() - tn != attr_size: # check for any dummy data in between attributes
485 file.read(attr_size - (file.tell() - tn))
486 return attrs
487
488
489 class XmlStartElement:
490 """
491 The starting point of an element, its attributes are described by XmlAttributeElement.
492 The attrext contains information about the element including the attribute count.
493 """
494
495 def __init__(self, header: ResXMLHeader, attrext, attributes, start_element_data):
496 self.header = header
497 self.attrext = attrext
498 self.attributes = attributes
499 self.data = start_element_data
500
501 @classmethod
502 def parse(cls, file, header_t: ResXMLHeader):
503 """
504 Parse the current element
505
506 :param file: the axml already pointing at the right offset
507 :type file: BytesIO
508 :param header_t: the already read header of the chunk
509 :type header_t: ResXMLHeader
510 :return: an instance of itself
511 :rtype: XmlStartElement
512 """
513 attrext_data = file.read(20)
514 full_namespace_index, name_index, attr_start, attr_size, attr_count, id_index, class_index, style_index = struct.unpack(
515 '<IIHHHHHH', attrext_data)
516 attrext = [full_namespace_index, name_index, attr_start, attr_size, attr_count, id_index, class_index,
517 style_index]
518 if attr_start != 20:
519 # Cover for dummy data between ResXMLTree_attrExt and the 1st ResXMLTree_attribute
520 gap_size = attr_start - 20
521 file.read(gap_size)
522 attributes_data = file.read(attr_size * attr_count)
523 attributes = XmlAttributeElement.parse(io.BytesIO(attributes_data), attr_count, attr_size)
524 return cls(header_t, attrext, attributes, (attrext_data + attributes_data))
525
526
527 class XmlEndElement:
528 """
529 The end of an element, where the attrext contains the necessary information on which element it ends.
530 """
531
532 def __init__(self, header: ResXMLHeader, attrext, attrext_data):
533 self.header = header
534 self.attrext = attrext
535 self.data = attrext_data
536
537 @classmethod
538 def parse(cls, file, header_t: ResXMLHeader):
539 """
540 Parse the end of an element.
541
542 :param file: the axml already pointing at the right offset
543 :type file: bytesIO
544 :param header_t: the already read header of the chunk
545 :type header_t: ResXMLHeader
546 :return: an instance of itself
547 :rtype: XmlEndElement
548 """
549 attrext_data = file.read(8)
550 full_namespace_index, name_index = struct.unpack('<II', attrext_data)
551 attrext = [full_namespace_index, name_index]
552 return cls(header_t, attrext, attrext_data)
553
554
555 class XmlcDataElement:
556 """
557 A class to cover any CDATA section
558 https://developer.android.com/reference/org/w3c/dom/CDATASection
559 """
560
561 def __init__(self, header: ResXMLHeader, data_index, typed_value_size, typed_value_res0,
562 typed_value_datatype, typed_value_data, cdata_data):
563 self.header = header
564 self.data_index = data_index
565 self.typed_value_size = typed_value_size
566 self.typed_value_res0 = typed_value_res0
567 self.typed_value_datatype = typed_value_datatype
568 self.typed_value_data = typed_value_data
569 self.data = cdata_data
570
571 @classmethod
572 def parse(cls, file, header_t: ResXMLHeader):
573 """
574 Parse the CDATA element.
575
576 :param file: the axml already pointing at the right offset
577 :type file: bytesIO
578 :param header_t: the already read header of the chunk
579 :type header_t: ResXMLHeader
580 :return: an instance of itself
581 :rtype: XmlcDataElement
582 """
583 cdata_data = file.read(12)
584 data_index, typed_value_size, typed_value_res0, typed_value_datatype, typed_value_data = struct.unpack('<IHBBI', cdata_data)
585 return cls(header_t, data_index, typed_value_size, typed_value_res0,
586 typed_value_datatype, typed_value_data, cdata_data)
587
588
589 class ManifestStruct:
590 """
591 A class to represent the AndroidManifest as a composition
592 """
593
594 def __init__(self, header: ResChunkHeader, string_pool: StringPoolType, resource_map: XmlResourceMapType, elements):
595 self.header = header
596 self.string_pool = string_pool
597 self.resource_map = resource_map
598 self.elements = elements
599
600 @staticmethod
601 def check_reached_element(file: io.BytesIO):
602 """
603 Static method to check if the next element right after the resource map chunk has been reached.
604 Android tolerates unknown chunk types, so we only need to verify
605 there's enough data for a header and that the header size is plausible.
606 Reference: AOSP ResXMLTree::setTo()
607
608 :param file: The AndroidManifest file
609 :type file: io.BytesIO
610 """
611 min_size = 8 # 2 bytes type, 2 bytes header_size, 4 bytes total_size
612 while True:
613 cur_pos = file.tell()
614 if file.getbuffer().nbytes < cur_pos + min_size:
615 break # not enough data for a header
616 try:
617 _type, _header_size, _size = struct.unpack('<HHL', file.read(8))
618 file.seek(cur_pos)
619 if min_size <= _header_size <= _size:
620 return True # Valid header, regardless of type
621 except struct.error:
622 break
623 file.seek(cur_pos + 1) # Try next byte if not valid
624
625 @staticmethod
626 def parse_next_header(file):
627 """
628 Dispatcher method to parse the next available header. It takes into account to move on past the header if it
629 contains extra info besides the standard ones.
630 The dispatcher automatically picks the correct processing method for each chunk type.
631
632 :param file: the axml that will be processed
633 :type file: bytesIO
634 :raises NotImplementedError: The chunk type identified is not supported
635 :return: Dispatches to the appropriate processing method for each chunk type.
636 """
637 chunk_header_total = ResXMLHeader.parse(file)
638 chunk_header = chunk_header_total.header
639 if chunk_header is None: # end of file
640 return None
641 chunk_type = hex(chunk_header.type)
642 handler = chunk_type_handlers.get(chunk_type, chunk_type_handlers['default'])
643 return handler(file, chunk_header_total)
644
645 @staticmethod
646 def process_elements(file, num_of_elements=None):
647 """
648 It starts processing the remaining chunks **after** the resource map chunk.
649
650 :param file: the axml that will be processed
651 :type file: BytesIO
652 :param num_of_elements: how many elements should it process
653 :type num_of_elements: int
654 :return: Returns all the elements found as their corresponding classes and whether dummy data were found in between.
655 :rtype: set(list, set(bool, bool))
656 """
657 elements = []
658 while True:
659 cur_pos = file.tell()
660 if file.getbuffer().nbytes < cur_pos + 8:
661 # we reached the end of the file
662 break
663 ManifestStruct.check_reached_element(file)
664 resXMLTree_node = ResXMLHeader.parse(file)
665 cur_elem_data = read_remaining(file, resXMLTree_node.header)
666 elem_data = resXMLTree_node.header.data + resXMLTree_node.data + cur_elem_data
667 element = ManifestStruct.parse_next_header(io.BytesIO(elem_data))
668 if isinstance(element, dict) and "raw" in element:
669 logging.warning(f"Unknown chunk type found: {element['type']}")
670 continue # TODO: consider value in collecting this!
671 elements.append(element)
672 if num_of_elements is None:
673 continue
674 if len(elements) == num_of_elements:
675 break
676 return elements
677
678 def get_manifest(self):
679 """
680 Method to return the AndroidManifest created from this instance
681
682 :return: The AndroidManifest.xml as a string
683 :rtype: str
684 """
685 manifest = create_manifest(self.elements, self.string_pool.string_list)
686 return manifest
687
688 @staticmethod
689 def parse_lite(manifest, num_of_elements=None):
690 """
691 Parse the AndroidManifest with a limit on the elements to be parsed after the string pool. The goal of this method
692 is to make it possible to partially parse the AndroidManifest and allow faster parsing when needed. Only the
693 header is parsed from each chunk, and the rest are there as blobs of bytes.
694
695 :param manifest: The manifest to be processed
696 :type manifest: bytesIO
697 :param num_of_elements: How many elements of the manifest to process. Usually 3 are enough to get basic info about it.
698 :type num_of_elements: int
699 :return: A tuple containing four elements: ResChunkHeader, [ResStringPoolHeader, string_pool_data], [ResChunkHeader, resource_map_data], elements
700 :rtype: tuple (ResChunkHeader_init, [ResStringPoolHeader, bytes], [ResChunkHeader, bytes], list of bytes)
701 """
702 ResChunkHeader_init = ResChunkHeader.parse(manifest)
703 ResStringPool_header, string_pool_data = StringPoolType.parse_lite(manifest)
704 resource_map_header, resource_map_data = XmlResourceMapType.parse_lite(manifest)
705 elements = ManifestStruct.process_elements(manifest, num_of_elements=num_of_elements)
706 return ResChunkHeader_init, [ResStringPool_header, string_pool_data], [resource_map_header,
707 resource_map_data], elements
708
709 @classmethod
710 def parse(cls, file):
711 """
712 A composition of the rest of the classes available in the apkInspector.axml module, to form the AndroidManifest structure.
713
714 :param file: the axml that will be processed
715 :type file: bytesIO
716 :return: an instance of itself
717 :rtype: ManifestStruct
718 """
719 header = ResChunkHeader.parse(file)
720 string_pool = StringPoolType.parse(file)
721 resource_map = XmlResourceMapType.parse(file)
722 elements = cls.process_elements(file)
723 return cls(header, string_pool, resource_map, elements)
724
725
726 def handle_unknown_chunk(file: io.BytesIO, header_t: ResXMLHeader):
727 """
728 Default handler for unknown chunk types.
729 # ResourceTypes.cpp skips unrecognized chunk types
730 # as long as their size and header are valid.
731 # Reference: AOSP ResXMLTree::setTo() and ResXMLParser::nextNode()
732 """
733 data = read_remaining(file, header_t.header)
734 # Optional: return raw chunk for logging or malware analysis
735 return {
736 "type": hex(header_t.header.type),
737 "raw": data
738 }
739
740
741 chunk_type_handlers = {
742 '0x100': XmlStartNamespace.parse, # RES_XML_START_NAMESPACE_TYPE
743 '0x101': XmlEndNamespace.parse, # RES_XML_END_NAMESPACE_TYPE
744 '0x102': XmlStartElement.parse, # RES_XML_START_ELEMENT_TYPE
745 '0x103': XmlEndElement.parse, # RES_XML_END_ELEMENT_TYPE
746 '0x104': XmlcDataElement.parse, # RES_XML_CDATA_TYPE
747 'default': handle_unknown_chunk # fallback
748 }
749
750 def read_remaining(file: io.BytesIO, header: ResChunkHeader):
751 """
752
753 :param file: the current file that is being processed
754 :type file: io.BytesIO
755 :param header: the header of the current chunk of instance ResChunkHeader
756 :type header: ResChunkHeader
757 :return: Returns the remaining bytes of the chunk except the header
758 :rtype: bytes
759 """
760 remaining_to_be_read = header.total_size - header.header_size
761 return file.read(remaining_to_be_read)
762
763
764 def process_attributes(attributes, string_list, ns_dict):
765 """
766 Helps in processing the representation of attributes found in each element of the axml. It should be noted that not
767 all datatypes are taken into account, meaning that the values of certain attributes might not be represented properly.
768
769 :param attributes: the attributes of an XmlStartElement object as returned by XmlAttributeElement.parse()
770 :type attributes: list
771 :param string_list: the string data list from the String Pool
772 :type string_list: list
773 :param ns_dict: a namespace dictionary based on the XmlStartNamespace elements found
774 :type ns_dict: dict
775 :return: returns a string of all the attributes with their values
776 :rtype: str
777 """
778 attribute_list = []
779 for attr in attributes:
780 try:
781 name = string_list[attr.name_index]
782 except:
783 continue
784 if not name: # It happens that the attr.name_index points to an empty string in StringPool and you have to use
785 # the public.xml. It falls outside the scope of the tool, so I am not going to solve it for now.
786 name = f'Unknown_Attribute_Name_{random.randint(1000, 9999)}'
787 if "\n" in name:
788 # may be obfuscated attribute - https://github.com/REAndroid/APKEditor
789 continue
790 if attr.typed_value_datatype == 1: # reference type
791 value = f"@{attr.typed_value_data}"
792 elif attr.typed_value_datatype == 3: # string type
793 try:
794 value = escape_xml_entities(string_list[attr.typed_value_data])
795 except:
796 value = attr.typed_value_data
797 elif attr.typed_value_datatype == 17: # int-hex type
798 value = "0x{:08X}".format(attr.typed_value_data)
799 elif attr.typed_value_datatype == 18: # boolean type
800 value = "true" if bool(attr.typed_value_data) else "false"
801 elif attr.typed_value_datatype == 0: # null, used for CData
802 return name
803 else:
804 # TODO: Not accurate enough, values should be represented based on which datatype. Good enough for now
805 value = str(attr.typed_value_data)
806 if attr.full_namespace_index < len(string_list):
807 namespace = string_list[attr.full_namespace_index]
808 if not namespace: # Same as with the empty name, points to an empty string in StringPool.
809 namespace = 'android'
810 try:
811 attribute_list.append(f'{ns_dict[namespace]}:{name}="{value}"')
812 except:
813 attribute_list.append(f'{namespace.split("/")[-1]}:{name}="{value}"')
814 else:
815 attribute_list.append(f'{name}="{value}"')
816
817 return ' '.join(attribute_list)
818
819
820 def create_manifest(elements, string_list):
821 """
822 Method to create the readable XML AndroidManifest.xml file based on the elements discovered from the processed APK
823
824 :param elements: The parsed elements as returned by process_elements()[0]
825 :type elements: list
826 :param string_list: The string pool data
827 :type string_list: list
828 :return: The AndroidManifest.xml as a string
829 :rtype: str
830 """
831 android_manifest_xml = []
832 namespaces = {}
833 ns_dict = {}
834 ns_declared = []
835 for element in elements:
836 if isinstance(element, XmlStartNamespace):
837 if element.ext[0] < len(string_list) or element.ext[1] < len(string_list):
838 namespaces[string_list[element.ext[0]]] = f'xmlns:{string_list[element.ext[0]]}="{string_list[element.ext[1]]}"'
839 ns_dict[string_list[element.ext[1]]] = string_list[element.ext[0]]
840 elif isinstance(element, XmlStartElement):
841 attributes = process_attributes(element.attributes, string_list, ns_dict)
842 attr_ns_list = set(ns.split(':')[0] for ns in attributes.split(' ') if ':' in ns)
843 tmp_ns = [] # TODO: Somewhat hacky way to add namespaces/ Maybe improve in future depending on needs
844 for vl in attr_ns_list:
845 if vl not in ns_declared:
846 if vl in namespaces:
847 tmp_ns.append(namespaces[vl])
848 elif vl == 'android':
849 tmp_ns.append(f'xmlns:android="http://schemas.android.com/apk/res/android"')
850 ns_declared.append(vl)
851 if tmp_ns:
852 tag_line = f"<{string_list[element.attrext[1]]} {' '.join(tmp_ns)} {attributes}>\n" if attributes else f"<{string_list[element.attrext[1]]}>\n"
853 else:
854 tag_line = f"<{string_list[element.attrext[1]]} {attributes}>\n" if attributes else f"<{string_list[element.attrext[1]]}>\n"
855 android_manifest_xml.append(tag_line)
856 elif isinstance(element, XmlcDataElement):
857 if android_manifest_xml[-1][-1] == '\n':
858 android_manifest_xml[-1] = android_manifest_xml[-1].replace('\n',
859 string_list[element.data_index])
860 elif isinstance(element, XmlEndElement):
861 name = string_list[element.attrext[1]]
862 closing_tag = f"</{name}>" if name == "manifest" else f"</{name}>\n"
863 android_manifest_xml.append(closing_tag)
864 return ''.join(android_manifest_xml)
865
866
867 def get_manifest(raw_manifest):
868 """
869 Helper method to directly return the AndroidManifest file as created by create_manifest()
870
871 :param raw_manifest: expects the encoded AndroidManifest.xml file as a file-like object
872 :type raw_manifest: bytesIO
873 :return: returns the decoded AndroidManifest file
874 :rtype: str
875 """
876 manifest_object = ManifestStruct.parse(raw_manifest)
877 return manifest_object.get_manifest()
878
879
880 def parse_apk_for_manifest(inc_apk, raw: bool = False, lite: bool = False, num_of_elements: int = 3):
881 """
882 Helper method to retrieve the AndroidManifest directly from an APK, either by providing the APK itself or the path.
883
884 :param inc_apk: The path of the APK file or the APK itself
885 :type inc_apk: str
886 :param raw: Boolean parameter to define whether the manifest is provided as string or bytes
887 :type raw: bool
888 :param lite: Boolean parameter to define whether the lite parsing would occur or not
889 :type lite: bool
890 :param num_of_elements: Number of elements to parse from the APK
891 :type num_of_elements: int
892 :return: Returns the AndroidManifest.xml as string
893 :rtype: str
894 """
895 if raw:
896 apk_file = inc_apk
897 else:
898 with open(inc_apk, 'rb') as apk:
899 apk_file = io.BytesIO(apk.read())
900
901 entry_manifest = ZipEntry.parse_single(apk_file, "AndroidManifest.xml")
902 manifest_local = entry_manifest.local_headers["AndroidManifest.xml"].to_dict()
903 manifest_bytes = extract_file_based_on_header_info(apk_file, manifest_local,
904 entry_manifest.central_directory.entries[
905 "AndroidManifest.xml"].to_dict())[0]
906 if lite:
907 manifest = get_manifest_lite(io.BytesIO(manifest_bytes), num_of_elements=num_of_elements)
908 else:
909 manifest = get_manifest(io.BytesIO(manifest_bytes))
910 return manifest
911
912
913 def get_manifest_lite(manifest: io.BytesIO, num_of_elements: int):
914 """
915 A method to provide 'lite' parsing of the AndroidManifest in order to retrieve a few details as fast as possible.
916 Based on the integer 'num_of_elements' being passed as a parameter, it will attempt to fetch this many chunks right
917 after the 'resource map' chunk and will get the attributes values of these elements if they are of instance XmlStartElement
918
919 :param manifest: The manifest to be processed
920 :type manifest: io.BytesIO
921 :param num_of_elements:
922 :type num_of_elements: int
923 :return: Returns a dictionary of the attributes discovered
924 :rtype: dict
925 """
926 (ResChunkHeader_init,
927 [string_pool_ResChunkHeader, string_pool_data],
928 [resource_map_header, resource_map_data], elements) = ManifestStruct.parse_lite(manifest,
929 num_of_elements=num_of_elements)
930 end_stringpool_offset = string_pool_ResChunkHeader.header.total_size + 8
931 strings_start = string_pool_ResChunkHeader.strings_start
932 is_utf8 = bool(string_pool_ResChunkHeader.flags & (1 << 8))
933 attributes_dict = {}
934 for element in elements:
935 if isinstance(element, XmlStartElement):
936 for attr in element.attributes:
937 if isinstance(attr, XmlAttributeElement):
938 attr_name = StringPoolType.get_string_from_pool(attr.name_index, io.BytesIO(string_pool_data),
939 end_stringpool_offset, strings_start, is_utf8)
940 attribute_value = get_attribute_value(attr_name, attr, end_stringpool_offset, strings_start,
941 is_utf8, io.BytesIO(string_pool_data))
942 attributes_dict[attr_name] = attribute_value
943 return attributes_dict
944
945
946 def get_attribute_value(attr_name, attribute, end_stringpool_offset, strings_start, is_utf8, string_pool_data):
947 """
948 Gets the value for a single attribute
949
950 :param attr_name: The attribute name as it has been retrieved by the string pool
951 :type attr_name: str
952 :param attribute: the parsed attribute itself
953 :type attribute: XmlAttributeElement
954 :param end_stringpool_offset: The end of string pool offset
955 :type end_stringpool_offset: int
956 :param strings_start: the strings start offset for the string pool
957 :type strings_start: int
958 :param is_utf8: boolean to check if a utf8 string is expected
959 :type is_utf8: bool
960 :param string_pool_data: The string pool data as io.BytesIO
961 :type string_pool_data: io.BytesIO
962 :return: returns the attribute value
963 :rtype: str
964 """
965 try:
966 if attribute.typed_value_datatype == 1: # reference type
967 return f"@{attribute.typed_value_data}"
968 elif attribute.typed_value_datatype == 3: # string type
969 str_pool_loc = StringPoolType.get_string_from_pool(attribute.typed_value_data, string_pool_data,
970 end_stringpool_offset,
971 strings_start, is_utf8)
972 return escape_xml_entities(str_pool_loc) if str_pool_loc else str(attribute.typed_value_data)
973 elif attribute.typed_value_datatype == 4: # float type
974 str_pool_loc = StringPoolType.get_string_from_pool(attribute.typed_value_data, string_pool_data,
975 end_stringpool_offset,
976 strings_start, is_utf8)
977 if not str_pool_loc:
978 str_pool_loc = StringPoolType.get_string_from_pool(attribute.raw_value_index, string_pool_data,
979 end_stringpool_offset,
980 strings_start, is_utf8)
981 return str_pool_loc if str_pool_loc else str(attribute.typed_value_data)
982 elif attribute.typed_value_datatype == 17: # int-hex type
983 return f"0x{attribute.typed_value_data:08X}"
984 elif attribute.typed_value_datatype == 18: # boolean type
985 return "true" if attribute.typed_value_data else "false"
986 else:
987 return str(attribute.typed_value_data)
988 except Exception as e:
989 logging.exception(f"Exception processing attribute {attr_name}: {e}")
990 return str(attribute.typed_value_data)