blob: db1ba2eb65dfdf503f85b1fa53295928ab27158a [file] [log] [blame]
Tao Baoafaa0a62017-02-27 15:08:36 -08001#!/usr/bin/env python
2
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Validate a given (signed) target_files.zip.
19
20It performs checks to ensure the integrity of the input zip.
21 - It verifies the file consistency between the ones in IMAGES/system.img (read
22 via IMAGES/system.map) and the ones under unpacked folder of SYSTEM/. The
23 same check also applies to the vendor image if present.
24"""
25
Tao Baoafaa0a62017-02-27 15:08:36 -080026import logging
27import os.path
Tianjie Xu9c384d22017-06-20 17:00:55 -070028import re
Tao Baoafaa0a62017-02-27 15:08:36 -080029import sys
Tao Baof6f13ac2018-03-07 21:40:24 -080030import zipfile
Tao Baoafaa0a62017-02-27 15:08:36 -080031
Tao Baobb20e8c2018-02-01 12:00:19 -080032import common
Tao Baoafaa0a62017-02-27 15:08:36 -080033
34
Tao Baob418c302017-08-30 15:54:59 -070035def _ReadFile(file_name, unpacked_name, round_up=False):
36 """Constructs and returns a File object. Rounds up its size if needed."""
Tao Baoafaa0a62017-02-27 15:08:36 -080037
Tianjie Xu9c384d22017-06-20 17:00:55 -070038 assert os.path.exists(unpacked_name)
39 with open(unpacked_name, 'r') as f:
40 file_data = f.read()
41 file_size = len(file_data)
42 if round_up:
Tao Baoc765cca2018-01-31 17:32:40 -080043 file_size_rounded_up = common.RoundUpTo4K(file_size)
Tianjie Xu9c384d22017-06-20 17:00:55 -070044 file_data += '\0' * (file_size_rounded_up - file_size)
Tao Baob418c302017-08-30 15:54:59 -070045 return common.File(file_name, file_data)
Tianjie Xu9c384d22017-06-20 17:00:55 -070046
47
48def ValidateFileAgainstSha1(input_tmp, file_name, file_path, expected_sha1):
49 """Check if the file has the expected SHA-1."""
50
Tao Baobb20e8c2018-02-01 12:00:19 -080051 logging.info('Validating the SHA-1 of %s', file_name)
Tianjie Xu9c384d22017-06-20 17:00:55 -070052 unpacked_name = os.path.join(input_tmp, file_path)
53 assert os.path.exists(unpacked_name)
Tao Baob418c302017-08-30 15:54:59 -070054 actual_sha1 = _ReadFile(file_name, unpacked_name, False).sha1
Tianjie Xu9c384d22017-06-20 17:00:55 -070055 assert actual_sha1 == expected_sha1, \
56 'SHA-1 mismatches for {}. actual {}, expected {}'.format(
Tao Baobb20e8c2018-02-01 12:00:19 -080057 file_name, actual_sha1, expected_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -070058
59
60def ValidateFileConsistency(input_zip, input_tmp):
61 """Compare the files from image files and unpacked folders."""
62
Tao Baoafaa0a62017-02-27 15:08:36 -080063 def CheckAllFiles(which):
64 logging.info('Checking %s image.', which)
Tao Baof6f13ac2018-03-07 21:40:24 -080065 # Allow having shared blocks when loading the sparse image, because allowing
66 # that doesn't affect the checks below (we will have all the blocks on file,
67 # unless it's skipped due to the holes).
68 image = common.GetSparseImage(which, input_tmp, input_zip, True)
Tao Baoafaa0a62017-02-27 15:08:36 -080069 prefix = '/' + which
70 for entry in image.file_map:
Tao Baoc765cca2018-01-31 17:32:40 -080071 # Skip entries like '__NONZERO-0'.
Tao Baoafaa0a62017-02-27 15:08:36 -080072 if not entry.startswith(prefix):
73 continue
74
75 # Read the blocks that the file resides. Note that it will contain the
76 # bytes past the file length, which is expected to be padded with '\0's.
77 ranges = image.file_map[entry]
Tao Baoc765cca2018-01-31 17:32:40 -080078
79 incomplete = ranges.extra.get('incomplete', False)
80 if incomplete:
81 logging.warning('Skipping %s that has incomplete block list', entry)
82 continue
83
Tao Baoafaa0a62017-02-27 15:08:36 -080084 blocks_sha1 = image.RangeSha1(ranges)
85
86 # The filename under unpacked directory, such as SYSTEM/bin/sh.
87 unpacked_name = os.path.join(
88 input_tmp, which.upper(), entry[(len(prefix) + 1):])
Tao Baob418c302017-08-30 15:54:59 -070089 unpacked_file = _ReadFile(entry, unpacked_name, True)
Tao Baob418c302017-08-30 15:54:59 -070090 file_sha1 = unpacked_file.sha1
Tao Baoafaa0a62017-02-27 15:08:36 -080091 assert blocks_sha1 == file_sha1, \
92 'file: %s, range: %s, blocks_sha1: %s, file_sha1: %s' % (
93 entry, ranges, blocks_sha1, file_sha1)
94
95 logging.info('Validating file consistency.')
96
97 # Verify IMAGES/system.img.
98 CheckAllFiles('system')
99
100 # Verify IMAGES/vendor.img if applicable.
101 if 'VENDOR/' in input_zip.namelist():
102 CheckAllFiles('vendor')
103
104 # Not checking IMAGES/system_other.img since it doesn't have the map file.
105
106
Tianjie Xu9c384d22017-06-20 17:00:55 -0700107def ValidateInstallRecoveryScript(input_tmp, info_dict):
108 """Validate the SHA-1 embedded in install-recovery.sh.
109
110 install-recovery.sh is written in common.py and has the following format:
111
112 1. full recovery:
113 ...
114 if ! applypatch -c type:device:size:SHA-1; then
115 applypatch /system/etc/recovery.img type:device sha1 size && ...
116 ...
117
118 2. recovery from boot:
119 ...
120 applypatch [-b bonus_args] boot_info recovery_info recovery_sha1 \
121 recovery_size patch_info && ...
122 ...
123
124 For full recovery, we want to calculate the SHA-1 of /system/etc/recovery.img
125 and compare it against the one embedded in the script. While for recovery
126 from boot, we want to check the SHA-1 for both recovery.img and boot.img
127 under IMAGES/.
128 """
129
130 script_path = 'SYSTEM/bin/install-recovery.sh'
131 if not os.path.exists(os.path.join(input_tmp, script_path)):
Tao Baobb20e8c2018-02-01 12:00:19 -0800132 logging.info('%s does not exist in input_tmp', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700133 return
134
Tao Baobb20e8c2018-02-01 12:00:19 -0800135 logging.info('Checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700136 with open(os.path.join(input_tmp, script_path), 'r') as script:
137 lines = script.read().strip().split('\n')
138 assert len(lines) >= 6
139 check_cmd = re.search(r'if ! applypatch -c \w+:.+:\w+:(\w+);',
140 lines[1].strip())
141 expected_recovery_check_sha1 = check_cmd.group(1)
142 patch_cmd = re.search(r'(applypatch.+)&&', lines[2].strip())
143 applypatch_argv = patch_cmd.group(1).strip().split()
144
145 full_recovery_image = info_dict.get("full_recovery_image") == "true"
146 if full_recovery_image:
147 assert len(applypatch_argv) == 5
148 # Check we have the same expected SHA-1 of recovery.img in both check mode
149 # and patch mode.
150 expected_recovery_sha1 = applypatch_argv[3].strip()
151 assert expected_recovery_check_sha1 == expected_recovery_sha1
152 ValidateFileAgainstSha1(input_tmp, 'recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800153 'SYSTEM/etc/recovery.img', expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700154 else:
155 # We're patching boot.img to get recovery.img where bonus_args is optional
156 if applypatch_argv[1] == "-b":
157 assert len(applypatch_argv) == 8
158 boot_info_index = 3
159 else:
160 assert len(applypatch_argv) == 6
161 boot_info_index = 1
162
163 # boot_info: boot_type:boot_device:boot_size:boot_sha1
164 boot_info = applypatch_argv[boot_info_index].strip().split(':')
165 assert len(boot_info) == 4
166 ValidateFileAgainstSha1(input_tmp, file_name='boot.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800167 file_path='IMAGES/boot.img',
168 expected_sha1=boot_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700169
170 recovery_sha1_index = boot_info_index + 2
171 expected_recovery_sha1 = applypatch_argv[recovery_sha1_index]
172 assert expected_recovery_check_sha1 == expected_recovery_sha1
173 ValidateFileAgainstSha1(input_tmp, file_name='recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800174 file_path='IMAGES/recovery.img',
175 expected_sha1=expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700176
Tao Baobb20e8c2018-02-01 12:00:19 -0800177 logging.info('Done checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700178
179
Tao Baoafaa0a62017-02-27 15:08:36 -0800180def main(argv):
181 def option_handler():
182 return True
183
184 args = common.ParseOptions(
185 argv, __doc__, extra_opts="",
186 extra_long_opts=[],
187 extra_option_handler=option_handler)
188
189 if len(args) != 1:
190 common.Usage(__doc__)
191 sys.exit(1)
192
193 logging_format = '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s'
194 date_format = '%Y/%m/%d %H:%M:%S'
195 logging.basicConfig(level=logging.INFO, format=logging_format,
196 datefmt=date_format)
197
198 logging.info("Unzipping the input target_files.zip: %s", args[0])
Tao Baodba59ee2018-01-09 13:21:02 -0800199 input_tmp = common.UnzipTemp(args[0])
Tao Baoafaa0a62017-02-27 15:08:36 -0800200
Tao Baodba59ee2018-01-09 13:21:02 -0800201 with zipfile.ZipFile(args[0], 'r') as input_zip:
202 ValidateFileConsistency(input_zip, input_tmp)
Tao Baoafaa0a62017-02-27 15:08:36 -0800203
Tianjie Xu9c384d22017-06-20 17:00:55 -0700204 info_dict = common.LoadInfoDict(input_tmp)
205 ValidateInstallRecoveryScript(input_tmp, info_dict)
206
Tao Baoafaa0a62017-02-27 15:08:36 -0800207 # TODO: Check if the OTA keys have been properly updated (the ones on /system,
208 # in recovery image).
209
Tao Baoafaa0a62017-02-27 15:08:36 -0800210 logging.info("Done.")
211
212
213if __name__ == '__main__':
214 try:
215 main(sys.argv[1:])
216 finally:
217 common.Cleanup()