blob: e8cea298aecc6742ed89e019b5d50210014d2208 [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
69def ValidateFileConsistency(input_zip, input_tmp):
70 """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
106 # Verify IMAGES/system.img.
107 CheckAllFiles('system')
108
109 # Verify IMAGES/vendor.img if applicable.
110 if 'VENDOR/' in input_zip.namelist():
111 CheckAllFiles('vendor')
112
113 # Not checking IMAGES/system_other.img since it doesn't have the map file.
114
115
Tianjie Xu9c384d22017-06-20 17:00:55 -0700116def ValidateInstallRecoveryScript(input_tmp, info_dict):
117 """Validate the SHA-1 embedded in install-recovery.sh.
118
119 install-recovery.sh is written in common.py and has the following format:
120
121 1. full recovery:
122 ...
123 if ! applypatch -c type:device:size:SHA-1; then
124 applypatch /system/etc/recovery.img type:device sha1 size && ...
125 ...
126
127 2. recovery from boot:
128 ...
129 applypatch [-b bonus_args] boot_info recovery_info recovery_sha1 \
130 recovery_size patch_info && ...
131 ...
132
133 For full recovery, we want to calculate the SHA-1 of /system/etc/recovery.img
134 and compare it against the one embedded in the script. While for recovery
135 from boot, we want to check the SHA-1 for both recovery.img and boot.img
136 under IMAGES/.
137 """
138
139 script_path = 'SYSTEM/bin/install-recovery.sh'
140 if not os.path.exists(os.path.join(input_tmp, script_path)):
Tao Baobb20e8c2018-02-01 12:00:19 -0800141 logging.info('%s does not exist in input_tmp', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700142 return
143
Tao Baobb20e8c2018-02-01 12:00:19 -0800144 logging.info('Checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700145 with open(os.path.join(input_tmp, script_path), 'r') as script:
146 lines = script.read().strip().split('\n')
147 assert len(lines) >= 6
148 check_cmd = re.search(r'if ! applypatch -c \w+:.+:\w+:(\w+);',
149 lines[1].strip())
150 expected_recovery_check_sha1 = check_cmd.group(1)
151 patch_cmd = re.search(r'(applypatch.+)&&', lines[2].strip())
152 applypatch_argv = patch_cmd.group(1).strip().split()
153
154 full_recovery_image = info_dict.get("full_recovery_image") == "true"
155 if full_recovery_image:
156 assert len(applypatch_argv) == 5
157 # Check we have the same expected SHA-1 of recovery.img in both check mode
158 # and patch mode.
159 expected_recovery_sha1 = applypatch_argv[3].strip()
160 assert expected_recovery_check_sha1 == expected_recovery_sha1
161 ValidateFileAgainstSha1(input_tmp, 'recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800162 'SYSTEM/etc/recovery.img', expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700163 else:
164 # We're patching boot.img to get recovery.img where bonus_args is optional
165 if applypatch_argv[1] == "-b":
166 assert len(applypatch_argv) == 8
167 boot_info_index = 3
168 else:
169 assert len(applypatch_argv) == 6
170 boot_info_index = 1
171
172 # boot_info: boot_type:boot_device:boot_size:boot_sha1
173 boot_info = applypatch_argv[boot_info_index].strip().split(':')
174 assert len(boot_info) == 4
175 ValidateFileAgainstSha1(input_tmp, file_name='boot.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800176 file_path='IMAGES/boot.img',
177 expected_sha1=boot_info[3])
Tianjie Xu9c384d22017-06-20 17:00:55 -0700178
179 recovery_sha1_index = boot_info_index + 2
180 expected_recovery_sha1 = applypatch_argv[recovery_sha1_index]
181 assert expected_recovery_check_sha1 == expected_recovery_sha1
182 ValidateFileAgainstSha1(input_tmp, file_name='recovery.img',
Tao Baobb20e8c2018-02-01 12:00:19 -0800183 file_path='IMAGES/recovery.img',
184 expected_sha1=expected_recovery_sha1)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700185
Tao Baobb20e8c2018-02-01 12:00:19 -0800186 logging.info('Done checking %s', script_path)
Tianjie Xu9c384d22017-06-20 17:00:55 -0700187
188
Tao Baoba557702018-03-10 20:41:16 -0800189def ValidateVerifiedBootImages(input_tmp, info_dict, options):
190 """Validates the Verified Boot related images.
Tao Baoafaa0a62017-02-27 15:08:36 -0800191
Tao Baoba557702018-03-10 20:41:16 -0800192 For Verified Boot 1.0, it verifies the signatures of the bootable images
193 (boot/recovery etc), as well as the dm-verity metadata in system images
194 (system/vendor/product). For Verified Boot 2.0, it calls avbtool to verify
195 vbmeta.img, which in turn verifies all the descriptors listed in vbmeta.
Tao Baoafaa0a62017-02-27 15:08:36 -0800196
Tao Baoba557702018-03-10 20:41:16 -0800197 Args:
198 input_tmp: The top-level directory of unpacked target-files.zip.
199 info_dict: The loaded info dict.
200 options: A dict that contains the user-supplied public keys to be used for
201 image verification. In particular, 'verity_key' is used to verify the
202 bootable images in VB 1.0, and the vbmeta image in VB 2.0, where
203 applicable. 'verity_key_mincrypt' will be used to verify the system
204 images in VB 1.0.
205
206 Raises:
207 AssertionError: On any verification failure.
208 """
209 # Verified boot 1.0 (images signed with boot_signer and verity_signer).
210 if info_dict.get('boot_signer') == 'true':
211 logging.info('Verifying Verified Boot images...')
212
213 # Verify the boot/recovery images (signed with boot_signer), against the
214 # given X.509 encoded pubkey (or falling back to the one in the info_dict if
215 # none given).
216 verity_key = options['verity_key']
217 if verity_key is None:
218 verity_key = info_dict['verity_key'] + '.x509.pem'
219 for image in ('boot.img', 'recovery.img', 'recovery-two-step.img'):
220 image_path = os.path.join(input_tmp, 'IMAGES', image)
221 if not os.path.exists(image_path):
222 continue
223
224 cmd = ['boot_signer', '-verify', image_path, '-certificate', verity_key]
225 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
226 stdoutdata, _ = proc.communicate()
227 assert proc.returncode == 0, \
228 'Failed to verify {} with boot_signer:\n{}'.format(image, stdoutdata)
229 logging.info(
230 'Verified %s with boot_signer (key: %s):\n%s', image, verity_key,
231 stdoutdata.rstrip())
232
233 # Verify verity signed system images in Verified Boot 1.0. Note that not using
234 # 'elif' here, since 'boot_signer' and 'verity' are not bundled in VB 1.0.
235 if info_dict.get('verity') == 'true':
236 # First verify that the verity key that's built into the root image (as
237 # /verity_key) matches the one given via command line, if any.
238 if info_dict.get("system_root_image") == "true":
239 verity_key_mincrypt = os.path.join(input_tmp, 'ROOT', 'verity_key')
240 else:
241 verity_key_mincrypt = os.path.join(
242 input_tmp, 'BOOT', 'RAMDISK', 'verity_key')
243 assert os.path.exists(verity_key_mincrypt), 'Missing verity_key'
244
245 if options['verity_key_mincrypt'] is None:
246 logging.warn(
247 'Skipped checking the content of /verity_key, as the key file not '
248 'provided. Use --verity_key_mincrypt to specify.')
249 else:
250 expected_key = options['verity_key_mincrypt']
251 assert filecmp.cmp(expected_key, verity_key_mincrypt, shallow=False), \
252 "Mismatching mincrypt verity key files"
253 logging.info('Verified the content of /verity_key')
254
255 # Then verify the verity signed system/vendor/product images, against the
256 # verity pubkey in mincrypt format.
257 for image in ('system.img', 'vendor.img', 'product.img'):
258 image_path = os.path.join(input_tmp, 'IMAGES', image)
259
260 # We are not checking if the image is actually enabled via info_dict (e.g.
261 # 'system_verity_block_device=...'). Because it's most likely a bug that
262 # skips signing some of the images in signed target-files.zip, while
263 # having the top-level verity flag enabled.
264 if not os.path.exists(image_path):
265 continue
266
267 cmd = ['verity_verifier', image_path, '-mincrypt', verity_key_mincrypt]
268 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
269 stdoutdata, _ = proc.communicate()
270 assert proc.returncode == 0, \
271 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
272 image, verity_key_mincrypt, stdoutdata)
273 logging.info(
274 'Verified %s with verity_verifier (key: %s):\n%s', image,
275 verity_key_mincrypt, stdoutdata.rstrip())
276
277 # Handle the case of Verified Boot 2.0 (AVB).
278 if info_dict.get("avb_enable") == "true":
279 logging.info('Verifying Verified Boot 2.0 (AVB) images...')
280
281 key = options['verity_key']
282 if key is None:
283 key = info_dict['avb_vbmeta_key_path']
284 # avbtool verifies all the images that have descriptors listed in vbmeta.
285 image = os.path.join(input_tmp, 'IMAGES', 'vbmeta.img')
286 cmd = ['avbtool', 'verify_image', '--image', image, '--key', key]
287 proc = common.Run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
288 stdoutdata, _ = proc.communicate()
289 assert proc.returncode == 0, \
290 'Failed to verify {} with verity_verifier (key: {}):\n{}'.format(
291 image, key, stdoutdata)
292
293 logging.info(
294 'Verified %s with avbtool (key: %s):\n%s', image, key,
295 stdoutdata.rstrip())
296
297
298def main():
299 parser = argparse.ArgumentParser(
300 description=__doc__,
301 formatter_class=argparse.RawDescriptionHelpFormatter)
302 parser.add_argument(
303 'target_files',
304 help='the input target_files.zip to be validated')
305 parser.add_argument(
306 '--verity_key',
307 help='the verity public key to verify the bootable images (Verified '
308 'Boot 1.0), or the vbmeta image (Verified Boot 2.0), where '
309 'applicable')
310 parser.add_argument(
311 '--verity_key_mincrypt',
312 help='the verity public key in mincrypt format to verify the system '
313 'images, if target using Verified Boot 1.0')
314 args = parser.parse_args()
315
316 # Unprovided args will have 'None' as the value.
317 options = vars(args)
Tao Baoafaa0a62017-02-27 15:08:36 -0800318
319 logging_format = '%(asctime)s - %(filename)s - %(levelname)-8s: %(message)s'
320 date_format = '%Y/%m/%d %H:%M:%S'
321 logging.basicConfig(level=logging.INFO, format=logging_format,
322 datefmt=date_format)
323
Tao Baoba557702018-03-10 20:41:16 -0800324 logging.info("Unzipping the input target_files.zip: %s", args.target_files)
325 input_tmp = common.UnzipTemp(args.target_files)
Tao Baoafaa0a62017-02-27 15:08:36 -0800326
Tao Baoba557702018-03-10 20:41:16 -0800327 with zipfile.ZipFile(args.target_files, 'r') as input_zip:
Tao Baodba59ee2018-01-09 13:21:02 -0800328 ValidateFileConsistency(input_zip, input_tmp)
Tao Baoafaa0a62017-02-27 15:08:36 -0800329
Tianjie Xu9c384d22017-06-20 17:00:55 -0700330 info_dict = common.LoadInfoDict(input_tmp)
331 ValidateInstallRecoveryScript(input_tmp, info_dict)
332
Tao Baoba557702018-03-10 20:41:16 -0800333 ValidateVerifiedBootImages(input_tmp, info_dict, options)
334
Tao Baoafaa0a62017-02-27 15:08:36 -0800335 # TODO: Check if the OTA keys have been properly updated (the ones on /system,
336 # in recovery image).
337
Tao Baoafaa0a62017-02-27 15:08:36 -0800338 logging.info("Done.")
339
340
341if __name__ == '__main__':
342 try:
Tao Baoba557702018-03-10 20:41:16 -0800343 main()
Tao Baoafaa0a62017-02-27 15:08:36 -0800344 finally:
345 common.Cleanup()