blob: acd5b6e36e603764132a22a99bd77ad9084d77cf [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
Tao Baoba557702018-03-10 20:41:16 -080020It performs the following checks to assert the integrity of the input zip.
21
Tao Baoafaa0a62017-02-27 15:08:36 -080022 - It verifies the file consistency between the ones in IMAGES/system.img (read
23 via IMAGES/system.map) and the ones under unpacked folder of SYSTEM/. The
24 same check also applies to the vendor image if present.
Tao Baoba557702018-03-10 20:41:16 -080025
26 - It verifies the install-recovery script consistency, by comparing the
27 checksums in the script against the ones of IMAGES/{boot,recovery}.img.
28
29 - It verifies the signed Verified Boot related images, for both of Verified
30 Boot 1.0 and 2.0 (aka AVB).
Tao Baoafaa0a62017-02-27 15:08:36 -080031"""
32
Tao Baoba557702018-03-10 20:41:16 -080033import argparse
34import filecmp
Tao Baoafaa0a62017-02-27 15:08:36 -080035import logging
36import os.path
Tianjie Xu9c384d22017-06-20 17:00:55 -070037import re
Tao Baoba557702018-03-10 20:41:16 -080038import subprocess
Tao Baoc63626b2018-03-07 21:40:24 -080039import zipfile
Tao Baoafaa0a62017-02-27 15:08:36 -080040
Tao Baobb20e8c2018-02-01 12:00:19 -080041import common
Tao Baoafaa0a62017-02-27 15:08:36 -080042
43
Tao Baob418c302017-08-30 15:54:59 -070044def _ReadFile(file_name, unpacked_name, round_up=False):
45 """Constructs and returns a File object. Rounds up its size if needed."""
Tao Baoafaa0a62017-02-27 15:08:36 -080046
Tianjie Xu9c384d22017-06-20 17:00:55 -070047 assert os.path.exists(unpacked_name)
48 with open(unpacked_name, 'r') as f:
49 file_data = f.read()
50 file_size = len(file_data)
51 if round_up:
Tao Baoc765cca2018-01-31 17:32:40 -080052 file_size_rounded_up = common.RoundUpTo4K(file_size)
Tianjie Xu9c384d22017-06-20 17:00:55 -070053 file_data += '\0' * (file_size_rounded_up - file_size)
Tao Baob418c302017-08-30 15:54:59 -070054 return common.File(file_name, file_data)
Tianjie Xu9c384d22017-06-20 17:00:55 -070055
56
57def ValidateFileAgainstSha1(input_tmp, file_name, file_path, expected_sha1):
58 """Check if the file has the expected SHA-1."""
59
Tao Baobb20e8c2018-02-01 12:00:19 -080060 logging.info('Validating the SHA-1 of %s', file_name)
Tianjie Xu9c384d22017-06-20 17:00:55 -070061 unpacked_name = os.path.join(input_tmp, file_path)
62 assert os.path.exists(unpacked_name)
Tao Baob418c302017-08-30 15:54:59 -070063 actual_sha1 = _ReadFile(file_name, unpacked_name, False).sha1
Tianjie Xu9c384d22017-06-20 17:00:55 -070064 assert actual_sha1 == expected_sha1, \
65 'SHA-1 mismatches for {}. actual {}, expected {}'.format(
Tao Baobb20e8c2018-02-01 12:00:19 -080066 file_name, actual_sha1, expected_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -070067
68
Tao Bao63e2f492018-05-11 23:38:46 -070069def ValidateFileConsistency(input_zip, input_tmp, info_dict):
Tianjie Xu9c384d22017-06-20 17:00:55 -070070 """Compare the files from image files and unpacked folders."""
71
Tao Baoafaa0a62017-02-27 15:08:36 -080072 def CheckAllFiles(which):
73 logging.info('Checking %s image.', which)
Tao Baoc63626b2018-03-07 21:40:24 -080074 # Allow having shared blocks when loading the sparse image, because allowing
75 # that doesn't affect the checks below (we will have all the blocks on file,
76 # unless it's skipped due to the holes).
77 image = common.GetSparseImage(which, input_tmp, input_zip, True)
Tao Baoafaa0a62017-02-27 15:08:36 -080078 prefix = '/' + which
79 for entry in image.file_map:
Tao Baoc765cca2018-01-31 17:32:40 -080080 # Skip entries like '__NONZERO-0'.
Tao Baoafaa0a62017-02-27 15:08:36 -080081 if not entry.startswith(prefix):
82 continue
83
84 # Read the blocks that the file resides. Note that it will contain the
85 # bytes past the file length, which is expected to be padded with '\0's.
86 ranges = image.file_map[entry]
Tao Baoc765cca2018-01-31 17:32:40 -080087
88 incomplete = ranges.extra.get('incomplete', False)
89 if incomplete:
90 logging.warning('Skipping %s that has incomplete block list', entry)
91 continue
92
Tao Baoafaa0a62017-02-27 15:08:36 -080093 blocks_sha1 = image.RangeSha1(ranges)
94
95 # The filename under unpacked directory, such as SYSTEM/bin/sh.
96 unpacked_name = os.path.join(
97 input_tmp, which.upper(), entry[(len(prefix) + 1):])
Tao Baob418c302017-08-30 15:54:59 -070098 unpacked_file = _ReadFile(entry, unpacked_name, True)
Tao Baob418c302017-08-30 15:54:59 -070099 file_sha1 = unpacked_file.sha1
Tao Baoafaa0a62017-02-27 15:08:36 -0800100 assert blocks_sha1 == file_sha1, \
101 'file: %s, range: %s, blocks_sha1: %s, file_sha1: %s' % (
102 entry, ranges, blocks_sha1, file_sha1)
103
104 logging.info('Validating file consistency.')
105
Tao Bao63e2f492018-05-11 23:38:46 -0700106 # TODO(b/79617342): Validate non-sparse images.
107 if info_dict.get('extfs_sparse_flag') != '-s':
108 logging.warning('Skipped due to target using non-sparse images')
109 return
110
Tao Baoafaa0a62017-02-27 15:08:36 -0800111 # Verify IMAGES/system.img.
112 CheckAllFiles('system')
113
114 # Verify IMAGES/vendor.img if applicable.
115 if 'VENDOR/' in input_zip.namelist():
116 CheckAllFiles('vendor')
117
118 # Not checking IMAGES/system_other.img since it doesn't have the map file.
119
120
Tianjie Xu9c384d22017-06-20 17:00:55 -0700121def ValidateInstallRecoveryScript(input_tmp, info_dict):
122 """Validate the SHA-1 embedded in install-recovery.sh.
123
124 install-recovery.sh is written in common.py and has the following format:
125
126 1. full recovery:
127 ...
128 if ! applypatch -c type:device:size:SHA-1; then
129 applypatch /system/etc/recovery.img type:device sha1 size && ...
130 ...
131
132 2. recovery from boot:
133 ...
134 applypatch [-b bonus_args] boot_info recovery_info recovery_sha1 \
135 recovery_size patch_info && ...
136 ...
137
138 For full recovery, we want to calculate the SHA-1 of /system/etc/recovery.img
139 and compare it against the one embedded in the script. While for recovery
140 from boot, we want to check the SHA-1 for both recovery.img and boot.img
141 under IMAGES/.
142 """
143
144 script_path = 'SYSTEM/bin/install-recovery.sh'
145 if not os.path.exists(os.path.join(input_tmp, script_path)):
Tao Baobb20e8c2018-02-01 12:00:19 -0800146 logging.info('%s does not exist in input_tmp', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700147 return
148
Tao Baobb20e8c2018-02-01 12:00:19 -0800149 logging.info('Checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700150 with open(os.path.join(input_tmp, script_path), 'r') as script:
151 lines = script.read().strip().split('\n')
152 assert len(lines) >= 6
153 check_cmd = re.search(r'if ! applypatch -c \w+:.+:\w+:(\w+);',
154 lines[1].strip())
155 expected_recovery_check_sha1 = check_cmd.group(1)
156 patch_cmd = re.search(r'(applypatch.+)&&', lines[2].strip())
157 applypatch_argv = patch_cmd.group(1).strip().split()
158
159 full_recovery_image = info_dict.get("full_recovery_image") == "true"
160 if full_recovery_image:
161 assert len(applypatch_argv) == 5
162 # Check we have the same expected SHA-1 of recovery.img in both check mode
163 # and patch mode.
164 expected_recovery_sha1 = applypatch_argv[3].strip()
165 assert expected_recovery_check_sha1 == expected_recovery_sha1
166 ValidateFileAgainstSha1(input_tmp, 'recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800167 'SYSTEM/etc/recovery.img', expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700168 else:
169 # We're patching boot.img to get recovery.img where bonus_args is optional
170 if applypatch_argv[1] == "-b":
171 assert len(applypatch_argv) == 8
172 boot_info_index = 3
173 else:
174 assert len(applypatch_argv) == 6
175 boot_info_index = 1
176
177 # boot_info: boot_type:boot_device:boot_size:boot_sha1
178 boot_info = applypatch_argv[boot_info_index].strip().split(':')
179 assert len(boot_info) == 4
180 ValidateFileAgainstSha1(input_tmp, file_name='boot.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800181 file_path='IMAGES/boot.img',
182 expected_sha1=boot_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700183
184 recovery_sha1_index = boot_info_index + 2
185 expected_recovery_sha1 = applypatch_argv[recovery_sha1_index]
186 assert expected_recovery_check_sha1 == expected_recovery_sha1
187 ValidateFileAgainstSha1(input_tmp, file_name='recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800188 file_path='IMAGES/recovery.img',
189 expected_sha1=expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700190
Tao Baobb20e8c2018-02-01 12:00:19 -0800191 logging.info('Done checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700192
193
Tao Baoba557702018-03-10 20:41:16 -0800194def ValidateVerifiedBootImages(input_tmp, info_dict, options):
195 """Validates the Verified Boot related images.
Tao Baoafaa0a62017-02-27 15:08:36 -0800196
Tao Baoba557702018-03-10 20:41:16 -0800197 For Verified Boot 1.0, it verifies the signatures of the bootable images
198 (boot/recovery etc), as well as the dm-verity metadata in system images
199 (system/vendor/product). For Verified Boot 2.0, it calls avbtool to verify
200 vbmeta.img, which in turn verifies all the descriptors listed in vbmeta.
Tao Baoafaa0a62017-02-27 15:08:36 -0800201
Tao Baoba557702018-03-10 20:41:16 -0800202 Args:
203 input_tmp: The top-level directory of unpacked target-files.zip.
204 info_dict: The loaded info dict.
205 options: A dict that contains the user-supplied public keys to be used for
206 image verification. In particular, 'verity_key' is used to verify the
207 bootable images in VB 1.0, and the vbmeta image in VB 2.0, where
208 applicable. 'verity_key_mincrypt' will be used to verify the system
209 images in VB 1.0.
210
211 Raises:
212 AssertionError: On any verification failure.
213 """
214 # Verified boot 1.0 (images signed with boot_signer and verity_signer).
215 if info_dict.get('boot_signer') == 'true':
216 logging.info('Verifying Verified Boot images...')
217
218 # Verify the boot/recovery images (signed with boot_signer), against the
219 # given X.509 encoded pubkey (or falling back to the one in the info_dict if
220 # none given).
221 verity_key = options['verity_key']
222 if verity_key is None:
223 verity_key = info_dict['verity_key'] + '.x509.pem'
224 for image in ('boot.img', 'recovery.img', 'recovery-two-step.img'):
225 image_path = os.path.join(input_tmp, 'IMAGES', image)
226 if not os.path.exists(image_path):
227 continue
228
229 cmd = ['boot_signer', '-verify', image_path, '-certificate', verity_key]
230 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
231 stdoutdata, _ = proc.communicate()
232 assert proc.returncode == 0, \
233 'Failed to verify {} with boot_signer:\n{}'.format(image, stdoutdata)
234 logging.info(
235 'Verified %s with boot_signer (key: %s):\n%s', image, verity_key,
236 stdoutdata.rstrip())
237
238 # Verify verity signed system images in Verified Boot 1.0. Note that not using
239 # 'elif' here, since 'boot_signer' and 'verity' are not bundled in VB 1.0.
240 if info_dict.get('verity') == 'true':
241 # First verify that the verity key that's built into the root image (as
242 # /verity_key) matches the one given via command line, if any.
243 if info_dict.get("system_root_image") == "true":
244 verity_key_mincrypt = os.path.join(input_tmp, 'ROOT', 'verity_key')
245 else:
246 verity_key_mincrypt = os.path.join(
247 input_tmp, 'BOOT', 'RAMDISK', 'verity_key')
248 assert os.path.exists(verity_key_mincrypt), 'Missing verity_key'
249
250 if options['verity_key_mincrypt'] is None:
251 logging.warn(
252 'Skipped checking the content of /verity_key, as the key file not '
253 'provided. Use --verity_key_mincrypt to specify.')
254 else:
255 expected_key = options['verity_key_mincrypt']
256 assert filecmp.cmp(expected_key, verity_key_mincrypt, shallow=False), \
257 "Mismatching mincrypt verity key files"
258 logging.info('Verified the content of /verity_key')
259
260 # Then verify the verity signed system/vendor/product images, against the
261 # verity pubkey in mincrypt format.
262 for image in ('system.img', 'vendor.img', 'product.img'):
263 image_path = os.path.join(input_tmp, 'IMAGES', image)
264
265 # We are not checking if the image is actually enabled via info_dict (e.g.
266 # 'system_verity_block_device=...'). Because it's most likely a bug that
267 # skips signing some of the images in signed target-files.zip, while
268 # having the top-level verity flag enabled.
269 if not os.path.exists(image_path):
270 continue
271
272 cmd = ['verity_verifier', image_path, '-mincrypt', verity_key_mincrypt]
273 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
274 stdoutdata, _ = proc.communicate()
275 assert proc.returncode == 0, \
276 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
277 image, verity_key_mincrypt, stdoutdata)
278 logging.info(
279 'Verified %s with verity_verifier (key: %s):\n%s', image,
280 verity_key_mincrypt, stdoutdata.rstrip())
281
282 # Handle the case of Verified Boot 2.0 (AVB).
283 if info_dict.get("avb_enable") == "true":
284 logging.info('Verifying Verified Boot 2.0 (AVB) images...')
285
286 key = options['verity_key']
287 if key is None:
288 key = info_dict['avb_vbmeta_key_path']
289 # avbtool verifies all the images that have descriptors listed in vbmeta.
290 image = os.path.join(input_tmp, 'IMAGES', 'vbmeta.img')
291 cmd = ['avbtool', 'verify_image', '--image', image, '--key', key]
292 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
293 stdoutdata, _ = proc.communicate()
294 assert proc.returncode == 0, \
295 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
296 image, key, stdoutdata)
297
298 logging.info(
299 'Verified %s with avbtool (key: %s):\n%s', image, key,
300 stdoutdata.rstrip())
301
302
303def main():
304 parser = argparse.ArgumentParser(
305 description=__doc__,
306 formatter_class=argparse.RawDescriptionHelpFormatter)
307 parser.add_argument(
308 'target_files',
309 help='the input target_files.zip to be validated')
310 parser.add_argument(
311 '--verity_key',
312 help='the verity public key to verify the bootable images (Verified '
313 'Boot 1.0), or the vbmeta image (Verified Boot 2.0), where '
314 'applicable')
315 parser.add_argument(
316 '--verity_key_mincrypt',
317 help='the verity public key in mincrypt format to verify the system '
318 'images, if target using Verified Boot 1.0')
319 args = parser.parse_args()
320
321 # Unprovided args will have 'None' as the value.
322 options = vars(args)
Tao Baoafaa0a62017-02-27 15:08:36 -0800323
324 logging_format = '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s'
325 date_format = '%Y/%m/%d %H:%M:%S'
326 logging.basicConfig(level=logging.INFO, format=logging_format,
327 datefmt=date_format)
328
Tao Baoba557702018-03-10 20:41:16 -0800329 logging.info("Unzipping the input target_files.zip: %s", args.target_files)
330 input_tmp = common.UnzipTemp(args.target_files)
Tao Baoafaa0a62017-02-27 15:08:36 -0800331
Tianjie Xu9c384d22017-06-20 17:00:55 -0700332 info_dict = common.LoadInfoDict(input_tmp)
Tao Bao63e2f492018-05-11 23:38:46 -0700333 with zipfile.ZipFile(args.target_files, 'r') as input_zip:
334 ValidateFileConsistency(input_zip, input_tmp, info_dict)
335
Tianjie Xu9c384d22017-06-20 17:00:55 -0700336 ValidateInstallRecoveryScript(input_tmp, info_dict)
337
Tao Baoba557702018-03-10 20:41:16 -0800338 ValidateVerifiedBootImages(input_tmp, info_dict, options)
339
Tao Baoafaa0a62017-02-27 15:08:36 -0800340 # TODO: Check if the OTA keys have been properly updated (the ones on /system,
341 # in recovery image).
342
Tao Baoafaa0a62017-02-27 15:08:36 -0800343 logging.info("Done.")
344
345
346if __name__ == '__main__':
347 try:
Tao Baoba557702018-03-10 20:41:16 -0800348 main()
Tao Baoafaa0a62017-02-27 15:08:36 -0800349 finally:
350 common.Cleanup()