-
Notifications
You must be signed in to change notification settings - Fork 16
/
extractor.py
executable file
·2363 lines (2171 loc) · 120 KB
/
extractor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# This file is part of Extractor.
# Copyright (C) 2021 Security Research Labs GmbH
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import logging
import sys
from collections import defaultdict, deque
import re
import argparse
import tempfile
from enum import Enum, auto
from Crypto.Cipher import AES
import struct
# noinspection PyPep8Naming
import xml.etree.ElementTree as ET
import json
from typing import List, Optional, DefaultDict
import shutil
import shlex
from lxml import etree
import liblp
base_dir = os.path.dirname(os.path.realpath(__file__))
def main():
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s: %(message)s')
if os.getuid() != 0:
logging.error("Not running as root, exiting")
sys.exit(1)
parser = argparse.ArgumentParser(description='Android firmware extraction tool')
parser.add_argument("input")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--tar-output", help="Path to system.tar file to generate")
group.add_argument("--system-dir-output", help="Path to store system dir, without intermediate tar file")
group.add_argument("--no-output", action="store_true", help="Only run extraction but ignore output")
parser.add_argument("--boot-recovery-output", help="Directory where boot/recovery img should be stored")
parser.add_argument("--allow-missing-vendor", action="store_true", help="Allow missing vendor partition for extraction, required for system-only updates (=> Project Treble), e.g. for some LineageOS images")
args = parser.parse_args()
extractor = FirmwareExtractor(args.input)
try:
output_boot_img_path = None
output_recovery_img_path = None
if args.boot_recovery_output is not None:
output_boot_img_path = os.path.join(os.path.abspath(args.boot_recovery_output), "boot.img")
output_recovery_img_path = os.path.join(os.path.abspath(args.boot_recovery_output), "recovery.img")
extractor.extract(output_system_tar=args.tar_output, output_system_dir=args.system_dir_output, output_boot_img_path=output_boot_img_path, output_recovery_img_path=output_recovery_img_path, allow_missing_vendor=args.allow_missing_vendor)
finally:
extractor.cleanup()
class CheckFileResult(Enum):
ARCHIVE = auto()
SYSTEM_IMG = auto()
VENDOR_IMG = auto()
BOOT_IMG = auto()
RECOVERY_IMG = auto()
SYSTEM_OR_VENDOR = auto()
HANDLER_NO_MATCH = auto()
HANDLER_NO_MATCH_AND_IGNORE_SIZE_COVERAGE = auto()
IGNORE = auto()
class ImageType(Enum):
SYSTEM = auto()
VENDOR = auto()
class FileHandler:
def __init__(self, extractor: "FirmwareExtractor", input_path_rel, file_type, image_type: ImageType = None):
self.extractor: FirmwareExtractor = extractor
self.input_path_rel = input_path_rel
self.abs_fn = self.extractor.abs_fn(input_path_rel)
assert isinstance(self.abs_fn, bytes), "abs_fn must be of type bytes"
assert isinstance(file_type, str), "file_type must be of type str"
assert image_type in (None, ImageType.SYSTEM, ImageType.VENDOR), "Invalid image_type=%r" % image_type
self.fn = self.abs_fn.split(b'/')[-1]
self.file_type = file_type
self.image_type: ImageType = image_type
def check(self) -> CheckFileResult:
raise NotImplementedError("check() must be implemented in subclass (%s)" % self.__class__.__name__)
def get_extra_handled_size(self):
return 0
class ZipHandler(FileHandler):
"""
Generic Zip Handler, often used as top-level container format
"""
def check(self) -> CheckFileResult:
if not self.is_good_extension():
return CheckFileResult.HANDLER_NO_MATCH
if not (self.file_type.lower().startswith("zip") or self.file_type.lower().startswith("java archive data")):
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def is_good_extension(self) -> bool:
if self.abs_fn.lower().endswith(b".zip"):
return True
if self.abs_fn.lower().endswith(b".ftf"):
# Sony ftf format
return True
if self.abs_fn.lower().endswith(b".ozip"):
# Oppo ozip, in some cases custom format (see OzipHandler), in other cases just a zip file
return True
if self.abs_fn.lower().endswith(b".up"):
# Some ZTE firmwares use ".up" for zip files
return True
return False
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["unzip", "-q", self.abs_fn]
logging.info("ZipHandler: cmd=%r cwd=%r" % (cmd, abs_output_path))
exitcode = subprocess.call(cmd, cwd=abs_output_path, stdin=subprocess.DEVNULL)
# 0: OK, 1: Finished with warnings
if exitcode in (0, 1):
return
logging.info("Extracting zip file with 'unzip' command failed (exit code %d), retrying with 'jar xf'", exitcode)
# unzip failed, clean up stage dir and try other extractor
assert b'/tmp/AND' in abs_output_path, "abs_output_path %r doesn't contain /tmp/AND" % abs_output_path
shutil.rmtree(abs_output_path)
os.mkdir(abs_output_path)
# Try jar as a second extractor, there is a known issue with unzip and large (>4GB) files:
# https://stackoverflow.com/a/31084012
cmd = ["jar", "xf", self.abs_fn]
logging.info("ZipHandler fallback to jar: cmd=%r cwd=%r" % (cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class TopLevelZipHandler(ZipHandler):
"""
Generic Zip Handler for top level format, also supports arbitrary file extensions, to be used for initial input file only
"""
def is_good_extension(self) -> bool:
return True
class SevenZipHandler(FileHandler):
"""
Generic 7z Handler, sometimes used as top-level container format
"""
def check(self) -> CheckFileResult:
good_extension = False
if self.abs_fn.lower().endswith(b".7z"):
good_extension = True
if not good_extension:
return CheckFileResult.HANDLER_NO_MATCH
if not self.file_type.lower().startswith("7-zip archive data"):
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["7z", "x", self.abs_fn]
logging.info("ZipHandler: cmd=%r cwd=%r" % (cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class RarHandler(FileHandler):
"""
Generic rar Handler, sometimes used as top-level container format
"""
def check(self) -> CheckFileResult:
# Disabled extension check, sometimes there is no .rar extension (but the file type should be reliable enough)
# good_extension = False
# if self.abs_fn.lower().endswith(b".rar"):
# good_extension = True
# if not good_extension:
# return CheckFileResult.HANDLER_NO_MATCH
if not self.file_type.lower().startswith("rar archive data"):
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["unrar", "x", "-psamdownloads.de", self.abs_fn]
logging.info("RarHandler: cmd=%r cwd=%r" % (cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class OzipHandler(FileHandler):
"""
OPPO encrypted image
"""
def check(self) -> CheckFileResult:
good_extension = False
if self.abs_fn.lower().endswith(b".ozip"):
good_extension = True
if not good_extension:
return CheckFileResult.HANDLER_NO_MATCH
magic = open(self.abs_fn, 'rb').read(12)
if magic != b'OPPOENCRYPT!':
if self.file_type.lower().startswith("java archive"):
# Some .ozip files are actually zip, e.g. CPH1809EX_11_OTA_0180_all_OlU3r4ImvcSX_local.ozip
return CheckFileResult.HANDLER_NO_MATCH
assert False, "Invalid ozip magic %r" % magic
return CheckFileResult.ARCHIVE
def extract_and_get_next_handler(self, stage_dir_rel):
# Replace .ozip with .zip
assert self.abs_fn.lower().endswith(b".ozip")
out_filename = os.path.basename(self.abs_fn)[0:-5] + b".zip"
out_path_rel = os.path.join(stage_dir_rel, out_filename)
abs_stage_dir = self.extractor.create_stage_dir(stage_dir_rel)
out_path_abs = os.path.join(abs_stage_dir, out_filename)
ozip = AES.new(b'\xD6\xDC\xCF\x0A\xD5\xAC\xD4\xE0\x29\x2E\x52\x2D\xB7\xC1\x38\x1E', AES.MODE_ECB)
with open(self.abs_fn, 'rb') as ifs:
ifs.seek(0x1050, 0)
with open(out_path_abs, 'wb') as ofs:
while True:
data = ifs.read(16)
ofs.write(ozip.decrypt(data))
data = ifs.read(0x4000)
if len(data) == 0:
break
ofs.write(data)
return ZipHandler(self.extractor, out_path_rel, file_type=get_file_type(out_path_abs))
class PacHandler(FileHandler):
"""
Mediatek PAC image
"""
def check(self) -> CheckFileResult:
good_extension = False
if self.abs_fn.lower().endswith(b".pac"):
good_extension = True
if not good_extension:
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
sr = os.stat(self.abs_fn)
with open(self.abs_fn, 'rb') as pac:
buf = pac.read(1024 * 1024)
last_file_end = 0
for pos in range(60, 69721, 2580):
file_item = buf[pos:pos + 2580]
name = file_item[0:0x40].decode("utf-16").replace("\x00", "")
start_pos = struct.unpack("<I", file_item[0x40c:0x410])[0]
length = struct.unpack("<I", file_item[0x400:0x404])[0]
if start_pos == 0:
continue
assert start_pos >= last_file_end, "start_pos >= last_file_end: %d >= %x" % (start_pos, last_file_end)
if start_pos + length > sr.st_size:
continue
if name in ("system.img", "system_raw.img", "boot.img", "recovery.img"):
logging.debug("Doing %s", name)
with open(os.path.join(abs_output_path, name.encode()), 'wb') as out:
pac.seek(start_pos)
bytes_done = 0
while bytes_done < length:
chunk_len = min(1024 * 1024, length - bytes_done)
out.write(pac.read(chunk_len))
bytes_done += chunk_len
last_file_end = start_pos + length
class IgnoreBadTarMd5Handler(FileHandler):
"""
Ignore same non-wanted .tar.md5 files
"""
def check(self) -> CheckFileResult:
good_extension = False
if self.abs_fn.lower().endswith(b".tar.md5"): # Samsung
good_extension = True
if not good_extension:
return CheckFileResult.HANDLER_NO_MATCH
if 'POSIX tar archive' not in self.file_type:
return CheckFileResult.HANDLER_NO_MATCH
if self.fn.startswith(b'USERDATA_'):
# USERDATA_*.tar.md5 is present on some Samsung images, but it contains only useless stuff such as dalvik caches
# Needs to be ignored so that ArchiveDirectoryHandler can accept handling only other files
return CheckFileResult.IGNORE
if self.fn.startswith(b'CSC_') or self.fn.startswith(b'HOME_CSC_'):
# Needs to be ignored so that ArchiveDirectoryHandler can accept handling only other files
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class TarHandler(FileHandler):
"""
Handler for tar files (and Samsung .tar.md5 files, which are actually tar archives)
"""
def check(self) -> CheckFileResult:
if not self.is_good_extension():
return CheckFileResult.HANDLER_NO_MATCH
# Not every tar archive is a "POSIX" tar archive.
if 'POSIX tar archive' in self.file_type or self.file_type == 'tar archive':
if self.fn.startswith(b'USERDATA_') and self.fn.endswith(b'.tar.md5'):
# USERDATA_*.tar.md5 is present on some Samsung images, but it contains only useless stuff such as dalvik caches
# Needs to be ignored so that ArchiveDirectoryHandler can accept handling only other files
return CheckFileResult.IGNORE
return CheckFileResult.ARCHIVE
else:
return CheckFileResult.HANDLER_NO_MATCH
def is_good_extension(self) -> bool:
if self.abs_fn.lower().endswith(b".tar"):
return True
if self.abs_fn.lower().endswith(b".tar.md5"): # Samsung
return True
return False
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["tar", "xvf", self.abs_fn]
logging.info("TarHandler.extract_file2dir(%r): cmd=%r cwd=%r" % (output_path_rel, cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class TarHandlerIgnoreExtension(TarHandler):
def is_good_extension(self) -> bool:
return True
class HuaweiAppHandler(FileHandler):
"""
Handler for Huawei .app images
"""
def check(self) -> CheckFileResult:
if not self.abs_fn.lower().endswith(b".app"):
return CheckFileResult.HANDLER_NO_MATCH
assert self.fn.lower().startswith(b'update')
# No file_type check, is typically "data"
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["%s/splituapp/splituapp" % base_dir, "-f", self.abs_fn, "-o", abs_output_path, "--no-crc"]
logging.info("HuaweiAppHandler.extract_file2dir(%r): cmd=%r cwd=%r" % (output_path_rel, cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class KdzHandler(FileHandler):
"""
Handler for LG kdz format
"""
def check(self) -> CheckFileResult:
if not self.abs_fn.lower().endswith(b".kdz"):
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["%s/kdzextractor/unkdz.py" % base_dir, "-x", "-f", self.abs_fn]
logging.info("KdzHandler.extract_file2dir(%r): cmd=%r cwd=%r" % (output_path_rel, cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class DzHandler(FileHandler):
"""
Handler for LG kdz format
"""
def check(self) -> CheckFileResult:
if not self.abs_fn.lower().endswith(b".dz"):
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["python", "%s/kdzextractor/undz.py" % base_dir, "-x", "-f", self.abs_fn]
logging.info("DzHandler.extract_file2dir(%r): cmd=%r cwd=%r" % (output_path_rel, cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
# undz creates a number of system_<num>.bin files.
# <num> is the block number whete this file is in the final system image.
# The block size is variable, can be found based on the size of the first image
# and the offset of the second image.
# pdb.set_trace()
dzextracted_path = os.path.join(abs_output_path, b'dzextracted')
listing = os.listdir(dzextracted_path)
file_num_to_fn = dict()
for fn in listing:
if fn.startswith(b'vendor_') and fn.endswith(b'.bin'):
assert False, "Please implement DzHandler Vendor extraction"
if not fn.startswith(b'system_'):
continue
if not fn.endswith(b'.bin'):
continue
num = int(fn[7:-4].decode())
file_num_to_fn[num] = os.path.join(dzextracted_path, fn)
files_sorted = list(sorted(file_num_to_fn.keys()))
offset = files_sorted[0]
value = files_sorted[1] - files_sorted[0]
info = os.stat(os.path.join(output_path_rel, file_num_to_fn[files_sorted[0]]))
# noinspection PyUnusedLocal
bs: int
if (value * 512) >= info.st_size:
bs = 512
elif (value * 1024) >= info.st_size:
bs = 1024
elif (value * 2048) >= info.st_size:
bs = 2048
elif (value * 4096) >= info.st_size:
bs = 4096
else:
assert False, "Failed to find block size"
abs_system_img = os.path.join(abs_output_path, b'system.img')
with open(abs_system_img, 'wb') as out_fh:
for file_num in files_sorted:
file_name = file_num_to_fn[file_num]
pos = bs * (file_num - offset)
out_fh.seek(pos)
with open(file_name, 'rb') as in_fh:
while True:
buf = in_fh.read(1024 * 1024)
if len(buf) == 0:
break
out_fh.write(buf)
os.unlink(file_name) # Unlink is required so that the next ArchiveDirectoryHandler will not be confused by the low handled size
# logging.info("Please check the results once")
# pdb.set_trace()
class SinHandler(FileHandler):
"""
Handler for system.sin files (Sony)
"""
def check(self) -> CheckFileResult:
if self.fn.lower() == b'system.sin':
return CheckFileResult.ARCHIVE
elif self.fn.lower() == b'vendor.sin':
assert False, "TODO: Check and implement extraction of vendor.sin"
else:
return CheckFileResult.HANDLER_NO_MATCH
def extract_file2dir(self, output_path_rel):
abs_output_path = self.extractor.abs_fn(output_path_rel)
cmd = ["%s/sinextract/sinextract" % base_dir, abs_output_path, self.abs_fn]
logging.info("SinHandler.extract_file2dir(%r): cmd=%r cwd=%r" % (output_path_rel, cmd, abs_output_path))
subprocess.check_call(cmd, cwd=abs_output_path)
class RawprogramUnsparseHandler(FileHandler):
system_parts_with_pos: List[List]
vendor_parts_with_pos: List[List]
super_parts_with_pos: List[List]
extra_ignored_size: int
def check(self) -> CheckFileResult:
self.system_parts_with_pos = []
self.vendor_parts_with_pos = []
self.super_parts_with_pos = []
self.extra_ignored_size = 0
if self.fn == b"contents.xml":
return self.check_contents_xml(self.abs_fn)
else:
xml_files_by_priority = (
b'rawprogram_unsparse.xml',
b'rawprogram0.xml',
b'rawprogram_unsparse(US).xml',
b'rawprogram0_unsparse.xml',
b'rawprogram_unsparse0.xml',
b'rawprogram0_unsparse_upgrade.xml',
b'rawprogram_upgrade.xml',
b'rawprogram_unsparse_upgrade.xml'
)
if self.fn not in xml_files_by_priority:
return CheckFileResult.HANDLER_NO_MATCH
input_dir_abs = os.path.dirname(self.abs_fn)
direct_system_img_path = os.path.join(input_dir_abs, b'system.img')
if os.path.exists(direct_system_img_path) and os.stat(direct_system_img_path).st_size > 128 * 1024 * 1024:
return CheckFileResult.HANDLER_NO_MATCH_AND_IGNORE_SIZE_COVERAGE # Some images contain a system.img file directly and some non-working xml
# If contents.xml exists, it should be used and this handler should return HANDLER_NO_MATCH for all other
# xml files. However, in some cases contents.xml is broken and we need to continue based on
# xml_files_by_priority
content_xml_path = os.path.join(input_dir_abs, b'contents.xml')
if os.path.exists(content_xml_path):
if self.check_contents_xml(content_xml_path) != CheckFileResult.HANDLER_NO_MATCH:
return CheckFileResult.HANDLER_NO_MATCH
highest_priority_existing_file = None
for tmp_fn in reversed(xml_files_by_priority):
if os.path.exists(os.path.join(input_dir_abs, tmp_fn)):
highest_priority_existing_file = tmp_fn
assert highest_priority_existing_file is not None
if highest_priority_existing_file != self.fn:
return CheckFileResult.HANDLER_NO_MATCH # There is a better (higher priority) xml file, so let's ignore this one
logging.info("RawprogramUnsparseHandler: Checking file %r" % self.abs_fn)
return self.parse_xml_file(self.abs_fn)
def check_contents_xml(self, abs_contents_xml: bytes) -> CheckFileResult:
contents_xml_dir = os.path.dirname(abs_contents_xml)
parser = etree.XMLParser()
tree = etree.parse(open(abs_contents_xml), parser)
root = tree.getroot()
params_tags = root.xpath('//step[@filter="hlos"]/params')
if len(params_tags) == 0:
if len(root.xpath("/contents/product_info/product_name")) > 0:
return CheckFileResult.HANDLER_NO_MATCH # Some firmwares have a completely different file called "contents.xml", which isn't required for extraction.
raise ValueError("Failed to parse contents.xml")
result = CheckFileResult.HANDLER_NO_MATCH
for params_tag in params_tags:
cmd_str = params_tag.text.strip()
assert "@rawprogram_xml" in cmd_str
cmd = shlex.split(cmd_str)
assert cmd[-2] == "-o"
xml_fn = cmd[-1]
abs_fn = os.path.join(contents_xml_dir, xml_fn.encode())
# assert os.path.exists(abs_fn), "File %r (referenced from %r) doesn't exist" % (abs_fn, self.abs_fn)
if os.path.exists(abs_fn):
result = self.parse_xml_file(abs_fn)
else:
logging.error("File %r (referenced from %r) doesn't exist", abs_fn, abs_contents_xml)
return result
def parse_xml_file(self, abs_xml_fn):
try:
root = ET.parse(open(abs_xml_fn))
except ET.ParseError:
# Workaround for crappy XML, e.g. document starting with </data
lines = open(abs_xml_fn).read().splitlines()
lines = [x for x in lines if "<program" in x]
logging.debug("\n".join(lines))
root = ET.XML("<data>\n" + "\n".join(lines) + "</data>")
program_tags = root.findall('program')
sector_size: Optional[int] = None
image_base_dir = os.path.dirname(abs_xml_fn)
partition_start_sector_by_label = {}
found_vendor_b: bool = False
for program_tag in program_tags:
label = program_tag.attrib["label"]
if label in ("system", "system_a", "vendor", "vendor_a", "super"):
logging.info("RawprogramUnsparseHandler: program_tag.attrib=%s" % json.dumps(program_tag.attrib, sort_keys=True))
# Sparse attribute can cause problems (sector size mismatch etc.), it will be handled directly by SuperImageHandler
if label == "super" and "sparse" in program_tag.attrib and program_tag.attrib["sparse"].lower() == "true":
continue
filename = program_tag.attrib["filename"]
abs_fn = os.path.join(image_base_dir, filename.encode())
if not os.path.exists(abs_fn):
if b'image/modem/' in abs_xml_fn:
return CheckFileResult.IGNORE
raise ValueError("File %r doesn't exist (referenced from %r)" % (abs_fn, abs_xml_fn))
if "SECTOR_SIZE_IN_BYTES" in program_tag.attrib:
if sector_size is None:
sector_size = int(program_tag.attrib["SECTOR_SIZE_IN_BYTES"])
assert sector_size in [512, 4096]
else:
assert int(program_tag.attrib["SECTOR_SIZE_IN_BYTES"]) == sector_size, "Inconsistent sector size: %r <=> %r" % (int(program_tag.attrib["SECTOR_SIZE_IN_BYTES"]), sector_size)
else:
# Found a program tag without SECTOR_SIZE_IN_BYTES => Fall back to default 512
sector_size = 512
assert os.stat(abs_fn).st_size % sector_size == 0, "File %r is not a multiple of %d bytes" % (abs_fn, sector_size)
start_sector = int(program_tag.attrib["start_sector"])
if label not in partition_start_sector_by_label:
partition_start_sector_by_label[label] = start_sector
start_pos = sector_size * (start_sector - partition_start_sector_by_label[label])
assert start_pos < 10 * 1024 * 1024 * 1024, "RawprogramUnsparseHandler: Sparse image too big (>10 GiB)"
if label.startswith("system"):
self.system_parts_with_pos.append([abs_fn, start_pos])
elif label.startswith("vendor"):
self.vendor_parts_with_pos.append([abs_fn, start_pos])
elif label.startswith("super"):
self.super_parts_with_pos.append([abs_fn, start_pos])
else:
raise ValueError("Bad label %r, this should not happen" % label)
elif label == "vendor_b":
found_vendor_b = True
elif label.startswith("custom") or label.startswith("userdata"):
filename = program_tag.attrib["filename"]
abs_fn = os.path.join(image_base_dir, filename.encode())
try:
self.extra_ignored_size += os.stat(abs_fn).st_size
except FileNotFoundError:
pass
else:
# Just to make sure we aren't missing a vendor partition here
assert 'vendor' not in label.lower(), "Found unexpected program label containing 'vendor' in %r" % program_tag.attrib["label"]
if found_vendor_b:
assert len(self.vendor_parts_with_pos) > 0, "XML file %r contains vendor_b but no valid vendor" % abs_xml_fn
if len(self.system_parts_with_pos) == 0 and len(self.vendor_parts_with_pos) == 0 and len(self.super_parts_with_pos) == 0:
return CheckFileResult.HANDLER_NO_MATCH
return CheckFileResult.SYSTEM_OR_VENDOR
def get_extra_handled_size(self):
result = 0
for (part_fn, pos) in self.system_parts_with_pos:
result += os.stat(part_fn).st_size
for (part_fn, pos) in self.vendor_parts_with_pos:
result += os.stat(part_fn).st_size
for (part_fn, pos) in self.super_parts_with_pos:
result += os.stat(part_fn).st_size
return result
def has_vendor(self):
return len(self.vendor_parts_with_pos) > 0
def extract_and_get_next_handlers(self, stage_dir_rel) -> List[FileHandler]:
def extract_parts_to_file(my_parts: List[List], my_abs_out_fn):
with open(my_abs_out_fn, 'wb') as out_fh:
for item in my_parts:
# logging.info("ITEM: %r" % item)
(part_fn, pos) = item
out_fh.seek(pos)
with open(part_fn, 'rb') as in_fh:
while True:
buf = in_fh.read(1024 * 1024)
if len(buf) == 0:
break
out_fh.write(buf)
abs_stage_dir = self.extractor.create_stage_dir(stage_dir_rel)
result: List[FileHandler] = []
if len(self.super_parts_with_pos) > 0:
assert len(self.system_parts_with_pos) == 0, "Can't have system and super image"
assert len(self.vendor_parts_with_pos) == 0, "Can't have vendor and super image"
output_fn = b'super.img'
abs_out_fn = os.path.join(abs_stage_dir, output_fn)
extract_parts_to_file(self.super_parts_with_pos, abs_out_fn)
handler = SuperImageHandler(self.extractor, self.extractor.rel_path(abs_out_fn), file_type=get_file_type(abs_out_fn))
handler_result = handler.check()
if handler_result == CheckFileResult.HANDLER_NO_MATCH:
raise ValueError("RawprogramUnsparseHandler: Extracted super.img but SuperImageHandler returned HANDLER_NO_MATCH")
result.append(handler)
else:
for image_type in (ImageType.SYSTEM, ImageType.VENDOR):
if image_type == ImageType.VENDOR and len(self.vendor_parts_with_pos) == 0:
continue
output_fn = b'%s.img' % image_type.name.lower().encode()
abs_out_fn = os.path.join(abs_stage_dir, output_fn)
parts: List[List]
if image_type == ImageType.SYSTEM:
parts = self.system_parts_with_pos
elif image_type == ImageType.VENDOR:
parts = self.vendor_parts_with_pos
else:
raise ValueError("Invalid image_type=%r" % image_type)
extract_parts_to_file(parts, abs_out_fn)
HANDLER_TYPES = [ExtfsHandler, ErofsHandler]
handlers = []
for handler_type in HANDLER_TYPES:
handler = handler_type(self.extractor, self.extractor.rel_path(abs_out_fn), image_type=image_type, file_type=get_file_type(abs_out_fn))
handler_result = handler.check()
if handler_result != CheckFileResult.HANDLER_NO_MATCH:
assert handler_result in (CheckFileResult.SYSTEM_IMG, CheckFileResult.VENDOR_IMG, CheckFileResult.SYSTEM_OR_VENDOR), "Unexpected handler_result=%r from handler %r" % (handler_result, handler.__class__.__name__)
handlers.append(handler)
if len(handlers) > 1:
raise MultipleHandlerMatchError("File %r: %r" % (abs_out_fn, [x.__class__.__name__ for x in handlers]))
elif len(handlers) == 0:
raise NoHandlerMatchError("RawprogramUnsparseHandler.extract_and_get_next_handler(): Don't know what to do with %r (file_type=%r)" % (abs_out_fn, get_file_type(abs_out_fn)))
else:
result.append(handlers[0])
return result
class IgnoreRadioHandler(FileHandler):
"""
Handler to ignore radio-*.img files, e.g. radio-taimen-g8998-00253-1805232234.img
"""
def check(self) -> CheckFileResult:
if self.fn.startswith(b'radio-') and self.fn.endswith(b'.img'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreBootloaderHandler(FileHandler):
"""
Handler to ignore bootloader-*.img files, e.g. bootloader-taimen-tmz20k.img
"""
def check(self) -> CheckFileResult:
if self.fn.startswith(b'bootloader-') and self.fn.endswith(b'.img'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreVmlinuxHandler(FileHandler):
"""
Handler to ignore "vmlinux" files, helps with coverage for some images
"""
def check(self) -> CheckFileResult:
if self.fn.lower() == b"vmlinux":
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreOpImageHandler(FileHandler):
"""
Handler to ignore OP_\\d+.bin files
"""
def check(self) -> CheckFileResult:
m = re.match(rb'op_\d+\.bin', self.fn.lower())
if m:
# May have various different file types, e.g. ext4 or jar. So let's just match by filename here.
logging.info("IgnoreOpImageHandler: file %r => file_type=%r" % (self.abs_fn, self.file_type))
return CheckFileResult.IGNORE
m = re.match(rb'op_\w+\.img', self.fn.lower())
if m:
# Sample: OP_OPEN_ZA.img from H84020c_00_OPEN_ZA_OP_0630.kdz
logging.info("IgnoreOpImageHandler: file %r => file_type=%r" % (self.abs_fn, self.file_type))
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreOemImgHandler(FileHandler):
"""
Handler to ignore oem.img files
"""
def check(self) -> CheckFileResult:
if self.fn == b'oem.img':
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreProductImgHandler(FileHandler):
"""
Handler to ignore product.img files
"""
def check(self) -> CheckFileResult:
if self.fn == b'product.img' or self.fn.startswith(b'product.img.'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreSystemExtImgHanlder(FileHandler):
"""
Handler to ignore system_ext.img files
"""
def check(self) -> CheckFileResult:
if self.fn == b'system_ext.img' or self.fn.startswith(b'system_ext.img.'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreXromImgHanlder(FileHandler):
"""
Handler to ignore xrom.img files
"""
def check(self) -> CheckFileResult:
if self.fn == b'xrom.img' or self.fn.startswith(b'xrom.img.'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreAppsImgHandler(FileHandler):
"""
Handler to ignore apps.img (and apps_X.img) files
"""
def check(self) -> CheckFileResult:
if re.match(rb'apps(_\d+)?\.img', self.fn):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreUpdateHwHandler(FileHandler):
"""
Handler to ignore update_full_*_hw_*.zip files
Only required in ArchiveDirectoryHandler Pass2
"""
def check(self) -> CheckFileResult:
m = re.match(rb'update_full_.*_hw_\w+\.zip', self.fn.lower())
if m:
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreHuaweiUserdataAppHandler(FileHandler):
"""
Handler to ignore USERDATA.APP
Required so that the actual image (UPDATE.APP) will be >90%
"""
def check(self) -> CheckFileResult:
if self.fn.lower() == b"userdata.app":
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class IgnoreElfHandler(FileHandler):
"""
Handler to ignore elf files
Required to reach size coverage threshold
"""
def check(self) -> CheckFileResult:
if self.file_type.startswith("ELF ") and self.fn.lower().endswith(b'.elf'):
return CheckFileResult.IGNORE
return CheckFileResult.HANDLER_NO_MATCH
class SparseImageHandler(FileHandler):
abs_fn_list: List[bytes]
def check(self) -> CheckFileResult:
if self.file_type.startswith("Android sparse image, version: 1.0,"):
if self.fn.lower().startswith(b"system_other"):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'hidden.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'cache'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'userdata.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'userdata_'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'persist.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'3rdmodem.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'cust.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'product.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'odm.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'oem.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'container.'):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b'apps.'):
# Vivo
return CheckFileResult.IGNORE
if self.fn.lower().endswith(b".duplicate"):
return CheckFileResult.IGNORE # splituapp duplicate file entries in Huawei UPDATE.APP
if self.fn.lower().startswith(b"op_") or self.fn.lower().startswith(b"op."):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b"oem_"):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b"preas_"):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b"preas."):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b"non-hlos."):
return CheckFileResult.IGNORE
if self.fn.lower().startswith(b"super"):
return CheckFileResult.HANDLER_NO_MATCH # Will be covered by SuperImageHandler
self.abs_fn_list = []
if b"sparsechunk" in self.fn.lower():
if self.fn.lower().endswith(b"sparsechunk.0"):
base_abs_fn = self.abs_fn[0:-2]
for i in range(100):
abs_fn = base_abs_fn + b".%d" % i
if os.path.exists(abs_fn):
self.abs_fn_list.append(abs_fn)
else:
break
else:
return CheckFileResult.IGNORE
else:
self.abs_fn_list.append(self.abs_fn)
if self.fn.lower().startswith(b"system.") or self.fn.lower().startswith(b"system_a.") or self.fn.lower().startswith(b"system-sign."):
self.image_type = ImageType.SYSTEM
return CheckFileResult.SYSTEM_IMG
elif self.fn.lower().startswith(b"vendor.") or self.fn.lower().startswith(b"vendor_a.") or self.fn.lower().startswith(b"vendor-sign."):
self.image_type = ImageType.VENDOR
return CheckFileResult.VENDOR_IMG
elif self.fn.lower().startswith(b"system_b.") or self.fn.lower().startswith(b"vendor_b."):
return CheckFileResult.IGNORE
elif self.fn.lower().startswith(b"system_ext."):
return CheckFileResult.IGNORE
elif self.fn.lower().startswith(b"system_other."):
return CheckFileResult.IGNORE
elif self.fn.lower().startswith(b"vendor_dlkm."):
return CheckFileResult.IGNORE
else:
if os.stat(self.abs_fn).st_size < 32 * 1024 * 1024:
# Ignore images smaller than 32 MiB, these images can't be a valid system/vendor partition
return CheckFileResult.IGNORE
assert False, "SparseImageHandler: %r does not start with system/vendor (Size %.2f MiB)" % (self.fn, os.stat(self.abs_fn).st_size / 1024**2)
else:
return CheckFileResult.HANDLER_NO_MATCH
def get_extra_handled_size(self) -> int:
result = 0
# Only count from file 1
for fn in self.abs_fn_list[1:]:
result += os.stat(fn).st_size
return result
def extract_and_get_next_handler(self, stage_dir_rel):
output_fn = self.fn + b".SparseImageHandler"
abs_stage_dir = self.extractor.create_stage_dir(stage_dir_rel)
abs_out_fn = os.path.join(abs_stage_dir, output_fn)
cmd: List[bytes] = [b"simg2img"] + self.abs_fn_list + [abs_out_fn]
logging.info("SparseImageHandler: cmd=%r" % cmd)
subprocess.check_call(cmd)
assert os.path.exists(abs_out_fn)
HANDLER_TYPES = [ExtfsHandler, AsusMagicHandler, ErofsHandler, MotoPivHandler]
handlers = []
for handler_type in HANDLER_TYPES:
handler = handler_type(self.extractor, self.extractor.rel_path(abs_out_fn), image_type=self.image_type, file_type=get_file_type(abs_out_fn))
handler_result = handler.check()
if handler_result != CheckFileResult.HANDLER_NO_MATCH:
assert handler_result in (CheckFileResult.SYSTEM_IMG, CheckFileResult.VENDOR_IMG, CheckFileResult.SYSTEM_OR_VENDOR), "Unexpected handler_result=%r from handler %r" % (handler_result, handler.__class__.__name__)
handlers.append(handler)
if len(handlers) > 1:
raise MultipleHandlerMatchError("File %r: %r" % (abs_out_fn, [x.__class__.__name__ for x in handlers]))
elif len(handlers) == 0:
raise NoHandlerMatchError("SparseImageHandler.extract_and_get_next_handler(): Don't know what to do with %r (file_type=%r)" % (abs_out_fn, get_file_type(abs_out_fn)))
else:
return handlers[0]
class MotoPivHandler(FileHandler):
def check(self) -> CheckFileResult:
with open(self.abs_fn, 'rb') as f:
buf = f.read(32)
if buf[0:4] == b'MOTO' and b'MOT_PIV_FULL256' in buf:
if self.image_type == ImageType.SYSTEM:
return CheckFileResult.SYSTEM_IMG
elif self.image_type == ImageType.VENDOR:
return CheckFileResult.VENDOR_IMG
else:
raise ValueError("Bad image_type %r" % self.image_type)
else:
return CheckFileResult.HANDLER_NO_MATCH
def extract_and_get_next_handler(self, stage_dir_rel):
output_fn = self.fn + b".MotoPivHandler"
abs_stage_dir = self.extractor.create_stage_dir(stage_dir_rel)
abs_out_fn = os.path.join(abs_stage_dir, output_fn)
with open(self.abs_fn, 'rb') as input_file:
buf = input_file.read(32)
offset = struct.unpack("<I", buf[24:28])[0]
assert offset <= 1024**2
assert offset % 512 == 0 # Just to make sure it is at least aligned to 512-byte sectors
input_file.seek(offset, 0)
with open(abs_out_fn, 'wb') as output_file:
while True:
buf = input_file.read(1024**2)
if buf == b'':
break
output_file.write(buf)
# Same structure as in SparseImageHandler, maybe we need other handlers later
HANDLER_TYPES = [ExtfsHandler]
handlers = []
for handler_type in HANDLER_TYPES:
handler = handler_type(self.extractor, self.extractor.rel_path(abs_out_fn), image_type=self.image_type, file_type=get_file_type(abs_out_fn))
handler_result = handler.check()
if handler_result != CheckFileResult.HANDLER_NO_MATCH:
assert handler_result in (CheckFileResult.SYSTEM_IMG, CheckFileResult.VENDOR_IMG, CheckFileResult.SYSTEM_OR_VENDOR), "Unexpected handler_result=%r from handler %r" % (handler_result, handler.__class__.__name__)
handlers.append(handler)
if len(handlers) > 1:
raise MultipleHandlerMatchError("File %r: %r" % (abs_out_fn, [x.__class__.__name__ for x in handlers]))
elif len(handlers) == 0:
raise NoHandlerMatchError("MotoPivHandler.extract_and_get_next_handler(): Don't know what to do with %r (file_type=%r)" % (abs_out_fn, get_file_type(abs_out_fn)))
else:
return handlers[0]
class SuperImageHandler(FileHandler):
is_sparse: bool
def check(self) -> CheckFileResult:
self.is_sparse = False
if self.file_type.startswith("Android sparse image, version: 1.0,"):
if self.fn.lower().startswith(b"super"):
self.is_sparse = True
return CheckFileResult.ARCHIVE
else:
return CheckFileResult.HANDLER_NO_MATCH
else:
with open(self.abs_fn, 'rb') as f:
if not liblp.check_magic(f):
return CheckFileResult.HANDLER_NO_MATCH
if not self.fn.lower().startswith(b'super'):
raise ValueError(f"Found liblp magic in {self.fn} but not in super image, this should not happen")
return CheckFileResult.ARCHIVE
def extract_file2dir(self, output_path_rel):
super_img_fn = self.abs_fn
if self.is_sparse:
super_img_fn = self.abs_fn + b'.unsparse'
cmd: List[bytes] = [b"simg2img", self.abs_fn, super_img_fn]
subprocess.check_call(cmd)
super_img = liblp.SuperImage(super_img_fn)
abs_output_path = self.extractor.abs_fn(output_path_rel)
partition_names = super_img.get_partition_names()
found_system = False
for partition_name in ["system", "system_a", "system_b"]:
if partition_name in partition_names:
output_fn = os.path.join(abs_output_path, partition_name.encode() + b".img")
with open(output_fn, 'wb') as f:
super_img.write_partition(partition_name, f)
found_system = True