blob: cfe3139f813443f384fae96f874ef781af343275 [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 Baoc63626b2018-03-07 21:40:24 -080038import zipfile
Tao Bao22632cc2019-10-03 23:12:55 -070039from hashlib import sha1
Tao Baoafaa0a62017-02-27 15:08:36 -080040
Tao Baobb20e8c2018-02-01 12:00:19 -080041import common
Tao Bao22632cc2019-10-03 23:12:55 -070042import rangelib
Tao Baoafaa0a62017-02-27 15:08:36 -080043
44
Tao Baob418c302017-08-30 15:54:59 -070045def _ReadFile(file_name, unpacked_name, round_up=False):
46 """Constructs and returns a File object. Rounds up its size if needed."""
Tianjie Xu9c384d22017-06-20 17:00:55 -070047 assert os.path.exists(unpacked_name)
Tao Baoda30cfa2017-12-01 16:19:46 -080048 with open(unpacked_name, 'rb') as f:
Tianjie Xu9c384d22017-06-20 17:00:55 -070049 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)
Tao Bao22632cc2019-10-03 23:12:55 -070053 file_data += b'\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
Tao Bao2a20f342018-12-03 15:08:23 -080088 # Use the original RangeSet if applicable, which includes the shared
89 # blocks. And this needs to happen before checking the monotonicity flag.
90 if ranges.extra.get('uses_shared_blocks'):
91 file_ranges = ranges.extra['uses_shared_blocks']
92 else:
93 file_ranges = ranges
94
xunchangc0f77ee2019-02-20 15:03:43 -080095 incomplete = file_ranges.extra.get('incomplete', False)
96 if incomplete:
97 logging.warning('Skipping %s that has incomplete block list', entry)
98 continue
99
Tao Bao22632cc2019-10-03 23:12:55 -0700100 # If the file has non-monotonic ranges, read each range in order.
Tao Bao2a20f342018-12-03 15:08:23 -0800101 if not file_ranges.monotonic:
Tao Bao22632cc2019-10-03 23:12:55 -0700102 h = sha1()
103 for file_range in file_ranges.extra['text_str'].split(' '):
104 for data in image.ReadRangeSet(rangelib.RangeSet(file_range)):
105 h.update(data)
106 blocks_sha1 = h.hexdigest()
107 else:
108 blocks_sha1 = image.RangeSha1(file_ranges)
Tao Baoafaa0a62017-02-27 15:08:36 -0800109
110 # The filename under unpacked directory, such as SYSTEM/bin/sh.
111 unpacked_name = os.path.join(
112 input_tmp, which.upper(), entry[(len(prefix) + 1):])
Tao Baob418c302017-08-30 15:54:59 -0700113 unpacked_file = _ReadFile(entry, unpacked_name, True)
Tao Baob418c302017-08-30 15:54:59 -0700114 file_sha1 = unpacked_file.sha1
Tao Baoafaa0a62017-02-27 15:08:36 -0800115 assert blocks_sha1 == file_sha1, \
116 'file: %s, range: %s, blocks_sha1: %s, file_sha1: %s' % (
Tao Bao2a20f342018-12-03 15:08:23 -0800117 entry, file_ranges, blocks_sha1, file_sha1)
Tao Baoafaa0a62017-02-27 15:08:36 -0800118
119 logging.info('Validating file consistency.')
120
Tao Bao63e2f492018-05-11 23:38:46 -0700121 # TODO(b/79617342): Validate non-sparse images.
122 if info_dict.get('extfs_sparse_flag') != '-s':
123 logging.warning('Skipped due to target using non-sparse images')
124 return
125
Tao Baoafaa0a62017-02-27 15:08:36 -0800126 # Verify IMAGES/system.img.
127 CheckAllFiles('system')
128
129 # Verify IMAGES/vendor.img if applicable.
130 if 'VENDOR/' in input_zip.namelist():
131 CheckAllFiles('vendor')
132
133 # Not checking IMAGES/system_other.img since it doesn't have the map file.
134
135
Tianjie Xu9c384d22017-06-20 17:00:55 -0700136def ValidateInstallRecoveryScript(input_tmp, info_dict):
137 """Validate the SHA-1 embedded in install-recovery.sh.
138
139 install-recovery.sh is written in common.py and has the following format:
140
141 1. full recovery:
142 ...
Tao Bao4948aed2018-07-13 16:11:16 -0700143 if ! applypatch --check type:device:size:sha1; then
Bill Peckhame868aec2019-09-17 17:06:47 -0700144 applypatch --flash /vendor/etc/recovery.img \\
Tao Bao4948aed2018-07-13 16:11:16 -0700145 type:device:size:sha1 && \\
Tianjie Xu9c384d22017-06-20 17:00:55 -0700146 ...
147
148 2. recovery from boot:
149 ...
Tao Bao4948aed2018-07-13 16:11:16 -0700150 if ! applypatch --check type:recovery_device:recovery_size:recovery_sha1; then
151 applypatch [--bonus bonus_args] \\
Bill Peckhame868aec2019-09-17 17:06:47 -0700152 --patch /vendor/recovery-from-boot.p \\
Tao Bao4948aed2018-07-13 16:11:16 -0700153 --source type:boot_device:boot_size:boot_sha1 \\
154 --target type:recovery_device:recovery_size:recovery_sha1 && \\
Tianjie Xu9c384d22017-06-20 17:00:55 -0700155 ...
156
Bill Peckhame868aec2019-09-17 17:06:47 -0700157 For full recovery, we want to calculate the SHA-1 of /vendor/etc/recovery.img
Tianjie Xu9c384d22017-06-20 17:00:55 -0700158 and compare it against the one embedded in the script. While for recovery
159 from boot, we want to check the SHA-1 for both recovery.img and boot.img
160 under IMAGES/.
161 """
162
Bill Peckhame868aec2019-09-17 17:06:47 -0700163 board_uses_vendorimage = info_dict.get("board_uses_vendorimage") == "true"
164
165 if board_uses_vendorimage:
166 script_path = 'VENDOR/bin/install-recovery.sh'
167 recovery_img = 'VENDOR/etc/recovery.img'
168 else:
169 script_path = 'SYSTEM/vendor/bin/install-recovery.sh'
170 recovery_img = 'SYSTEM/vendor/etc/recovery.img'
171
Tianjie Xu9c384d22017-06-20 17:00:55 -0700172 if not os.path.exists(os.path.join(input_tmp, script_path)):
Tao Baobb20e8c2018-02-01 12:00:19 -0800173 logging.info('%s does not exist in input_tmp', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700174 return
175
Tao Baobb20e8c2018-02-01 12:00:19 -0800176 logging.info('Checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700177 with open(os.path.join(input_tmp, script_path), 'r') as script:
178 lines = script.read().strip().split('\n')
Tao Bao4948aed2018-07-13 16:11:16 -0700179 assert len(lines) >= 10
180 check_cmd = re.search(r'if ! applypatch --check (\w+:.+:\w+:\w+);',
Tianjie Xu9c384d22017-06-20 17:00:55 -0700181 lines[1].strip())
Tao Bao4948aed2018-07-13 16:11:16 -0700182 check_partition = check_cmd.group(1)
183 assert len(check_partition.split(':')) == 4
Tianjie Xu9c384d22017-06-20 17:00:55 -0700184
185 full_recovery_image = info_dict.get("full_recovery_image") == "true"
186 if full_recovery_image:
Tao Bao4948aed2018-07-13 16:11:16 -0700187 assert len(lines) == 10, "Invalid line count: {}".format(lines)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700188
Tao Bao4948aed2018-07-13 16:11:16 -0700189 # Expect something like "EMMC:/dev/block/recovery:28:5f9c..62e3".
190 target = re.search(r'--target (.+) &&', lines[4].strip())
191 assert target is not None, \
192 "Failed to parse target line \"{}\"".format(lines[4])
193 flash_partition = target.group(1)
194
195 # Check we have the same recovery target in the check and flash commands.
196 assert check_partition == flash_partition, \
Kelvin Zhang4093d602021-05-25 09:17:38 -0400197 "Mismatching targets: {} vs {}".format(
198 check_partition, flash_partition)
Tao Bao4948aed2018-07-13 16:11:16 -0700199
200 # Validate the SHA-1 of the recovery image.
201 recovery_sha1 = flash_partition.split(':')[3]
202 ValidateFileAgainstSha1(
Bill Peckhame868aec2019-09-17 17:06:47 -0700203 input_tmp, 'recovery.img', recovery_img, recovery_sha1)
Tao Bao4948aed2018-07-13 16:11:16 -0700204 else:
205 assert len(lines) == 11, "Invalid line count: {}".format(lines)
206
207 # --source boot_type:boot_device:boot_size:boot_sha1
208 source = re.search(r'--source (\w+:.+:\w+:\w+) \\', lines[4].strip())
209 assert source is not None, \
210 "Failed to parse source line \"{}\"".format(lines[4])
211
212 source_partition = source.group(1)
213 source_info = source_partition.split(':')
214 assert len(source_info) == 4, \
215 "Invalid source partition: {}".format(source_partition)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700216 ValidateFileAgainstSha1(input_tmp, file_name='boot.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800217 file_path='IMAGES/boot.img',
Tao Bao4948aed2018-07-13 16:11:16 -0700218 expected_sha1=source_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700219
Tao Bao4948aed2018-07-13 16:11:16 -0700220 # --target recovery_type:recovery_device:recovery_size:recovery_sha1
221 target = re.search(r'--target (\w+:.+:\w+:\w+) && \\', lines[5].strip())
222 assert target is not None, \
223 "Failed to parse target line \"{}\"".format(lines[5])
224 target_partition = target.group(1)
225
226 # Check we have the same recovery target in the check and patch commands.
227 assert check_partition == target_partition, \
228 "Mismatching targets: {} vs {}".format(
229 check_partition, target_partition)
230
231 recovery_info = target_partition.split(':')
232 assert len(recovery_info) == 4, \
233 "Invalid target partition: {}".format(target_partition)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700234 ValidateFileAgainstSha1(input_tmp, file_name='recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800235 file_path='IMAGES/recovery.img',
Tao Bao4948aed2018-07-13 16:11:16 -0700236 expected_sha1=recovery_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700237
Tao Baobb20e8c2018-02-01 12:00:19 -0800238 logging.info('Done checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700239
Tianjie2e0b8352021-01-12 14:04:58 -0800240
Kelvin Zhang5d2b56b2020-06-26 11:37:28 -0400241# Symlink files in `src` to `dst`, if the files do not
242# already exists in `dst` directory.
243def symlinkIfNotExists(src, dst):
244 if not os.path.isdir(src):
245 return
246 for filename in os.listdir(src):
247 if os.path.exists(os.path.join(dst, filename)):
248 continue
249 os.symlink(os.path.join(src, filename), os.path.join(dst, filename))
Tianjie Xu9c384d22017-06-20 17:00:55 -0700250
Tianjie2e0b8352021-01-12 14:04:58 -0800251
Kelvin Zhang4093d602021-05-25 09:17:38 -0400252def ValidatePartitionFingerprints(input_tmp, info_dict):
253 build_info = common.BuildInfo(info_dict)
254 # Expected format:
255 # Prop: com.android.build.vendor.fingerprint -> 'generic/aosp_cf_x86_64_phone/vsoc_x86_64:S/AOSP.MASTER/7335886:userdebug/test-keys'
256 # Prop: com.android.build.vendor_boot.fingerprint -> 'generic/aosp_cf_x86_64_phone/vsoc_x86_64:S/AOSP.MASTER/7335886:userdebug/test-keys'
257 p = re.compile(
258 r"Prop: com.android.build.(?P<partition>\w+).fingerprint -> '(?P<fingerprint>[\w\/:\.-]+)'")
259 for vbmeta_partition in ["vbmeta", "vbmeta_system"]:
260 image = os.path.join(input_tmp, "IMAGES", vbmeta_partition + ".img")
261 output = common.RunAndCheckOutput(
262 [info_dict["avb_avbtool"], "info_image", "--image", image])
263 matches = p.findall(output)
264 for (partition, fingerprint) in matches:
265 actual_fingerprint = build_info.GetPartitionFingerprint(
266 partition)
267 if actual_fingerprint is None:
268 logging.warning(
269 "Failed to get fingerprint for partition %s", partition)
270 continue
271 assert fingerprint == actual_fingerprint, "Fingerprint mismatch for partition {}, expected: {} actual: {}".format(
272 partition, fingerprint, actual_fingerprint)
273
274
Tao Baoba557702018-03-10 20:41:16 -0800275def ValidateVerifiedBootImages(input_tmp, info_dict, options):
276 """Validates the Verified Boot related images.
Tao Baoafaa0a62017-02-27 15:08:36 -0800277
Tao Baoba557702018-03-10 20:41:16 -0800278 For Verified Boot 1.0, it verifies the signatures of the bootable images
279 (boot/recovery etc), as well as the dm-verity metadata in system images
280 (system/vendor/product). For Verified Boot 2.0, it calls avbtool to verify
281 vbmeta.img, which in turn verifies all the descriptors listed in vbmeta.
Tao Baoafaa0a62017-02-27 15:08:36 -0800282
Tao Baoba557702018-03-10 20:41:16 -0800283 Args:
284 input_tmp: The top-level directory of unpacked target-files.zip.
285 info_dict: The loaded info dict.
286 options: A dict that contains the user-supplied public keys to be used for
287 image verification. In particular, 'verity_key' is used to verify the
288 bootable images in VB 1.0, and the vbmeta image in VB 2.0, where
289 applicable. 'verity_key_mincrypt' will be used to verify the system
290 images in VB 1.0.
291
292 Raises:
293 AssertionError: On any verification failure.
294 """
Kelvin Zhang5d2b56b2020-06-26 11:37:28 -0400295 # See bug 159299583
296 # After commit 5277d1015, some images (e.g. acpio.img and tos.img) are no
297 # longer copied from RADIO to the IMAGES folder. But avbtool assumes that
298 # images are in IMAGES folder. So we symlink them.
299 symlinkIfNotExists(os.path.join(input_tmp, "RADIO"),
Kelvin Zhang4093d602021-05-25 09:17:38 -0400300 os.path.join(input_tmp, "IMAGES"))
Tao Baoba557702018-03-10 20:41:16 -0800301 # Verified boot 1.0 (images signed with boot_signer and verity_signer).
302 if info_dict.get('boot_signer') == 'true':
303 logging.info('Verifying Verified Boot images...')
304
305 # Verify the boot/recovery images (signed with boot_signer), against the
306 # given X.509 encoded pubkey (or falling back to the one in the info_dict if
307 # none given).
308 verity_key = options['verity_key']
309 if verity_key is None:
310 verity_key = info_dict['verity_key'] + '.x509.pem'
311 for image in ('boot.img', 'recovery.img', 'recovery-two-step.img'):
Tao Bao04808502019-07-25 23:11:41 -0700312 if image == 'recovery-two-step.img':
313 image_path = os.path.join(input_tmp, 'OTA', image)
314 else:
315 image_path = os.path.join(input_tmp, 'IMAGES', image)
Tao Baoba557702018-03-10 20:41:16 -0800316 if not os.path.exists(image_path):
317 continue
318
319 cmd = ['boot_signer', '-verify', image_path, '-certificate', verity_key]
Tao Bao73dd4f42018-10-04 16:25:33 -0700320 proc = common.Run(cmd)
Tao Baoba557702018-03-10 20:41:16 -0800321 stdoutdata, _ = proc.communicate()
322 assert proc.returncode == 0, \
323 'Failed to verify {} with boot_signer:\n{}'.format(image, stdoutdata)
324 logging.info(
325 'Verified %s with boot_signer (key: %s):\n%s', image, verity_key,
326 stdoutdata.rstrip())
327
328 # Verify verity signed system images in Verified Boot 1.0. Note that not using
329 # 'elif' here, since 'boot_signer' and 'verity' are not bundled in VB 1.0.
330 if info_dict.get('verity') == 'true':
Tao Baoc9981932019-09-16 12:10:43 -0700331 # First verify that the verity key is built into the root image (regardless
332 # of system-as-root).
333 verity_key_mincrypt = os.path.join(input_tmp, 'ROOT', 'verity_key')
Tao Baoba557702018-03-10 20:41:16 -0800334 assert os.path.exists(verity_key_mincrypt), 'Missing verity_key'
335
Tao Baoc9981932019-09-16 12:10:43 -0700336 # Verify /verity_key matches the one given via command line, if any.
Tao Baoba557702018-03-10 20:41:16 -0800337 if options['verity_key_mincrypt'] is None:
338 logging.warn(
339 'Skipped checking the content of /verity_key, as the key file not '
340 'provided. Use --verity_key_mincrypt to specify.')
341 else:
342 expected_key = options['verity_key_mincrypt']
343 assert filecmp.cmp(expected_key, verity_key_mincrypt, shallow=False), \
344 "Mismatching mincrypt verity key files"
345 logging.info('Verified the content of /verity_key')
346
Tao Baoc9981932019-09-16 12:10:43 -0700347 # For devices with a separate ramdisk (i.e. non-system-as-root), there must
348 # be a copy in ramdisk.
349 if info_dict.get("system_root_image") != "true":
350 verity_key_ramdisk = os.path.join(
351 input_tmp, 'BOOT', 'RAMDISK', 'verity_key')
Kelvin Zhang4093d602021-05-25 09:17:38 -0400352 assert os.path.exists(
353 verity_key_ramdisk), 'Missing verity_key in ramdisk'
Tao Baoc9981932019-09-16 12:10:43 -0700354
355 assert filecmp.cmp(
356 verity_key_mincrypt, verity_key_ramdisk, shallow=False), \
Kelvin Zhang4093d602021-05-25 09:17:38 -0400357 'Mismatching verity_key files in root and ramdisk'
Tao Baoc9981932019-09-16 12:10:43 -0700358 logging.info('Verified the content of /verity_key in ramdisk')
359
Tao Baoba557702018-03-10 20:41:16 -0800360 # Then verify the verity signed system/vendor/product images, against the
361 # verity pubkey in mincrypt format.
362 for image in ('system.img', 'vendor.img', 'product.img'):
363 image_path = os.path.join(input_tmp, 'IMAGES', image)
364
365 # We are not checking if the image is actually enabled via info_dict (e.g.
366 # 'system_verity_block_device=...'). Because it's most likely a bug that
367 # skips signing some of the images in signed target-files.zip, while
368 # having the top-level verity flag enabled.
369 if not os.path.exists(image_path):
370 continue
371
372 cmd = ['verity_verifier', image_path, '-mincrypt', verity_key_mincrypt]
Tao Bao73dd4f42018-10-04 16:25:33 -0700373 proc = common.Run(cmd)
Tao Baoba557702018-03-10 20:41:16 -0800374 stdoutdata, _ = proc.communicate()
375 assert proc.returncode == 0, \
376 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
377 image, verity_key_mincrypt, stdoutdata)
378 logging.info(
379 'Verified %s with verity_verifier (key: %s):\n%s', image,
380 verity_key_mincrypt, stdoutdata.rstrip())
381
382 # Handle the case of Verified Boot 2.0 (AVB).
383 if info_dict.get("avb_enable") == "true":
384 logging.info('Verifying Verified Boot 2.0 (AVB) images...')
385
Tao Baoa81d4292019-03-26 12:13:04 -0700386 key = options['verity_key']
387 if key is None:
388 key = info_dict['avb_vbmeta_key_path']
389
Kelvin Zhang4093d602021-05-25 09:17:38 -0400390 ValidatePartitionFingerprints(input_tmp, info_dict)
391
Tao Baoa81d4292019-03-26 12:13:04 -0700392 # avbtool verifies all the images that have descriptors listed in vbmeta.
cfig1aeef722019-09-20 22:45:06 +0800393 # Using `--follow_chain_partitions` so it would additionally verify chained
394 # vbmeta partitions (e.g. vbmeta_system).
Tao Baoa81d4292019-03-26 12:13:04 -0700395 image = os.path.join(input_tmp, 'IMAGES', 'vbmeta.img')
Tao Bao1ac886e2019-06-26 11:58:22 -0700396 cmd = [info_dict['avb_avbtool'], 'verify_image', '--image', image,
Tianjie Xu9bd832a2020-02-06 13:12:56 -0800397 '--follow_chain_partitions']
Tao Baoa81d4292019-03-26 12:13:04 -0700398
Hongguang Chenf23364d2020-04-27 18:36:36 -0700399 # Custom images.
400 custom_partitions = info_dict.get(
401 "avb_custom_images_partition_list", "").strip().split()
402
Tao Baoa81d4292019-03-26 12:13:04 -0700403 # Append the args for chained partitions if any.
Hongguang Chenf23364d2020-04-27 18:36:36 -0700404 for partition in (common.AVB_PARTITIONS + common.AVB_VBMETA_PARTITIONS +
405 tuple(custom_partitions)):
Tao Baoa81d4292019-03-26 12:13:04 -0700406 key_name = 'avb_' + partition + '_key_path'
407 if info_dict.get(key_name) is not None:
cfig1aeef722019-09-20 22:45:06 +0800408 if info_dict.get('ab_update') != 'true' and partition == 'recovery':
409 continue
410
Tao Bao08c190f2019-06-03 23:07:58 -0700411 # Use the key file from command line if specified; otherwise fall back
412 # to the one in info dict.
413 key_file = options.get(key_name, info_dict[key_name])
Tao Baoa81d4292019-03-26 12:13:04 -0700414 chained_partition_arg = common.GetAvbChainedPartitionArg(
Tao Bao08c190f2019-06-03 23:07:58 -0700415 partition, info_dict, key_file)
cfig1aeef722019-09-20 22:45:06 +0800416 cmd.extend(['--expected_chain_partition', chained_partition_arg])
Tao Baoa81d4292019-03-26 12:13:04 -0700417
Tianjie5ec1a7a2020-06-25 22:59:54 -0700418 # Handle the boot image with a non-default name, e.g. boot-5.4.img
419 boot_images = info_dict.get("boot_images")
420 if boot_images:
421 # we used the 1st boot image to generate the vbmeta. Rename the filename
422 # to boot.img so that avbtool can find it correctly.
423 first_image_name = boot_images.split()[0]
424 first_image_path = os.path.join(input_tmp, 'IMAGES', first_image_name)
425 assert os.path.isfile(first_image_path)
426 renamed_boot_image_path = os.path.join(input_tmp, 'IMAGES', 'boot.img')
427 os.rename(first_image_path, renamed_boot_image_path)
428
Tao Baoa81d4292019-03-26 12:13:04 -0700429 proc = common.Run(cmd)
430 stdoutdata, _ = proc.communicate()
431 assert proc.returncode == 0, \
432 'Failed to verify {} with avbtool (key: {}):\n{}'.format(
433 image, key, stdoutdata)
434
435 logging.info(
436 'Verified %s with avbtool (key: %s):\n%s', image, key,
437 stdoutdata.rstrip())
Tao Baoba557702018-03-10 20:41:16 -0800438
cfig1aeef722019-09-20 22:45:06 +0800439 # avbtool verifies recovery image for non-A/B devices.
440 if (info_dict.get('ab_update') != 'true' and
Kelvin Zhang4093d602021-05-25 09:17:38 -0400441 info_dict.get('no_recovery') != 'true'):
cfig1aeef722019-09-20 22:45:06 +0800442 image = os.path.join(input_tmp, 'IMAGES', 'recovery.img')
443 key = info_dict['avb_recovery_key_path']
444 cmd = [info_dict['avb_avbtool'], 'verify_image', '--image', image,
445 '--key', key]
446 proc = common.Run(cmd)
447 stdoutdata, _ = proc.communicate()
448 assert proc.returncode == 0, \
449 'Failed to verify {} with avbtool (key: {}):\n{}'.format(
450 image, key, stdoutdata)
451 logging.info(
452 'Verified %s with avbtool (key: %s):\n%s', image, key,
453 stdoutdata.rstrip())
454
Tianjie2e0b8352021-01-12 14:04:58 -0800455
456def CheckDataInconsistency(lines):
Kelvin Zhang4093d602021-05-25 09:17:38 -0400457 build_prop = {}
458 for line in lines:
459 if line.startswith("import") or line.startswith("#"):
460 continue
461 if "=" not in line:
462 continue
Tianjie2e0b8352021-01-12 14:04:58 -0800463
Kelvin Zhang4093d602021-05-25 09:17:38 -0400464 key, value = line.rstrip().split("=", 1)
465 if key in build_prop:
466 logging.info("Duplicated key found for {}".format(key))
467 if value != build_prop[key]:
468 logging.error("Key {} is defined twice with different values {} vs {}"
469 .format(key, value, build_prop[key]))
470 return key
471 build_prop[key] = value
Kelvin Zhangf2e846f2020-06-29 16:04:51 -0400472
Tianjie2e0b8352021-01-12 14:04:58 -0800473
Kelvin Zhangf2e846f2020-06-29 16:04:51 -0400474def CheckBuildPropDuplicity(input_tmp):
475 """Check all buld.prop files inside directory input_tmp, raise error
476 if they contain duplicates"""
477
478 if not os.path.isdir(input_tmp):
479 raise ValueError("Expect {} to be a directory".format(input_tmp))
480 for name in os.listdir(input_tmp):
481 if not name.isupper():
482 continue
483 for prop_file in ['build.prop', 'etc/build.prop']:
484 path = os.path.join(input_tmp, name, prop_file)
485 if not os.path.exists(path):
486 continue
487 logging.info("Checking {}".format(path))
488 with open(path, 'r') as fp:
Tianjie2e0b8352021-01-12 14:04:58 -0800489 dupKey = CheckDataInconsistency(fp.readlines())
Kelvin Zhangf2e846f2020-06-29 16:04:51 -0400490 if dupKey:
Tianjie2e0b8352021-01-12 14:04:58 -0800491 raise ValueError("{} contains duplicate keys for {}".format(
492 path, dupKey))
493
Tao Baoba557702018-03-10 20:41:16 -0800494
495def main():
496 parser = argparse.ArgumentParser(
497 description=__doc__,
498 formatter_class=argparse.RawDescriptionHelpFormatter)
499 parser.add_argument(
500 'target_files',
501 help='the input target_files.zip to be validated')
502 parser.add_argument(
503 '--verity_key',
504 help='the verity public key to verify the bootable images (Verified '
Tao Bao02a08592018-07-22 12:40:45 -0700505 'Boot 1.0), or the vbmeta image (Verified Boot 2.0, aka AVB), where '
Tao Baoba557702018-03-10 20:41:16 -0800506 'applicable')
Tao Bao08c190f2019-06-03 23:07:58 -0700507 for partition in common.AVB_PARTITIONS + common.AVB_VBMETA_PARTITIONS:
Tao Bao02a08592018-07-22 12:40:45 -0700508 parser.add_argument(
509 '--avb_' + partition + '_key_path',
510 help='the public or private key in PEM format to verify AVB chained '
511 'partition of {}'.format(partition))
Tao Baoba557702018-03-10 20:41:16 -0800512 parser.add_argument(
513 '--verity_key_mincrypt',
514 help='the verity public key in mincrypt format to verify the system '
515 'images, if target using Verified Boot 1.0')
516 args = parser.parse_args()
517
518 # Unprovided args will have 'None' as the value.
519 options = vars(args)
Tao Baoafaa0a62017-02-27 15:08:36 -0800520
521 logging_format = '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s'
522 date_format = '%Y/%m/%d %H:%M:%S'
523 logging.basicConfig(level=logging.INFO, format=logging_format,
524 datefmt=date_format)
525
Tao Baoba557702018-03-10 20:41:16 -0800526 logging.info("Unzipping the input target_files.zip: %s", args.target_files)
527 input_tmp = common.UnzipTemp(args.target_files)
Tao Baoafaa0a62017-02-27 15:08:36 -0800528
Tianjie Xu9c384d22017-06-20 17:00:55 -0700529 info_dict = common.LoadInfoDict(input_tmp)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400530 with zipfile.ZipFile(args.target_files, 'r', allowZip64=True) as input_zip:
Tao Bao63e2f492018-05-11 23:38:46 -0700531 ValidateFileConsistency(input_zip, input_tmp, info_dict)
532
Kelvin Zhangf2e846f2020-06-29 16:04:51 -0400533 CheckBuildPropDuplicity(input_tmp)
534
Tianjie Xu9c384d22017-06-20 17:00:55 -0700535 ValidateInstallRecoveryScript(input_tmp, info_dict)
536
Tao Baoba557702018-03-10 20:41:16 -0800537 ValidateVerifiedBootImages(input_tmp, info_dict, options)
538
Tao Baoafaa0a62017-02-27 15:08:36 -0800539 # TODO: Check if the OTA keys have been properly updated (the ones on /system,
540 # in recovery image).
541
Tao Baoafaa0a62017-02-27 15:08:36 -0800542 logging.info("Done.")
543
544
545if __name__ == '__main__':
546 try:
Tao Baoba557702018-03-10 20:41:16 -0800547 main()
Tao Baoafaa0a62017-02-27 15:08:36 -0800548 finally:
549 common.Cleanup()