Debian Codegraph @

apkInspector/headers.py

raw symbols SCIP
1 import io
2 import logging
3 import os
4 import struct
5 from typing import Dict
6
7 from .extract import extract_file_based_on_header_info, extract_all_files_from_central_directory
8 from .helpers import pretty_print_header, save_to_json, save_data_to_file
9
10
11 class EndOfCentralDirectoryRecord:
12 """
13 A class to provide details about the end of central directory record.
14 """
15 def __init__(self, signature, number_of_this_disk, disk_where_central_directory_starts,
16 number_of_central_directory_records_on_this_disk,
17 total_number_of_central_directory_records, size_of_central_directory,
18 offset_of_start_of_central_directory, comment_length, comment):
19 self.signature = signature
20 self.number_of_this_disk = number_of_this_disk
21 self.disk_where_central_directory_starts = disk_where_central_directory_starts
22 self.number_of_central_directory_records_on_this_disk = number_of_central_directory_records_on_this_disk
23 self.total_number_of_central_directory_records = total_number_of_central_directory_records
24 self.size_of_central_directory = size_of_central_directory
25 self.offset_of_start_of_central_directory = offset_of_start_of_central_directory
26 self.comment_length = comment_length
27 self.comment = comment
28
29 @classmethod
30 def parse(cls, apk_file):
31 """
32 Method to locate the "end of central directory record signature" as the first step of the correct process of
33 reading a ZIP archive. Should be noted that certain APKs do not follow the zip specification and declare multiple
34 "end of central directory records". For this reason the search for the corresponding signature of the eocd starts
35 from the end of the apk.
36
37 :param apk_file: The already read/loaded data of the APK file e.g. with open('test.apk', 'rb') as apk_file
38 :type apk_file: bytesIO
39 :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.
40 :rtype: EndOfCentralDirectoryRecord or None
41 """
42 chunk_size = 1024
43 offset = 0
44 signature_offset = -1
45 file_size = apk_file.seek(0, 2)
46 while offset < file_size:
47 position = max(0, file_size - offset - chunk_size)
48 apk_file.seek(position)
49 chunk = apk_file.read(chunk_size)
50 if not chunk:
51 break
52 signature_offset = chunk.rfind(b'\x50\x4b\x05\x06') # EOCD signature
53 if signature_offset != -1:
54 eo_central_directory_offset = position + signature_offset
55 break # Found EOCD signature
56 # Adjust offset to overlap by 4 bytes
57 offset += chunk_size - 4
58
59 if signature_offset == -1:
60 raise ValueError("End of central directory record (EOCD) signature not found")
61 apk_file.seek(eo_central_directory_offset)
62
63 signature = apk_file.read(4)
64 number_of_this_disk = struct.unpack('<H', apk_file.read(2))[0]
65 disk_where_central_directory_starts = struct.unpack('<H', apk_file.read(2))[0]
66 number_of_central_directory_records_on_this_disk = struct.unpack('<H', apk_file.read(2))[0]
67 total_number_of_central_directory_records = struct.unpack('<H', apk_file.read(2))[0]
68 size_of_central_directory = struct.unpack('<I', apk_file.read(4))[0]
69 offset_of_start_of_central_directory = struct.unpack('<I', apk_file.read(4))[0]
70 comment_length = struct.unpack('<H', apk_file.read(2))[0]
71 comment = struct.unpack(f'<{comment_length}s', apk_file.read(comment_length))[0].decode('utf-8', 'ignore')
72 return cls(
73 signature,
74 number_of_this_disk,
75 disk_where_central_directory_starts,
76 number_of_central_directory_records_on_this_disk,
77 total_number_of_central_directory_records,
78 size_of_central_directory,
79 offset_of_start_of_central_directory,
80 comment_length,
81 comment
82 )
83
84 def to_dict(self):
85 """
86 Represent the class as a dictionary.
87
88 :return: returns the dictionary
89 :rtype: dict
90 """
91 return {
92 "signature": self.signature,
93 "number_of_this_disk": self.number_of_this_disk,
94 "disk_where_central_directory_starts": self.disk_where_central_directory_starts,
95 "number_of_central_directory_records_on_this_disk": self.number_of_central_directory_records_on_this_disk,
96 "total_number_of_central_directory_records": self.total_number_of_central_directory_records,
97 "size_of_central_directory": self.size_of_central_directory,
98 "offset_of_start_of_central_directory": self.offset_of_start_of_central_directory,
99 "comment_length": self.comment_length,
100 "comment": self.comment
101 }
102
103 @classmethod
104 def from_dict(cls, entry_dict):
105 """
106 Convert a dictionary back to an instance of the class.
107
108 :param entry_dict: the dictionary
109 :type entry_dict: dict
110 :return: the instance of the class
111 :rtype: EndOfCentralDirectoryRecord
112 """
113 return cls(**entry_dict)
114
115
116 class CentralDirectoryEntry:
117 """
118 A class representing each entry in the central directory.
119 """
120 def __init__(self, version_made_by, version_needed_to_extract, general_purpose_bit_flag,
121 compression_method, file_last_modification_time, file_last_modification_date,
122 crc32_of_uncompressed_data, compressed_size, uncompressed_size, file_name_length,
123 extra_field_length, file_comment_length, disk_number_where_file_starts,
124 internal_file_attributes, external_file_attributes, relative_offset_of_local_file_header,
125 filename, extra_field, file_comment, offset_in_central_directory):
126 self.version_made_by = version_made_by
127 self.version_needed_to_extract = version_needed_to_extract
128 self.general_purpose_bit_flag = general_purpose_bit_flag
129 self.compression_method = compression_method
130 self.file_last_modification_time = file_last_modification_time
131 self.file_last_modification_date = file_last_modification_date
132 self.crc32_of_uncompressed_data = crc32_of_uncompressed_data
133 self.compressed_size = compressed_size
134 self.uncompressed_size = uncompressed_size
135 self.file_name_length = file_name_length
136 self.extra_field_length = extra_field_length
137 self.file_comment_length = file_comment_length
138 self.disk_number_where_file_starts = disk_number_where_file_starts
139 self.internal_file_attributes = internal_file_attributes
140 self.external_file_attributes = external_file_attributes
141 self.relative_offset_of_local_file_header = relative_offset_of_local_file_header
142 self.filename = filename
143 self.extra_field = extra_field
144 self.file_comment = file_comment
145 self.offset_in_central_directory = offset_in_central_directory
146
147 def to_dict(self):
148 """
149 Represent the class as a dictionary.
150
151 :return: returns the dictionary
152 :rtype: dict
153 """
154 return {
155 "version_made_by": self.version_made_by,
156 "version_needed_to_extract": self.version_needed_to_extract,
157 "general_purpose_bit_flag": self.general_purpose_bit_flag,
158 "compression_method": self.compression_method,
159 "file_last_modification_time": self.file_last_modification_time,
160 "file_last_modification_date": self.file_last_modification_date,
161 "crc32_of_uncompressed_data": self.crc32_of_uncompressed_data,
162 "compressed_size": self.compressed_size,
163 "uncompressed_size": self.uncompressed_size,
164 "file_name_length": self.file_name_length,
165 "extra_field_length": self.extra_field_length,
166 "file_comment_length": self.file_comment_length,
167 "disk_number_where_file_starts": self.disk_number_where_file_starts,
168 "internal_file_attributes": self.internal_file_attributes,
169 "external_file_attributes": self.external_file_attributes,
170 "relative_offset_of_local_file_header": self.relative_offset_of_local_file_header,
171 "filename": self.filename,
172 "extra_field": self.extra_field,
173 "file_comment": self.file_comment,
174 "offset_in_central_directory": self.offset_in_central_directory
175 }
176
177 @classmethod
178 def from_dict(cls, entry_dict):
179 """
180 Convert a dictionary back to an instance of the class.
181
182 :param entry_dict: the dictionary
183 :type entry_dict: dict
184 :return: the instance of the class
185 :rtype: CentralDirectoryEntry
186 """
187 return cls(**entry_dict)
188
189
190 class CentralDirectory:
191 """
192 The CentralDirectory containing all the CentralDirectoryEntry entries discovered.
193 The entries are listed as a dictionary where the filename is the key.
194 """
195 def __init__(self, entries):
196 self.entries = entries
197
198 @classmethod
199 def parse(cls, apk_file, eocd: EndOfCentralDirectoryRecord = None):
200 """
201 Method that is used to parse the central directory header according to the specification
202 https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT
203 based on the offset provided by the end of central directory record: eocd.offset_of_start_of_central_directory.
204
205 :param apk_file: The already read/loaded data of the APK file e.g. with open('test.apk', 'rb') as apk_file
206 :type apk_file: bytesIO
207 :param eocd: End of central directory record
208 :type eocd: EndOfCentralDirectoryRecord
209 :return: Returns a dictionary with all the entries discovered. The filename of each entry is used as the key. Besides the fields defined by the specification, each entry has an additional field named 'Offset in the central directory header', which includes the offset of the entry in the central directory itself.
210 :rtype: CentralDirectory
211 """
212 if not eocd:
213 eocd = EndOfCentralDirectoryRecord.parse(apk_file)
214 apk_file.seek(eocd.offset_of_start_of_central_directory)
215 if apk_file.tell() != eocd.offset_of_start_of_central_directory:
216 raise ValueError(f"Failed to find the offset for the central directory within the file!")
217
218 central_directory_entries = {}
219 while True:
220 c_offset = apk_file.tell()
221 signature = apk_file.read(4)
222 if signature != b'\x50\x4b\x01\x02':
223 break # Reached the end of the central directory
224 version_made_by = struct.unpack('<H', apk_file.read(2))[0]
225 version_needed_to_extract = struct.unpack('<H', apk_file.read(2))[0]
226 general_purpose_bit_flag = struct.unpack('<H', apk_file.read(2))[0]
227 compression_method = struct.unpack('<H', apk_file.read(2))[0]
228 file_last_modification_time = struct.unpack('<H', apk_file.read(2))[0]
229 file_last_modification_date = struct.unpack('<H', apk_file.read(2))[0]
230 crc32_of_uncompressed_data = struct.unpack('<I', apk_file.read(4))[0]
231 compressed_size = struct.unpack('<I', apk_file.read(4))[0]
232 uncompressed_size = struct.unpack('<I', apk_file.read(4))[0]
233 file_name_length = struct.unpack('<H', apk_file.read(2))[0]
234 extra_field_length = struct.unpack('<H', apk_file.read(2))[0]
235 file_comment_length = struct.unpack('<H', apk_file.read(2))[0]
236 disk_number_where_file_starts = struct.unpack('<H', apk_file.read(2))[0]
237 internal_file_attributes = struct.unpack('<H', apk_file.read(2))[0]
238 external_file_attributes = struct.unpack('<I', apk_file.read(4))[0]
239 relative_offset_of_local_file_header = struct.unpack('<I', apk_file.read(4))[0]
240 filename = struct.unpack(f'<{file_name_length}s', apk_file.read(file_name_length))[0].decode('utf-8', 'ignore')
241 extra_field = struct.unpack(f'<{extra_field_length}s', apk_file.read(extra_field_length))[0].decode('utf-8', 'ignore')
242 file_comment = struct.unpack(f'<{file_comment_length}s', apk_file.read(file_comment_length))[0].decode('utf-8', 'ignore')
243 offset_in_central_directory = c_offset
244
245 central_directory_entry = CentralDirectoryEntry(
246 version_made_by, version_needed_to_extract, general_purpose_bit_flag, compression_method,
247 file_last_modification_time, file_last_modification_date, crc32_of_uncompressed_data,
248 compressed_size, uncompressed_size, file_name_length, extra_field_length, file_comment_length,
249 disk_number_where_file_starts, internal_file_attributes, external_file_attributes,
250 relative_offset_of_local_file_header, filename, extra_field, file_comment,
251 offset_in_central_directory
252 )
253 central_directory_entries[central_directory_entry.filename] = central_directory_entry
254
255 return cls(central_directory_entries)
256
257 def to_dict(self):
258 """
259 Represent the class as a dictionary.
260
261 :return: returns the dictionary
262 :rtype: dict
263 """
264 return {filename: entry.to_dict() for filename, entry in self.entries.items()}
265
266 @classmethod
267 def from_dict(cls, entry_dict):
268 """
269 Convert a dictionary back to an instance of the class.
270
271 :param entry_dict: the dictionary
272 :type entry_dict: dict
273 :return: the instance of the class
274 :rtype: CentralDirectory
275 """
276 entries = {}
277 for filename, entry_data in entry_dict.items():
278 entry_instance = CentralDirectoryEntry.from_dict(entry_data)
279 entries[filename] = entry_instance
280 return cls(entries=entries)
281
282
283 class LocalHeaderRecord:
284 """
285 The local header for each entry discovered.
286 """
287 def __init__(self, version_needed_to_extract, general_purpose_bit_flag,
288 compression_method, file_last_modification_time, file_last_modification_date,
289 crc32_of_uncompressed_data, compressed_size, uncompressed_size, file_name_length,
290 extra_field_length, filename, extra_field):
291
292 self.version_needed_to_extract = version_needed_to_extract
293 self.general_purpose_bit_flag = general_purpose_bit_flag
294 self.compression_method = compression_method
295 self.file_last_modification_time = file_last_modification_time
296 self.file_last_modification_date = file_last_modification_date
297 self.crc32_of_uncompressed_data = crc32_of_uncompressed_data
298 self.compressed_size = compressed_size
299 self.uncompressed_size = uncompressed_size
300 self.file_name_length = file_name_length
301 self.extra_field_length = extra_field_length
302 self.filename = filename
303 self.extra_field = extra_field
304
305 @classmethod
306 def parse(cls, apk_file, entry_of_interest: CentralDirectoryEntry):
307 """
308 Method that attempts to read the local file header according to the specification https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT.
309
310 :param apk_file: The already read/loaded data of the APK file e.g. with open('test.apk', 'rb') as apk_file
311 :type apk_file: bytesIO
312 :param entry_of_interest: The central directory header of the specific entry of interest
313 :type entry_of_interest: CentralDirectoryEntry
314 :return: Returns a dictionary with the local header information or None if it failed to find the header.
315 :rtype: LocalHeaderRecord or None
316 """
317 apk_file.seek(entry_of_interest.relative_offset_of_local_file_header)
318 header_signature = apk_file.read(4)
319
320 if not header_signature == b'\x50\x4b\x03\x04':
321 logging.warning("Does not seem to be the start of a local header!")
322 return None
323 else:
324 version_needed_to_extract = struct.unpack('<H', apk_file.read(2))[0]
325 general_purpose_bit_flag = struct.unpack('<H', apk_file.read(2))[0]
326 compression_method = struct.unpack('<H', apk_file.read(2))[0]
327 file_last_modification_time = struct.unpack('<H', apk_file.read(2))[0]
328 file_last_modification_date = struct.unpack('<H', apk_file.read(2))[0]
329 crc32_of_uncompressed_data = struct.unpack('<I', apk_file.read(4))[0]
330 compressed_size = struct.unpack('<I', apk_file.read(4))[0]
331 uncompressed_size = struct.unpack('<I', apk_file.read(4))[0]
332 file_name_length = struct.unpack('<H', apk_file.read(2))[0]
333 extra_field_length = struct.unpack('<H', apk_file.read(2))[0]
334 try:
335 filename = struct.unpack(f'<{file_name_length}s', apk_file.read(file_name_length))[0].decode('utf-8', 'ignore')
336 extra_field = struct.unpack(f'<{extra_field_length}s', apk_file.read(extra_field_length))[0].decode('utf-8', 'ignore')
337 except:
338 filename = entry_of_interest.filename
339 extra_field = entry_of_interest.extra_field
340 return cls(
341 version_needed_to_extract, general_purpose_bit_flag, compression_method,
342 file_last_modification_time, file_last_modification_date, crc32_of_uncompressed_data,
343 compressed_size, uncompressed_size, file_name_length, extra_field_length,
344 filename, extra_field)
345
346 def to_dict(self):
347 """
348 Represent the class as a dictionary.
349
350 :return: returns the dictionary
351 :rtype: dict
352 """
353 return {
354 "version_needed_to_extract": self.version_needed_to_extract,
355 "general_purpose_bit_flag": self.general_purpose_bit_flag,
356 "compression_method": self.compression_method,
357 "file_last_modification_time": self.file_last_modification_time,
358 "file_last_modification_date": self.file_last_modification_date,
359 "crc32_of_uncompressed_data": self.crc32_of_uncompressed_data,
360 "compressed_size": self.compressed_size,
361 "uncompressed_size": self.uncompressed_size,
362 "file_name_length": self.file_name_length,
363 "extra_field_length": self.extra_field_length,
364 "filename": self.filename,
365 "extra_field": self.extra_field
366 }
367
368 @classmethod
369 def from_dict(cls, entry_dict):
370 """
371 Convert a dictionary back to an instance of the class.
372
373 :param entry_dict: the dictionary
374 :type entry_dict: dict
375 :return: the instance of the class
376 :rtype: LocalHeaderRecord
377 """
378 return cls(**entry_dict)
379
380
381 class ZipEntry:
382 """
383 Is the actual APK represented as a composition of the previous classes, which are: the EndOfCentralDirectoryRecord, the CentralDirectory and a dictionary of values of LocalHeaderRecord.
384 """
385 def __init__(self, zip_bytes, eocd: EndOfCentralDirectoryRecord, central_directory: CentralDirectory,
386 local_headers: Dict[str, LocalHeaderRecord]):
387 self.zip = zip_bytes
388 self.eocd = eocd
389 self.central_directory = central_directory
390 self.local_headers = local_headers
391
392 @classmethod
393 def parse(cls, inc_apk, raw: bool = True):
394 """
395 Method to start processing an APK. The raw (bytes) APK may be passed or the path to it.
396
397 :param inc_apk: the incoming apk, either path or bytes
398 :type inc_apk: str or bytesIO
399 :param raw: boolean flag to specify whether it is the raw apk in bytes or not
400 :type raw: bool
401 :return: returns the instance of the class
402 :rtype: ZipEntry
403 """
404 if raw:
405 apk_file = inc_apk
406 else:
407 with open(inc_apk, 'rb') as apk:
408 apk_file = io.BytesIO(apk.read())
409 eocd = EndOfCentralDirectoryRecord.parse(apk_file)
410 central_directory = CentralDirectory.parse(apk_file, eocd)
411 local_headers = {}
412 for entry in central_directory.entries:
413 local_header_entry = LocalHeaderRecord.parse(apk_file, central_directory.entries[entry])
414 if local_header_entry:
415 local_headers[local_header_entry.filename] = local_header_entry
416 return cls(apk_file, eocd, central_directory, local_headers)
417
418 @classmethod
419 def parse_single(cls, apk_file, filename, eocd: EndOfCentralDirectoryRecord = None,
420 central_directory: CentralDirectory = None):
421 """
422 Similar to parse, but instead of parsing the entire APK, it only targets the specified file.
423
424 :param apk_file: The apk file expected raw
425 :type apk_file: bytesIO
426 :param filename: the filename of the file to be parsed
427 :type filename: str
428 :param eocd: Optionally, the instance of the end of central directory from the APK
429 :type eocd: EndOfCentralDirectoryRecord(, optional)
430 :param central_directory: Optionally, the instance of the central directory record
431 :type central_directory: CentralDirectory(, optional)
432 :return: returns the instance of the class
433 :rtype: ZipEntry
434 """
435 if not eocd or not central_directory:
436 eocd = EndOfCentralDirectoryRecord.parse(apk_file)
437 central_directory = CentralDirectory.parse(apk_file, eocd)
438 local_header = {filename: LocalHeaderRecord.parse(apk_file, central_directory.entries[filename])}
439 return cls(apk_file, eocd, central_directory, local_header)
440
441 def to_dict(self):
442 """
443 Represent the class as a dictionary.
444
445 :return: returns the dictionary
446 :rtype: dict
447 """
448 return {
449 "end_of_central_directory": self.eocd.to_dict(),
450 "central_directory": self.central_directory.to_dict(),
451 "local_headers": {filename: entry.to_dict() for filename, entry in self.local_headers.items()}
452 }
453
454 def get_central_directory_entry_dict(self, filename):
455 """
456 Method to retrieve the central directory entry for a specific filename.
457
458 :param filename: the filename of the file to search for in the central directory
459 :type filename: str
460 :return: returns a dictionary of the central directory entry or None if the filename is not found
461 :rtype: dict
462 """
463 if filename in self.central_directory.entries:
464 return self.central_directory.entries[filename].to_dict()
465 else:
466 raise KeyError(f"Key: {filename} was not found within the central directory entries!")
467
468 def get_local_header_dict(self, filename):
469 """
470 Method to retrieve the local header of a specific filename.
471
472 :param filename: the filename of the entry to search for among the local headers
473 :type filename: str
474 :return: returns a ditionary of the local header entry or None if the filename is not found
475 :rtype: dict
476 """
477 if filename in self.local_headers:
478 return self.local_headers[filename].to_dict()
479 else:
480 raise KeyError(f"Key: {filename} was not found within the local headers list!")
481
482 def read(self, name, save: bool = False):
483 """
484 Method to utilize the extract module and extract a single entry from the APK based on the filename.
485
486 :param name: the name of the file to be read/extracted
487 :type name: str
488 :param save: boolean to define whether the extracted file should be saved as well or not
489 :type save: bool(, optional)
490 :return: returns the raw bytes of the filename that was extracted
491 :rtype: bytes
492 """
493 extracted_file = extract_file_based_on_header_info(self.zip, self.get_local_header_dict(name),
494 self.get_central_directory_entry_dict(name))[0]
495 if save:
496 save_data_to_file(f"EXTRACTED_{name}", extracted_file)
497 return extracted_file
498
499 def infolist(self) -> Dict[str, CentralDirectoryEntry]:
500 """
501 List of information about the entries in the central directory.
502
503 :return: returns a dictionary where the keys are the filenames and the values are each an instance of the CentralDirectoryEntry
504 :rtype: dict
505 """
506 return self.central_directory.entries
507
508 def namelist(self):
509 """
510 List of the filenames included in the central directory.
511
512 :return: returns the list of the filenames
513 :rtype: list
514 """
515 return [vl for vl in self.central_directory.to_dict()]
516
517 def extract_all(self, extract_path, apk_name):
518 """
519 Extracts all the contents of the APK.
520
521 :param extract_path: where to extract it
522 :type extract_path: str
523 :param apk_name: the name of the apk
524 :type apk_name: str
525 """
526 output_path = os.path.join(extract_path, apk_name)
527 if not extract_all_files_from_central_directory(self.zip, self.to_dict()["central_directory"],
528 self.to_dict()["local_headers"], output_path):
529 logging.info(f"Extraction successful for: {apk_name}")
530
531
532 def print_headers_of_filename(cd_h_of_file, local_header_of_file):
533 """
534 Prints out the details for both the central directory header and the local file header. Useful for the CLI.
535
536 :param cd_h_of_file: central directory header of a filename as it may be retrieved from headers_of_filename
537 :type cd_h_of_file: dict
538 :param local_header_of_file: local header dictionary of a filename as it may be retrieved from headers_of_filename
539 :type local_header_of_file: dict
540 """
541 if not cd_h_of_file or not local_header_of_file:
542 logging.info("Are you sure the filename exists?")
543 return
544 pretty_print_header("CENTRAL DIRECTORY")
545 for k in cd_h_of_file:
546 if k == 'Relative offset of local file header' or k == 'Offset in the central directory header':
547 print(f"{k:40} : {hex(int(cd_h_of_file[k]))} | {cd_h_of_file[k]}")
548 else:
549 print(f"{k:40} : {cd_h_of_file[k]}")
550 pretty_print_header("LOCAL HEADER")
551 for k in local_header_of_file:
552 print(f"{k:40} : {local_header_of_file[k]}")
553
554
555 def show_and_save_info_of_headers(entries, apk_name, header_type: str, export: bool, show: bool):
556 """
557 Print information for each entry for the central directory header and allow to possibly export to JSON.
558
559 :param entries: The dictionary with all the entries for the central directory
560 :type entries: dict
561 :param apk_name: String with the name of the APK, so it can be used for the export.
562 :type apk_name: str
563 :param header_type: What type of header that is, either central_directory or local, to be used for the export
564 :type header_type: str
565 :param export: Boolean for exporting or not to JSON
566 :type export: bool
567 :param show: Boolean for printing or not the entries
568 :type show: bool
569 """
570 if show:
571 for entry in entries:
572 pretty_print_header(entry)
573 print(entries[entry])
574 if export:
575 save_to_json(f"{apk_name}_{header_type}_header.json", entries)