blob: 09f800f92ec87ffa6623e0206bb2fc819e565b35 [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 Baod32936d2018-05-17 19:42:41 -070093 # TODO(b/79951650): Handle files with non-monotonic ranges.
94 if not ranges.monotonic:
95 logging.warning(
96 'Skipping %s that has non-monotonic ranges: %s', entry, ranges)
97 continue
98
Tao Baoafaa0a62017-02-27 15:08:36 -080099 blocks_sha1 = image.RangeSha1(ranges)
100
101 # The filename under unpacked directory, such as SYSTEM/bin/sh.
102 unpacked_name = os.path.join(
103 input_tmp, which.upper(), entry[(len(prefix) + 1):])
Tao Baob418c302017-08-30 15:54:59 -0700104 unpacked_file = _ReadFile(entry, unpacked_name, True)
Tao Baob418c302017-08-30 15:54:59 -0700105 file_sha1 = unpacked_file.sha1
Tao Baoafaa0a62017-02-27 15:08:36 -0800106 assert blocks_sha1 == file_sha1, \
107 'file: %s, range: %s, blocks_sha1: %s, file_sha1: %s' % (
108 entry, ranges, blocks_sha1, file_sha1)
109
110 logging.info('Validating file consistency.')
111
Tao Bao63e2f492018-05-11 23:38:46 -0700112 # TODO(b/79617342): Validate non-sparse images.
113 if info_dict.get('extfs_sparse_flag') != '-s':
114 logging.warning('Skipped due to target using non-sparse images')
115 return
116
Tao Baoafaa0a62017-02-27 15:08:36 -0800117 # Verify IMAGES/system.img.
118 CheckAllFiles('system')
119
120 # Verify IMAGES/vendor.img if applicable.
121 if 'VENDOR/' in input_zip.namelist():
122 CheckAllFiles('vendor')
123
124 # Not checking IMAGES/system_other.img since it doesn't have the map file.
125
126
Tianjie Xu9c384d22017-06-20 17:00:55 -0700127def ValidateInstallRecoveryScript(input_tmp, info_dict):
128 """Validate the SHA-1 embedded in install-recovery.sh.
129
130 install-recovery.sh is written in common.py and has the following format:
131
132 1. full recovery:
133 ...
Tao Bao4948aed2018-07-13 16:11:16 -0700134 if ! applypatch --check type:device:size:sha1; then
135 applypatch --flash /system/etc/recovery.img \\
136 type:device:size:sha1 && \\
Tianjie Xu9c384d22017-06-20 17:00:55 -0700137 ...
138
139 2. recovery from boot:
140 ...
Tao Bao4948aed2018-07-13 16:11:16 -0700141 if ! applypatch --check type:recovery_device:recovery_size:recovery_sha1; then
142 applypatch [--bonus bonus_args] \\
143 --patch /system/recovery-from-boot.p \\
144 --source type:boot_device:boot_size:boot_sha1 \\
145 --target type:recovery_device:recovery_size:recovery_sha1 && \\
Tianjie Xu9c384d22017-06-20 17:00:55 -0700146 ...
147
148 For full recovery, we want to calculate the SHA-1 of /system/etc/recovery.img
149 and compare it against the one embedded in the script. While for recovery
150 from boot, we want to check the SHA-1 for both recovery.img and boot.img
151 under IMAGES/.
152 """
153
154 script_path = 'SYSTEM/bin/install-recovery.sh'
155 if not os.path.exists(os.path.join(input_tmp, script_path)):
Tao Baobb20e8c2018-02-01 12:00:19 -0800156 logging.info('%s does not exist in input_tmp', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700157 return
158
Tao Baobb20e8c2018-02-01 12:00:19 -0800159 logging.info('Checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700160 with open(os.path.join(input_tmp, script_path), 'r') as script:
161 lines = script.read().strip().split('\n')
Tao Bao4948aed2018-07-13 16:11:16 -0700162 assert len(lines) >= 10
163 check_cmd = re.search(r'if ! applypatch --check (\w+:.+:\w+:\w+);',
Tianjie Xu9c384d22017-06-20 17:00:55 -0700164 lines[1].strip())
Tao Bao4948aed2018-07-13 16:11:16 -0700165 check_partition = check_cmd.group(1)
166 assert len(check_partition.split(':')) == 4
Tianjie Xu9c384d22017-06-20 17:00:55 -0700167
168 full_recovery_image = info_dict.get("full_recovery_image") == "true"
169 if full_recovery_image:
Tao Bao4948aed2018-07-13 16:11:16 -0700170 assert len(lines) == 10, "Invalid line count: {}".format(lines)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700171
Tao Bao4948aed2018-07-13 16:11:16 -0700172 # Expect something like "EMMC:/dev/block/recovery:28:5f9c..62e3".
173 target = re.search(r'--target (.+) &&', lines[4].strip())
174 assert target is not None, \
175 "Failed to parse target line \"{}\"".format(lines[4])
176 flash_partition = target.group(1)
177
178 # Check we have the same recovery target in the check and flash commands.
179 assert check_partition == flash_partition, \
180 "Mismatching targets: {} vs {}".format(check_partition, flash_partition)
181
182 # Validate the SHA-1 of the recovery image.
183 recovery_sha1 = flash_partition.split(':')[3]
184 ValidateFileAgainstSha1(
185 input_tmp, 'recovery.img', 'SYSTEM/etc/recovery.img', recovery_sha1)
186 else:
187 assert len(lines) == 11, "Invalid line count: {}".format(lines)
188
189 # --source boot_type:boot_device:boot_size:boot_sha1
190 source = re.search(r'--source (\w+:.+:\w+:\w+) \\', lines[4].strip())
191 assert source is not None, \
192 "Failed to parse source line \"{}\"".format(lines[4])
193
194 source_partition = source.group(1)
195 source_info = source_partition.split(':')
196 assert len(source_info) == 4, \
197 "Invalid source partition: {}".format(source_partition)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700198 ValidateFileAgainstSha1(input_tmp, file_name='boot.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800199 file_path='IMAGES/boot.img',
Tao Bao4948aed2018-07-13 16:11:16 -0700200 expected_sha1=source_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700201
Tao Bao4948aed2018-07-13 16:11:16 -0700202 # --target recovery_type:recovery_device:recovery_size:recovery_sha1
203 target = re.search(r'--target (\w+:.+:\w+:\w+) && \\', lines[5].strip())
204 assert target is not None, \
205 "Failed to parse target line \"{}\"".format(lines[5])
206 target_partition = target.group(1)
207
208 # Check we have the same recovery target in the check and patch commands.
209 assert check_partition == target_partition, \
210 "Mismatching targets: {} vs {}".format(
211 check_partition, target_partition)
212
213 recovery_info = target_partition.split(':')
214 assert len(recovery_info) == 4, \
215 "Invalid target partition: {}".format(target_partition)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700216 ValidateFileAgainstSha1(input_tmp, file_name='recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800217 file_path='IMAGES/recovery.img',
Tao Bao4948aed2018-07-13 16:11:16 -0700218 expected_sha1=recovery_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700219
Tao Baobb20e8c2018-02-01 12:00:19 -0800220 logging.info('Done checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700221
222
Tao Baoba557702018-03-10 20:41:16 -0800223def ValidateVerifiedBootImages(input_tmp, info_dict, options):
224 """Validates the Verified Boot related images.
Tao Baoafaa0a62017-02-27 15:08:36 -0800225
Tao Baoba557702018-03-10 20:41:16 -0800226 For Verified Boot 1.0, it verifies the signatures of the bootable images
227 (boot/recovery etc), as well as the dm-verity metadata in system images
228 (system/vendor/product). For Verified Boot 2.0, it calls avbtool to verify
229 vbmeta.img, which in turn verifies all the descriptors listed in vbmeta.
Tao Baoafaa0a62017-02-27 15:08:36 -0800230
Tao Baoba557702018-03-10 20:41:16 -0800231 Args:
232 input_tmp: The top-level directory of unpacked target-files.zip.
233 info_dict: The loaded info dict.
234 options: A dict that contains the user-supplied public keys to be used for
235 image verification. In particular, 'verity_key' is used to verify the
236 bootable images in VB 1.0, and the vbmeta image in VB 2.0, where
237 applicable. 'verity_key_mincrypt' will be used to verify the system
238 images in VB 1.0.
239
240 Raises:
241 AssertionError: On any verification failure.
242 """
243 # Verified boot 1.0 (images signed with boot_signer and verity_signer).
244 if info_dict.get('boot_signer') == 'true':
245 logging.info('Verifying Verified Boot images...')
246
247 # Verify the boot/recovery images (signed with boot_signer), against the
248 # given X.509 encoded pubkey (or falling back to the one in the info_dict if
249 # none given).
250 verity_key = options['verity_key']
251 if verity_key is None:
252 verity_key = info_dict['verity_key'] + '.x509.pem'
253 for image in ('boot.img', 'recovery.img', 'recovery-two-step.img'):
254 image_path = os.path.join(input_tmp, 'IMAGES', image)
255 if not os.path.exists(image_path):
256 continue
257
258 cmd = ['boot_signer', '-verify', image_path, '-certificate', verity_key]
259 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
260 stdoutdata, _ = proc.communicate()
261 assert proc.returncode == 0, \
262 'Failed to verify {} with boot_signer:\n{}'.format(image, stdoutdata)
263 logging.info(
264 'Verified %s with boot_signer (key: %s):\n%s', image, verity_key,
265 stdoutdata.rstrip())
266
267 # Verify verity signed system images in Verified Boot 1.0. Note that not using
268 # 'elif' here, since 'boot_signer' and 'verity' are not bundled in VB 1.0.
269 if info_dict.get('verity') == 'true':
270 # First verify that the verity key that's built into the root image (as
271 # /verity_key) matches the one given via command line, if any.
272 if info_dict.get("system_root_image") == "true":
273 verity_key_mincrypt = os.path.join(input_tmp, 'ROOT', 'verity_key')
274 else:
275 verity_key_mincrypt = os.path.join(
276 input_tmp, 'BOOT', 'RAMDISK', 'verity_key')
277 assert os.path.exists(verity_key_mincrypt), 'Missing verity_key'
278
279 if options['verity_key_mincrypt'] is None:
280 logging.warn(
281 'Skipped checking the content of /verity_key, as the key file not '
282 'provided. Use --verity_key_mincrypt to specify.')
283 else:
284 expected_key = options['verity_key_mincrypt']
285 assert filecmp.cmp(expected_key, verity_key_mincrypt, shallow=False), \
286 "Mismatching mincrypt verity key files"
287 logging.info('Verified the content of /verity_key')
288
289 # Then verify the verity signed system/vendor/product images, against the
290 # verity pubkey in mincrypt format.
291 for image in ('system.img', 'vendor.img', 'product.img'):
292 image_path = os.path.join(input_tmp, 'IMAGES', image)
293
294 # We are not checking if the image is actually enabled via info_dict (e.g.
295 # 'system_verity_block_device=...'). Because it's most likely a bug that
296 # skips signing some of the images in signed target-files.zip, while
297 # having the top-level verity flag enabled.
298 if not os.path.exists(image_path):
299 continue
300
301 cmd = ['verity_verifier', image_path, '-mincrypt', verity_key_mincrypt]
302 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
303 stdoutdata, _ = proc.communicate()
304 assert proc.returncode == 0, \
305 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
306 image, verity_key_mincrypt, stdoutdata)
307 logging.info(
308 'Verified %s with verity_verifier (key: %s):\n%s', image,
309 verity_key_mincrypt, stdoutdata.rstrip())
310
311 # Handle the case of Verified Boot 2.0 (AVB).
312 if info_dict.get("avb_enable") == "true":
313 logging.info('Verifying Verified Boot 2.0 (AVB) images...')
314
315 key = options['verity_key']
316 if key is None:
317 key = info_dict['avb_vbmeta_key_path']
Tao Bao02a08592018-07-22 12:40:45 -0700318
Tao Baoba557702018-03-10 20:41:16 -0800319 # avbtool verifies all the images that have descriptors listed in vbmeta.
320 image = os.path.join(input_tmp, 'IMAGES', 'vbmeta.img')
321 cmd = ['avbtool', 'verify_image', '--image', image, '--key', key]
Tao Bao02a08592018-07-22 12:40:45 -0700322
323 # Append the args for chained partitions if any.
324 for partition in common.AVB_PARTITIONS:
325 key_name = 'avb_' + partition + '_key_path'
326 if info_dict.get(key_name) is not None:
327 chained_partition_arg = common.GetAvbChainedPartitionArg(
328 partition, info_dict, options[key_name])
329 cmd.extend(["--expected_chain_partition", chained_partition_arg])
330
Tao Baoba557702018-03-10 20:41:16 -0800331 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
332 stdoutdata, _ = proc.communicate()
333 assert proc.returncode == 0, \
334 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
335 image, key, stdoutdata)
336
337 logging.info(
338 'Verified %s with avbtool (key: %s):\n%s', image, key,
339 stdoutdata.rstrip())
340
341
342def main():
343 parser = argparse.ArgumentParser(
344 description=__doc__,
345 formatter_class=argparse.RawDescriptionHelpFormatter)
346 parser.add_argument(
347 'target_files',
348 help='the input target_files.zip to be validated')
349 parser.add_argument(
350 '--verity_key',
351 help='the verity public key to verify the bootable images (Verified '
Tao Bao02a08592018-07-22 12:40:45 -0700352 'Boot 1.0), or the vbmeta image (Verified Boot 2.0, aka AVB), where '
Tao Baoba557702018-03-10 20:41:16 -0800353 'applicable')
Tao Bao02a08592018-07-22 12:40:45 -0700354 for partition in common.AVB_PARTITIONS:
355 parser.add_argument(
356 '--avb_' + partition + '_key_path',
357 help='the public or private key in PEM format to verify AVB chained '
358 'partition of {}'.format(partition))
Tao Baoba557702018-03-10 20:41:16 -0800359 parser.add_argument(
360 '--verity_key_mincrypt',
361 help='the verity public key in mincrypt format to verify the system '
362 'images, if target using Verified Boot 1.0')
363 args = parser.parse_args()
364
365 # Unprovided args will have 'None' as the value.
366 options = vars(args)
Tao Baoafaa0a62017-02-27 15:08:36 -0800367
368 logging_format = '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s'
369 date_format = '%Y/%m/%d %H:%M:%S'
370 logging.basicConfig(level=logging.INFO, format=logging_format,
371 datefmt=date_format)
372
Tao Baoba557702018-03-10 20:41:16 -0800373 logging.info("Unzipping the input target_files.zip: %s", args.target_files)
374 input_tmp = common.UnzipTemp(args.target_files)
Tao Baoafaa0a62017-02-27 15:08:36 -0800375
Tianjie Xu9c384d22017-06-20 17:00:55 -0700376 info_dict = common.LoadInfoDict(input_tmp)
Tao Bao63e2f492018-05-11 23:38:46 -0700377 with zipfile.ZipFile(args.target_files, 'r') as input_zip:
378 ValidateFileConsistency(input_zip, input_tmp, info_dict)
379
Tianjie Xu9c384d22017-06-20 17:00:55 -0700380 ValidateInstallRecoveryScript(input_tmp, info_dict)
381
Tao Baoba557702018-03-10 20:41:16 -0800382 ValidateVerifiedBootImages(input_tmp, info_dict, options)
383
Tao Baoafaa0a62017-02-27 15:08:36 -0800384 # TODO: Check if the OTA keys have been properly updated (the ones on /system,
385 # in recovery image).
386
Tao Baoafaa0a62017-02-27 15:08:36 -0800387 logging.info("Done.")
388
389
390if __name__ == '__main__':
391 try:
Tao Baoba557702018-03-10 20:41:16 -0800392 main()
Tao Baoafaa0a62017-02-27 15:08:36 -0800393 finally:
394 common.Cleanup()