Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # |
| 3 | # Copyright (C) 2021 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 | """sign_virt_apex is a command line tool for sign the Virt APEX file. |
| 17 | |
Jooyung Han | 98498f4 | 2022-02-07 15:23:08 +0900 | [diff] [blame] | 18 | Typical usage: |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 19 | sign_virt_apex payload_key payload_dir |
| 20 | -v, --verbose |
| 21 | --verify |
| 22 | --avbtool path_to_avbtool |
| 23 | --signing_args args |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 24 | |
| 25 | sign_virt_apex uses external tools which are assumed to be available via PATH. |
| 26 | - avbtool (--avbtool can override the tool) |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 27 | - lpmake, lpunpack, simg2img, img2simg, initrd_bootconfig |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 28 | """ |
| 29 | import argparse |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 30 | import binascii |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 31 | import builtins |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 32 | import hashlib |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 33 | import os |
| 34 | import re |
Jooyung Han | 98498f4 | 2022-02-07 15:23:08 +0900 | [diff] [blame] | 35 | import shlex |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 36 | import subprocess |
| 37 | import sys |
| 38 | import tempfile |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 39 | import traceback |
| 40 | from concurrent import futures |
| 41 | |
| 42 | # pylint: disable=line-too-long,consider-using-with |
| 43 | |
| 44 | # Use executor to parallelize the invocation of external tools |
| 45 | # If a task depends on another, pass the future object of the previous task as wait list. |
| 46 | # Every future object created by a task should be consumed with AwaitAll() |
| 47 | # so that exceptions are propagated . |
| 48 | executor = futures.ThreadPoolExecutor() |
| 49 | |
| 50 | # Temporary directory for unpacked super.img. |
| 51 | # We could put its creation/deletion into the task graph as well, but |
| 52 | # having it as a global setup is much simpler. |
| 53 | unpack_dir = tempfile.TemporaryDirectory() |
| 54 | |
| 55 | # tasks created with Async() are kept in a list so that they are awaited |
| 56 | # before exit. |
| 57 | tasks = [] |
| 58 | |
| 59 | # create an async task and return a future value of it. |
| 60 | def Async(fn, *args, wait=None, **kwargs): |
| 61 | |
| 62 | # wrap a function with AwaitAll() |
| 63 | def wrapped(): |
| 64 | AwaitAll(wait) |
| 65 | fn(*args, **kwargs) |
| 66 | |
| 67 | task = executor.submit(wrapped) |
| 68 | tasks.append(task) |
| 69 | return task |
| 70 | |
| 71 | |
| 72 | # waits for task (captured in fs as future values) with future.result() |
| 73 | # so that any exception raised during task can be raised upward. |
| 74 | def AwaitAll(fs): |
| 75 | if fs: |
| 76 | for f in fs: |
| 77 | f.result() |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 78 | |
| 79 | |
| 80 | def ParseArgs(argv): |
| 81 | parser = argparse.ArgumentParser(description='Sign the Virt APEX') |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 82 | parser.add_argument('--verify', action='store_true', |
| 83 | help='Verify the Virt APEX') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 84 | parser.add_argument( |
| 85 | '-v', '--verbose', |
| 86 | action='store_true', |
| 87 | help='verbose execution') |
| 88 | parser.add_argument( |
| 89 | '--avbtool', |
| 90 | default='avbtool', |
| 91 | help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.') |
| 92 | parser.add_argument( |
Jooyung Han | 98498f4 | 2022-02-07 15:23:08 +0900 | [diff] [blame] | 93 | '--signing_args', |
| 94 | help='the extra signing arguments passed to avbtool.' |
| 95 | ) |
| 96 | parser.add_argument( |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 97 | '--key_override', |
| 98 | metavar="filename=key", |
| 99 | action='append', |
| 100 | help='Overrides a signing key for a file e.g. microdroid_bootloader=mykey (for testing)') |
| 101 | parser.add_argument( |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 102 | 'key', |
| 103 | help='path to the private key file.') |
| 104 | parser.add_argument( |
| 105 | 'input_dir', |
| 106 | help='the directory having files to be packaged') |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 107 | parser.add_argument( |
| 108 | '--do_not_update_bootconfigs', |
| 109 | action='store_true', |
| 110 | help='This will NOT update the vbmeta related bootconfigs while signing the apex.\ |
| 111 | Used for testing only!!') |
Nikita Ioffe | 314d7e3 | 2023-12-18 17:38:18 +0000 | [diff] [blame] | 112 | parser.add_argument('--do_not_validate_avb_version', action='store_true', help='Do not validate the avb_version when updating vbmeta bootconfig. Only use in tests!') |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 113 | args = parser.parse_args(argv) |
| 114 | # preprocess --key_override into a map |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 115 | args.key_overrides = {} |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 116 | if args.key_override: |
| 117 | for pair in args.key_override: |
| 118 | name, key = pair.split('=') |
| 119 | args.key_overrides[name] = key |
| 120 | return args |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 121 | |
| 122 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 123 | def RunCommand(args, cmd, env=None, expected_return_values=None): |
| 124 | expected_return_values = expected_return_values or {0} |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 125 | env = env or {} |
| 126 | env.update(os.environ.copy()) |
| 127 | |
| 128 | # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts |
| 129 | # e.g. sign_apex.py, sign_target_files_apk.py |
| 130 | if cmd[0] == 'avbtool': |
| 131 | cmd[0] = args.avbtool |
| 132 | |
| 133 | if args.verbose: |
| 134 | print('Running: ' + ' '.join(cmd)) |
| 135 | p = subprocess.Popen( |
| 136 | cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True) |
| 137 | output, _ = p.communicate() |
| 138 | |
| 139 | if args.verbose or p.returncode not in expected_return_values: |
| 140 | print(output.rstrip()) |
| 141 | |
| 142 | assert p.returncode in expected_return_values, ( |
| 143 | '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode |
| 144 | return (output, p.returncode) |
| 145 | |
| 146 | |
| 147 | def ReadBytesSize(value): |
| 148 | return int(value.removesuffix(' bytes')) |
| 149 | |
| 150 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 151 | def ExtractAvbPubkey(args, key, output): |
| 152 | RunCommand(args, ['avbtool', 'extract_public_key', |
| 153 | '--key', key, '--output', output]) |
| 154 | |
| 155 | |
| 156 | def AvbInfo(args, image_path): |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 157 | """Parses avbtool --info image output |
| 158 | |
| 159 | Args: |
| 160 | args: program arguments. |
| 161 | image_path: The path to the image. |
| 162 | descriptor_name: Descriptor name of interest. |
| 163 | |
| 164 | Returns: |
| 165 | A pair of |
| 166 | - a dict that contains VBMeta info. None if there's no VBMeta info. |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 167 | - a list of descriptors. |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 168 | """ |
| 169 | if not os.path.exists(image_path): |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 170 | raise ValueError(f'Failed to find image: {image_path}') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 171 | |
| 172 | output, ret_code = RunCommand( |
| 173 | args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1}) |
| 174 | if ret_code == 1: |
| 175 | return None, None |
| 176 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 177 | info, descriptors = {}, [] |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 178 | |
| 179 | # Read `avbtool info_image` output as "key:value" lines |
| 180 | matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$') |
| 181 | |
| 182 | def IterateLine(output): |
| 183 | for line in output.split('\n'): |
| 184 | line_info = matcher.match(line) |
| 185 | if not line_info: |
| 186 | continue |
| 187 | yield line_info.group(1), line_info.group(2), line_info.group(3) |
| 188 | |
| 189 | gen = IterateLine(output) |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 190 | |
| 191 | def ReadDescriptors(cur_indent, cur_name, cur_value): |
| 192 | descriptor = cur_value if cur_name == 'Prop' else {} |
| 193 | descriptors.append((cur_name, descriptor)) |
| 194 | for indent, key, value in gen: |
| 195 | if indent <= cur_indent: |
| 196 | # read descriptors recursively to pass the read key as descriptor name |
| 197 | ReadDescriptors(indent, key, value) |
| 198 | break |
| 199 | descriptor[key] = value |
| 200 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 201 | # Read VBMeta info |
| 202 | for _, key, value in gen: |
| 203 | if key == 'Descriptors': |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 204 | ReadDescriptors(*next(gen)) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 205 | break |
| 206 | info[key] = value |
| 207 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 208 | return info, descriptors |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 209 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 210 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 211 | def find_all_values_by_key(pairs, key): |
| 212 | """Find all the values of the key in the pairs.""" |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 213 | return [v for (k, v) in pairs if k == key] |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 214 | |
Seungjae Yoo | b18d163 | 2024-01-10 11:08:19 +0900 | [diff] [blame] | 215 | # Extract properties from the descriptors of original vbmeta image, |
| 216 | # append to command as parameter. |
| 217 | def AppendPropArgument(cmd, descriptors): |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 218 | for prop in find_all_values_by_key(descriptors, 'Prop'): |
Seungjae Yoo | b18d163 | 2024-01-10 11:08:19 +0900 | [diff] [blame] | 219 | cmd.append('--prop') |
| 220 | result = re.match(r"(.+) -> '(.+)'", prop) |
| 221 | cmd.append(result.group(1) + ":" + result.group(2)) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 222 | |
Seungjae Yoo | 3f46c7f | 2024-01-10 14:32:54 +0900 | [diff] [blame] | 223 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 224 | def check_resigned_image_avb_info(image_path, original_info, original_descriptors, args): |
| 225 | updated_info, updated_descriptors = AvbInfo(args, image_path) |
| 226 | assert original_info is not None, f'no avbinfo on original image: {image_path}' |
| 227 | assert updated_info is not None, f'no avbinfo on resigned image: {image_path}' |
| 228 | assert_different_value(original_info, updated_info, "Public key (sha1)", image_path) |
| 229 | updated_public_key = updated_info.pop("Public key (sha1)") |
| 230 | if not hasattr(check_resigned_image_avb_info, "new_public_key"): |
| 231 | check_resigned_image_avb_info.new_public_key = updated_public_key |
| 232 | else: |
| 233 | assert check_resigned_image_avb_info.new_public_key == updated_public_key, \ |
| 234 | "All images should be resigned with the same public key. Expected public key (sha1):" \ |
| 235 | f" {check_resigned_image_avb_info.new_public_key}, actual public key (sha1): " \ |
| 236 | f"{updated_public_key}, Path: {image_path}" |
| 237 | original_info.pop("Public key (sha1)") |
| 238 | assert original_info == updated_info, \ |
| 239 | f"Original info and updated info should be the same for {image_path}. " \ |
| 240 | f"Original info: {original_info}, updated info: {updated_info}" |
Seungjae Yoo | 3f46c7f | 2024-01-10 14:32:54 +0900 | [diff] [blame] | 241 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 242 | # Verify the descriptors of the original and updated images. |
| 243 | assert len(original_descriptors) == len(updated_descriptors), \ |
| 244 | f"Number of descriptors should be the same for {image_path}. " \ |
| 245 | f"Original descriptors: {original_descriptors}, updated descriptors: {updated_descriptors}" |
| 246 | original_prop_descriptors = sorted(find_all_values_by_key(original_descriptors, "Prop")) |
| 247 | updated_prop_descriptors = sorted(find_all_values_by_key(updated_descriptors, "Prop")) |
| 248 | assert original_prop_descriptors == updated_prop_descriptors, \ |
| 249 | f"Prop descriptors should be the same for {image_path}. " \ |
| 250 | f"Original prop descriptors: {original_prop_descriptors}, " \ |
| 251 | f"updated prop descriptors: {updated_prop_descriptors}" |
| 252 | |
| 253 | # Remove digest from hash descriptors before comparing, since some digests should change. |
| 254 | original_hash_descriptors = extract_hash_descriptors(original_descriptors, drop_digest) |
| 255 | updated_hash_descriptors = extract_hash_descriptors(updated_descriptors, drop_digest) |
| 256 | assert original_hash_descriptors == updated_hash_descriptors, \ |
| 257 | f"Hash descriptors' parameters should be the same for {image_path}. " \ |
| 258 | f"Original hash descriptors: {original_hash_descriptors}, " \ |
| 259 | f"updated hash descriptors: {updated_hash_descriptors}" |
| 260 | |
| 261 | def drop_digest(descriptor): |
| 262 | return {k: v for k, v in descriptor.items() if k != "Digest"} |
| 263 | |
| 264 | def AddHashFooter(args, key, image_path, additional_images=()): |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 265 | if os.path.basename(image_path) in args.key_overrides: |
| 266 | key = args.key_overrides[os.path.basename(image_path)] |
Seungjae Yoo | b18d163 | 2024-01-10 11:08:19 +0900 | [diff] [blame] | 267 | info, descriptors = AvbInfo(args, image_path) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 268 | assert info is not None, f'no avbinfo: {image_path}' |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 269 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 270 | # Extract hash descriptor of original image. |
| 271 | hash_descriptors_original = extract_hash_descriptors(descriptors, drop_digest) |
| 272 | for additional_image in additional_images: |
| 273 | _, additional_desc = AvbInfo(args, additional_image) |
| 274 | hash_descriptors = extract_hash_descriptors(additional_desc, drop_digest) |
| 275 | for k, v in hash_descriptors.items(): |
| 276 | assert v == hash_descriptors_original[k], \ |
| 277 | f"Hash descriptor of {k} in {additional_image} and {image_path} should be " \ |
| 278 | f"the same. {additional_image}: {v}, {image_path}: {hash_descriptors_original[k]}" |
| 279 | del hash_descriptors_original[k] |
| 280 | assert len(hash_descriptors_original) == 1, \ |
| 281 | f"Only one hash descriptor is expected for {image_path} after removing " \ |
| 282 | f"additional images. Hash descriptors: {hash_descriptors_original}" |
| 283 | [(original_image_partition_name, original_image_descriptor)] = hash_descriptors_original.items() |
| 284 | assert info["Original image size"] == original_image_descriptor["Image Size"], \ |
| 285 | f"Original image size should be the same as the image size in the hash descriptor " \ |
| 286 | f"for {image_path}. Original image size: {info['Original image size']}, " \ |
| 287 | f"image size in the hash descriptor: {original_image_descriptor['Image Size']}" |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 288 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 289 | partition_size = str(ReadBytesSize(info['Image size'])) |
| 290 | algorithm = info['Algorithm'] |
| 291 | original_image_salt = original_image_descriptor['Salt'] |
Shikha Panwar | 2a78866 | 2023-09-11 14:04:24 +0000 | [diff] [blame] | 292 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 293 | cmd = ['avbtool', 'add_hash_footer', |
| 294 | '--key', key, |
| 295 | '--algorithm', algorithm, |
| 296 | '--partition_name', original_image_partition_name, |
| 297 | '--salt', original_image_salt, |
| 298 | '--partition_size', partition_size, |
| 299 | '--image', image_path] |
| 300 | AppendPropArgument(cmd, descriptors) |
| 301 | if args.signing_args: |
| 302 | cmd.extend(shlex.split(args.signing_args)) |
| 303 | for additional_image in additional_images: |
| 304 | cmd.extend(['--include_descriptors_from_image', additional_image]) |
| 305 | cmd.extend(['--rollback_index', info['Rollback Index']]) |
| 306 | |
| 307 | RunCommand(args, cmd) |
| 308 | check_resigned_image_avb_info(image_path, info, descriptors, args) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 309 | |
| 310 | def AddHashTreeFooter(args, key, image_path): |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 311 | if os.path.basename(image_path) in args.key_overrides: |
| 312 | key = args.key_overrides[os.path.basename(image_path)] |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 313 | info, descriptors = AvbInfo(args, image_path) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 314 | if info: |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 315 | descriptor = find_all_values_by_key(descriptors, 'Hashtree descriptor')[0] |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 316 | image_size = ReadBytesSize(info['Image size']) |
| 317 | algorithm = info['Algorithm'] |
| 318 | partition_name = descriptor['Partition Name'] |
Shikha Panwar | 638119b | 2023-01-03 06:00:26 +0000 | [diff] [blame] | 319 | hash_algorithm = descriptor['Hash Algorithm'] |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 320 | salt = descriptor['Salt'] |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 321 | partition_size = str(image_size) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 322 | cmd = ['avbtool', 'add_hashtree_footer', |
| 323 | '--key', key, |
| 324 | '--algorithm', algorithm, |
| 325 | '--partition_name', partition_name, |
| 326 | '--partition_size', partition_size, |
| 327 | '--do_not_generate_fec', |
Shikha Panwar | 638119b | 2023-01-03 06:00:26 +0000 | [diff] [blame] | 328 | '--hash_algorithm', hash_algorithm, |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 329 | '--salt', salt, |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 330 | '--image', image_path] |
Seungjae Yoo | b18d163 | 2024-01-10 11:08:19 +0900 | [diff] [blame] | 331 | AppendPropArgument(cmd, descriptors) |
Jooyung Han | 98498f4 | 2022-02-07 15:23:08 +0900 | [diff] [blame] | 332 | if args.signing_args: |
| 333 | cmd.extend(shlex.split(args.signing_args)) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 334 | RunCommand(args, cmd) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 335 | check_resigned_image_avb_info(image_path, info, descriptors, args) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 336 | |
| 337 | |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 338 | def UpdateVbmetaBootconfig(args, initrds, vbmeta_img): |
| 339 | # Update the bootconfigs in ramdisk |
| 340 | def detach_bootconfigs(initrd_bc, initrd, bc): |
| 341 | cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc] |
| 342 | RunCommand(args, cmd) |
| 343 | |
| 344 | def attach_bootconfigs(initrd_bc, initrd, bc): |
| 345 | cmd = ['initrd_bootconfig', 'attach', |
| 346 | initrd, bc, '--output', initrd_bc] |
| 347 | RunCommand(args, cmd) |
| 348 | |
| 349 | # Validate that avb version used while signing the apex is the same as used by build server |
| 350 | def validate_avb_version(bootconfigs): |
| 351 | cmd = ['avbtool', 'version'] |
| 352 | stdout, _ = RunCommand(args, cmd) |
| 353 | avb_version_curr = stdout.split(" ")[1].strip() |
| 354 | avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')] |
| 355 | |
| 356 | avb_version_bc = re.search( |
| 357 | r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1) |
| 358 | if avb_version_curr != avb_version_bc: |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 359 | raise builtins.Exception(f'AVB version mismatch between current & one & \ |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 360 | used to build bootconfigs:{avb_version_curr}&{avb_version_bc}') |
| 361 | |
| 362 | def calc_vbmeta_digest(): |
| 363 | cmd = ['avbtool', 'calculate_vbmeta_digest', '--image', |
| 364 | vbmeta_img, '--hash_algorithm', 'sha256'] |
| 365 | stdout, _ = RunCommand(args, cmd) |
| 366 | return stdout.strip() |
| 367 | |
| 368 | def calc_vbmeta_size(): |
| 369 | cmd = ['avbtool', 'info_image', '--image', vbmeta_img] |
| 370 | stdout, _ = RunCommand(args, cmd) |
| 371 | size = 0 |
| 372 | for line in stdout.split("\n"): |
| 373 | line = line.split(":") |
| 374 | if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']: |
| 375 | size += int(line[1].strip()[0:-6]) |
| 376 | return size |
| 377 | |
| 378 | def update_vbmeta_digest(bootconfigs): |
| 379 | # Update androidboot.vbmeta.digest in bootconfigs |
| 380 | result = re.search( |
| 381 | r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs) |
| 382 | if not result: |
| 383 | raise ValueError("Failed to find androidboot.vbmeta.digest") |
| 384 | |
| 385 | return bootconfigs.replace(result.group(), |
| 386 | f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"') |
| 387 | |
| 388 | def update_vbmeta_size(bootconfigs): |
| 389 | # Update androidboot.vbmeta.size in bootconfigs |
| 390 | result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs) |
| 391 | if not result: |
| 392 | raise ValueError("Failed to find androidboot.vbmeta.size") |
| 393 | return bootconfigs.replace(result.group(), |
| 394 | f'androidboot.vbmeta.size = {calc_vbmeta_size()}') |
| 395 | |
| 396 | with tempfile.TemporaryDirectory() as work_dir: |
| 397 | tmp_initrd = os.path.join(work_dir, 'initrd') |
| 398 | tmp_bc = os.path.join(work_dir, 'bc') |
| 399 | |
| 400 | for initrd in initrds: |
| 401 | detach_bootconfigs(initrd, tmp_initrd, tmp_bc) |
| 402 | bc_file = open(tmp_bc, "rt", encoding="utf-8") |
| 403 | bc_data = bc_file.read() |
Nikita Ioffe | 314d7e3 | 2023-12-18 17:38:18 +0000 | [diff] [blame] | 404 | if not args.do_not_validate_avb_version: |
| 405 | validate_avb_version(bc_data) |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 406 | bc_data = update_vbmeta_digest(bc_data) |
| 407 | bc_data = update_vbmeta_size(bc_data) |
| 408 | bc_file.close() |
| 409 | bc_file = open(tmp_bc, "wt", encoding="utf-8") |
| 410 | bc_file.write(bc_data) |
| 411 | bc_file.flush() |
| 412 | attach_bootconfigs(initrd, tmp_initrd, tmp_bc) |
| 413 | |
| 414 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 415 | def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None): |
Jooyung Han | 1c3d2fa | 2022-02-24 02:35:59 +0900 | [diff] [blame] | 416 | if os.path.basename(vbmeta_img) in args.key_overrides: |
| 417 | key = args.key_overrides[os.path.basename(vbmeta_img)] |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 418 | info, descriptors = AvbInfo(args, vbmeta_img) |
| 419 | if info is None: |
| 420 | return |
| 421 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 422 | with tempfile.TemporaryDirectory() as work_dir: |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 423 | algorithm = info['Algorithm'] |
| 424 | rollback_index = info['Rollback Index'] |
| 425 | rollback_index_location = info['Rollback Index Location'] |
| 426 | |
| 427 | cmd = ['avbtool', 'make_vbmeta_image', |
| 428 | '--key', key, |
| 429 | '--algorithm', algorithm, |
| 430 | '--rollback_index', rollback_index, |
| 431 | '--rollback_index_location', rollback_index_location, |
| 432 | '--output', vbmeta_img] |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 433 | if images: |
| 434 | for img in images: |
| 435 | cmd.extend(['--include_descriptors_from_image', img]) |
| 436 | |
| 437 | # replace pubkeys of chained_partitions as well |
| 438 | for name, descriptor in descriptors: |
| 439 | if name == 'Chain Partition descriptor': |
| 440 | part_name = descriptor['Partition Name'] |
| 441 | ril = descriptor['Rollback Index Location'] |
| 442 | part_key = chained_partitions[part_name] |
| 443 | avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey') |
| 444 | ExtractAvbPubkey(args, part_key, avbpubkey) |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 445 | cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}']) |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 446 | |
Jooyung Han | 98498f4 | 2022-02-07 15:23:08 +0900 | [diff] [blame] | 447 | if args.signing_args: |
| 448 | cmd.extend(shlex.split(args.signing_args)) |
| 449 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 450 | RunCommand(args, cmd) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 451 | check_resigned_image_avb_info(vbmeta_img, info, descriptors, args) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 452 | # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition |
| 453 | # which matches this or the read will fail. |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 454 | with open(vbmeta_img, 'a', encoding='utf8') as f: |
Jooyung Han | dcb0b49 | 2022-02-26 09:04:17 +0900 | [diff] [blame] | 455 | f.truncate(65536) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 456 | |
| 457 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 458 | def UnpackSuperImg(args, super_img, work_dir): |
| 459 | tmp_super_img = os.path.join(work_dir, 'super.img') |
| 460 | RunCommand(args, ['simg2img', super_img, tmp_super_img]) |
| 461 | RunCommand(args, ['lpunpack', tmp_super_img, work_dir]) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 462 | |
| 463 | |
| 464 | def MakeSuperImage(args, partitions, output): |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 465 | with tempfile.TemporaryDirectory() as work_dir: |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 466 | cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B |
| 467 | '--metadata-size=65536', '--sparse', '--output=' + output] |
| 468 | |
| 469 | for part, img in partitions.items(): |
| 470 | tmp_img = os.path.join(work_dir, part) |
| 471 | RunCommand(args, ['img2simg', img, tmp_img]) |
| 472 | |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 473 | image_arg = f'--image={part}={img}' |
| 474 | partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default' |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 475 | cmd.extend([image_arg, partition_arg]) |
| 476 | |
| 477 | RunCommand(args, cmd) |
| 478 | |
| 479 | |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 480 | def GenVbmetaImage(args, image, output, partition_name, salt): |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 481 | cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size', |
| 482 | '--do_not_append_vbmeta_image', |
| 483 | '--partition_name', partition_name, |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 484 | '--salt', salt, |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 485 | '--image', image, |
| 486 | '--output_vbmeta_image', output] |
| 487 | RunCommand(args, cmd) |
| 488 | |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 489 | |
Inseob Kim | 0276f61 | 2023-12-07 17:25:18 +0900 | [diff] [blame] | 490 | gki_versions = ['android14-6.1'] |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 491 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 492 | # dict of (key, file) for re-sign/verification. keys are un-versioned for readability. |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 493 | virt_apex_non_gki_files = { |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 494 | 'kernel': 'etc/fs/microdroid_kernel', |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 495 | 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img', |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 496 | 'super.img': 'etc/fs/microdroid_super.img', |
| 497 | 'initrd_normal.img': 'etc/microdroid_initrd_normal.img', |
| 498 | 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img', |
Alice Wang | be8330c | 2023-10-19 08:55:07 +0000 | [diff] [blame] | 499 | 'rialto': 'etc/rialto.bin', |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 500 | } |
| 501 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 502 | def TargetFiles(input_dir): |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 503 | ret = {k: os.path.join(input_dir, v) for k, v in virt_apex_non_gki_files.items()} |
| 504 | |
| 505 | for ver in gki_versions: |
| 506 | kernel = os.path.join(input_dir, f'etc/fs/microdroid_gki-{ver}_kernel') |
| 507 | initrd_normal = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_normal.img') |
| 508 | initrd_debug = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_debuggable.img') |
| 509 | |
| 510 | if os.path.isfile(kernel): |
| 511 | ret[f'gki-{ver}_kernel'] = kernel |
| 512 | ret[f'gki-{ver}_initrd_normal.img'] = initrd_normal |
| 513 | ret[f'gki-{ver}_initrd_debuggable.img'] = initrd_debug |
| 514 | |
| 515 | return ret |
| 516 | |
| 517 | def IsInitrdImage(path): |
| 518 | return path.endswith('initrd_normal.img') or path.endswith('initrd_debuggable.img') |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 519 | |
| 520 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 521 | def SignVirtApex(args): |
| 522 | key = args.key |
| 523 | input_dir = args.input_dir |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 524 | files = TargetFiles(input_dir) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 525 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 526 | # unpacked files (will be unpacked from super.img below) |
| 527 | system_a_img = os.path.join(unpack_dir.name, 'system_a.img') |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 528 | vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 529 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 530 | # re-sign super.img |
Jooyung Han | bae6ce4 | 2022-09-13 15:15:18 +0900 | [diff] [blame] | 531 | # 1. unpack super.img |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 532 | # 2. resign system and vendor (if exists) |
| 533 | # 3. repack super.img out of resigned system and vendor (if exists) |
Jooyung Han | bae6ce4 | 2022-09-13 15:15:18 +0900 | [diff] [blame] | 534 | UnpackSuperImg(args, files['super.img'], unpack_dir.name) |
| 535 | system_a_f = Async(AddHashTreeFooter, args, key, system_a_img) |
Nikita Ioffe | baf578d | 2023-06-14 20:29:37 +0000 | [diff] [blame] | 536 | partitions = {"system_a": system_a_img} |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 537 | images = [system_a_img] |
| 538 | images_f = [system_a_f] |
| 539 | |
| 540 | # if vendor_a.img exists, resign it |
| 541 | if os.path.exists(vendor_a_img): |
| 542 | partitions.update({'vendor_a': vendor_a_img}) |
| 543 | images.append(vendor_a_img) |
| 544 | vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img) |
| 545 | images_f.append(vendor_a_f) |
| 546 | |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 547 | Async(MakeSuperImage, args, partitions, |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 548 | files['super.img'], wait=images_f) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 549 | |
Nikita Ioffe | baf578d | 2023-06-14 20:29:37 +0000 | [diff] [blame] | 550 | # re-generate vbmeta from re-signed system_a.img |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 551 | vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'], |
Nikita Ioffe | e111203 | 2023-11-13 15:09:39 +0000 | [diff] [blame] | 552 | images=images, |
| 553 | wait=images_f) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 554 | |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 555 | vbmeta_bc_f = None |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 556 | if not args.do_not_update_bootconfigs: |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 557 | initrd_files = [v for k, v in files.items() if IsInitrdImage(k)] |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 558 | vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args, initrd_files, |
| 559 | files['vbmeta.img'], |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 560 | wait=[vbmeta_f]) |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 561 | |
Shikha Panwar | c149d24 | 2023-01-20 16:23:04 +0000 | [diff] [blame] | 562 | # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s) |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 563 | def resign_kernel(kernel, initrd_normal, initrd_debug): |
| 564 | kernel_file = files[kernel] |
| 565 | initrd_normal_file = files[initrd_normal] |
| 566 | initrd_debug_file = files[initrd_debug] |
| 567 | |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 568 | _, kernel_image_descriptors = AvbInfo(args, kernel_file) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 569 | salts = extract_hash_descriptors( |
| 570 | kernel_image_descriptors, lambda descriptor: descriptor['Salt']) |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 571 | initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name |
| 572 | initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name |
| 573 | initrd_n_f = Async(GenVbmetaImage, args, initrd_normal_file, |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 574 | initrd_normal_hashdesc, "initrd_normal", salts["initrd_normal"], |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 575 | wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else []) |
| 576 | initrd_d_f = Async(GenVbmetaImage, args, initrd_debug_file, |
Seungjae Yoo | 4357448 | 2024-01-11 16:27:51 +0900 | [diff] [blame] | 577 | initrd_debug_hashdesc, "initrd_debug", salts["initrd_debug"], |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 578 | wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else []) |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 579 | return Async(AddHashFooter, args, key, kernel_file, |
| 580 | additional_images=[initrd_normal_hashdesc, initrd_debug_hashdesc], |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 581 | wait=[initrd_n_f, initrd_d_f]) |
| 582 | |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 583 | _, original_kernel_descriptors = AvbInfo(args, files['kernel']) |
| 584 | resign_kernel_task = resign_kernel('kernel', 'initrd_normal.img', 'initrd_debuggable.img') |
Inseob Kim | 77c7f71 | 2023-11-06 17:01:02 +0900 | [diff] [blame] | 585 | |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 586 | for ver in gki_versions: |
| 587 | if f'gki-{ver}_kernel' in files: |
| 588 | resign_kernel( |
| 589 | f'gki-{ver}_kernel', |
| 590 | f'gki-{ver}_initrd_normal.img', |
| 591 | f'gki-{ver}_initrd_debuggable.img') |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame] | 592 | |
Alice Wang | be8330c | 2023-10-19 08:55:07 +0000 | [diff] [blame] | 593 | # Re-sign rialto if it exists. Rialto only exists in arm64 environment. |
| 594 | if os.path.exists(files['rialto']): |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 595 | update_initrd_digests_task = Async( |
| 596 | update_initrd_digests_in_rialto, original_kernel_descriptors, args, |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 597 | files, wait=[resign_kernel_task]) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 598 | Async(resign_rialto, args, key, files['rialto'], wait=[update_initrd_digests_task]) |
Alice Wang | be8330c | 2023-10-19 08:55:07 +0000 | [diff] [blame] | 599 | |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 600 | def resign_rialto(args, key, rialto_path): |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 601 | _, original_descriptors = AvbInfo(args, rialto_path) |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 602 | AddHashFooter(args, key, rialto_path) |
| 603 | |
| 604 | # Verify the new AVB footer. |
| 605 | updated_info, updated_descriptors = AvbInfo(args, rialto_path) |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 606 | assert len(updated_descriptors) == 2, \ |
| 607 | f"There should be two descriptors for rialto. Updated descriptors: {updated_descriptors}" |
| 608 | updated_prop = find_all_values_by_key(updated_descriptors, "Prop") |
| 609 | assert len(updated_prop) == 1, "There should be only one Prop descriptor for rialto. " \ |
| 610 | f"Updated descriptors: {updated_descriptors}" |
| 611 | assert updated_info["Rollback Index"] != "0", "Rollback index should not be zero for rialto." |
| 612 | |
| 613 | # Verify the only hash descriptor of rialto. |
| 614 | updated_hash_descriptors = extract_hash_descriptors(updated_descriptors) |
| 615 | assert len(updated_hash_descriptors) == 1, \ |
| 616 | f"There should be only one hash descriptor for rialto. " \ |
| 617 | f"Updated hash descriptors: {updated_hash_descriptors}" |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 618 | # Since salt is not updated, the change of digest reflects the change of content of rialto |
| 619 | # kernel. |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 620 | if not args.do_not_update_bootconfigs: |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 621 | [(_, original_descriptor)] = extract_hash_descriptors(original_descriptors).items() |
| 622 | [(_, updated_descriptor)] = updated_hash_descriptors.items() |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 623 | assert_different_value(original_descriptor, updated_descriptor, "Digest", |
| 624 | "rialto_hash_descriptor") |
| 625 | |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 626 | def assert_different_value(original, updated, key, context): |
| 627 | assert original[key] != updated[key], \ |
| 628 | f"Value of '{key}' should change for '{context}'" \ |
| 629 | f"Original value: {original[key]}, updated value: {updated[key]}" |
| 630 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 631 | def update_initrd_digests_in_rialto(original_descriptors, args, files): |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 632 | _, updated_descriptors = AvbInfo(args, files['kernel']) |
| 633 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 634 | original_digests = extract_hash_descriptors( |
| 635 | original_descriptors, lambda x: binascii.unhexlify(x['Digest'])) |
| 636 | updated_digests = extract_hash_descriptors( |
| 637 | updated_descriptors, lambda x: binascii.unhexlify(x['Digest'])) |
| 638 | assert original_digests.pop("boot") == updated_digests.pop("boot"), \ |
| 639 | "Hash descriptor of boot should not change for kernel. " \ |
| 640 | f"Original descriptors: {original_descriptors}, " \ |
| 641 | f"updated descriptors: {updated_descriptors}" |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 642 | |
| 643 | # Update the hashes of initrd_normal and initrd_debug in rialto if the |
| 644 | # bootconfigs in them are updated. |
| 645 | if args.do_not_update_bootconfigs: |
| 646 | return |
| 647 | |
| 648 | with open(files['rialto'], "rb") as file: |
| 649 | content = file.read() |
| 650 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 651 | # Check that the original and updated digests are different before updating rialto. |
| 652 | partition_names = {'initrd_normal', 'initrd_debug'} |
| 653 | assert set(original_digests.keys()) == set(updated_digests.keys()) == partition_names, \ |
| 654 | f"Original digests' partitions should be {partition_names}. " \ |
| 655 | f"Original digests: {original_digests}. Updated digests: {updated_digests}" |
| 656 | assert set(original_digests.values()).isdisjoint(updated_digests.values()), \ |
| 657 | "Digests of initrd_normal and initrd_debug should change. " \ |
| 658 | f"Original descriptors: {original_descriptors}, " \ |
| 659 | f"updated descriptors: {updated_descriptors}" |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 660 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 661 | for partition_name, original_digest in original_digests.items(): |
| 662 | updated_digest = updated_digests[partition_name] |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 663 | assert len(original_digest) == len(updated_digest), \ |
| 664 | f"Length of original_digest and updated_digest must be the same for {partition_name}." \ |
| 665 | f" Original digest: {original_digest}, updated digest: {updated_digest}" |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 666 | |
| 667 | new_content = content.replace(original_digest, updated_digest) |
| 668 | assert len(new_content) == len(content), \ |
| 669 | "Length of new_content and content must be the same." |
| 670 | assert new_content != content, \ |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 671 | f"original digest of the partition {partition_name} not found." |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 672 | content = new_content |
| 673 | |
Alice Wang | 2a6caf1 | 2024-01-11 08:14:05 +0000 | [diff] [blame] | 674 | with open(files['rialto'], "wb") as file: |
| 675 | file.write(content) |
| 676 | |
Alice Wang | 34c1923 | 2024-01-11 16:06:28 +0000 | [diff] [blame] | 677 | def extract_hash_descriptors(descriptors, f=lambda x: x): |
| 678 | return {desc["Partition Name"]: f(desc) for desc in |
| 679 | find_all_values_by_key(descriptors, "Hash descriptor")} |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 680 | |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 681 | def VerifyVirtApex(args): |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 682 | key = args.key |
| 683 | input_dir = args.input_dir |
| 684 | files = TargetFiles(input_dir) |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 685 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 686 | # unpacked files |
| 687 | UnpackSuperImg(args, files['super.img'], unpack_dir.name) |
| 688 | system_a_img = os.path.join(unpack_dir.name, 'system_a.img') |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 689 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 690 | # Read pubkey digest from the input key |
| 691 | with tempfile.NamedTemporaryFile() as pubkey_file: |
| 692 | ExtractAvbPubkey(args, key, pubkey_file.name) |
| 693 | with open(pubkey_file.name, 'rb') as f: |
| 694 | pubkey = f.read() |
| 695 | pubkey_digest = hashlib.sha1(pubkey).hexdigest() |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 696 | |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 697 | def check_avb_pubkey(file): |
| 698 | info, _ = AvbInfo(args, file) |
Jiyong Park | 40bf2dc | 2022-05-23 23:41:25 +0900 | [diff] [blame] | 699 | assert info is not None, f'no avbinfo: {file}' |
| 700 | assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}' |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 701 | |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 702 | for k, f in files.items(): |
| 703 | if IsInitrdImage(k): |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 704 | # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest |
| 705 | continue |
Alice Wang | be8330c | 2023-10-19 08:55:07 +0000 | [diff] [blame] | 706 | if k == 'rialto' and not os.path.exists(f): |
| 707 | # Rialto only exists in arm64 environment. |
| 708 | continue |
Inseob Kim | 7a1fc8f | 2023-11-22 18:45:28 +0900 | [diff] [blame] | 709 | if k == 'super.img': |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 710 | Async(check_avb_pubkey, system_a_img) |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 711 | else: |
| 712 | # Check pubkey for other files using avbtool |
| 713 | Async(check_avb_pubkey, f) |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 714 | |
| 715 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 716 | def main(argv): |
| 717 | try: |
| 718 | args = ParseArgs(argv) |
Jooyung Han | 02dceed | 2021-11-08 17:50:22 +0900 | [diff] [blame] | 719 | if args.verify: |
| 720 | VerifyVirtApex(args) |
| 721 | else: |
| 722 | SignVirtApex(args) |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 723 | # ensure all tasks are completed without exceptions |
| 724 | AwaitAll(tasks) |
Shikha Panwar | a7605cf | 2023-01-12 09:29:39 +0000 | [diff] [blame] | 725 | except: # pylint: disable=bare-except |
Jooyung Han | 486609f | 2022-04-20 11:38:00 +0900 | [diff] [blame] | 726 | traceback.print_exc() |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 727 | sys.exit(1) |
| 728 | |
| 729 | |
| 730 | if __name__ == '__main__': |
| 731 | main(sys.argv[1:]) |