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 | |
| 18 | Typical usage: sign_virt_apex [-v] [--avbtool path_to_avbtool] path_to_key payload_contents_dir |
| 19 | |
| 20 | sign_virt_apex uses external tools which are assumed to be available via PATH. |
| 21 | - avbtool (--avbtool can override the tool) |
| 22 | - lpmake, lpunpack, simg2img, img2simg |
| 23 | """ |
| 24 | import argparse |
| 25 | import os |
| 26 | import re |
| 27 | import shutil |
| 28 | import subprocess |
| 29 | import sys |
| 30 | import tempfile |
| 31 | |
| 32 | |
| 33 | def ParseArgs(argv): |
| 34 | parser = argparse.ArgumentParser(description='Sign the Virt APEX') |
| 35 | parser.add_argument( |
| 36 | '-v', '--verbose', |
| 37 | action='store_true', |
| 38 | help='verbose execution') |
| 39 | parser.add_argument( |
| 40 | '--avbtool', |
| 41 | default='avbtool', |
| 42 | help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.') |
| 43 | parser.add_argument( |
| 44 | 'key', |
| 45 | help='path to the private key file.') |
| 46 | parser.add_argument( |
| 47 | 'input_dir', |
| 48 | help='the directory having files to be packaged') |
| 49 | return parser.parse_args(argv) |
| 50 | |
| 51 | |
| 52 | def RunCommand(args, cmd, env=None, expected_return_values={0}): |
| 53 | env = env or {} |
| 54 | env.update(os.environ.copy()) |
| 55 | |
| 56 | # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts |
| 57 | # e.g. sign_apex.py, sign_target_files_apk.py |
| 58 | if cmd[0] == 'avbtool': |
| 59 | cmd[0] = args.avbtool |
| 60 | |
| 61 | if args.verbose: |
| 62 | print('Running: ' + ' '.join(cmd)) |
| 63 | p = subprocess.Popen( |
| 64 | cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True) |
| 65 | output, _ = p.communicate() |
| 66 | |
| 67 | if args.verbose or p.returncode not in expected_return_values: |
| 68 | print(output.rstrip()) |
| 69 | |
| 70 | assert p.returncode in expected_return_values, ( |
| 71 | '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode |
| 72 | return (output, p.returncode) |
| 73 | |
| 74 | |
| 75 | def ReadBytesSize(value): |
| 76 | return int(value.removesuffix(' bytes')) |
| 77 | |
| 78 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 79 | def ExtractAvbPubkey(args, key, output): |
| 80 | RunCommand(args, ['avbtool', 'extract_public_key', |
| 81 | '--key', key, '--output', output]) |
| 82 | |
| 83 | |
| 84 | def AvbInfo(args, image_path): |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 85 | """Parses avbtool --info image output |
| 86 | |
| 87 | Args: |
| 88 | args: program arguments. |
| 89 | image_path: The path to the image. |
| 90 | descriptor_name: Descriptor name of interest. |
| 91 | |
| 92 | Returns: |
| 93 | A pair of |
| 94 | - 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^] | 95 | - a list of descriptors. |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 96 | """ |
| 97 | if not os.path.exists(image_path): |
| 98 | raise ValueError('Failed to find image: {}'.format(image_path)) |
| 99 | |
| 100 | output, ret_code = RunCommand( |
| 101 | args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1}) |
| 102 | if ret_code == 1: |
| 103 | return None, None |
| 104 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 105 | info, descriptors = {}, [] |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 106 | |
| 107 | # Read `avbtool info_image` output as "key:value" lines |
| 108 | matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$') |
| 109 | |
| 110 | def IterateLine(output): |
| 111 | for line in output.split('\n'): |
| 112 | line_info = matcher.match(line) |
| 113 | if not line_info: |
| 114 | continue |
| 115 | yield line_info.group(1), line_info.group(2), line_info.group(3) |
| 116 | |
| 117 | gen = IterateLine(output) |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 118 | |
| 119 | def ReadDescriptors(cur_indent, cur_name, cur_value): |
| 120 | descriptor = cur_value if cur_name == 'Prop' else {} |
| 121 | descriptors.append((cur_name, descriptor)) |
| 122 | for indent, key, value in gen: |
| 123 | if indent <= cur_indent: |
| 124 | # read descriptors recursively to pass the read key as descriptor name |
| 125 | ReadDescriptors(indent, key, value) |
| 126 | break |
| 127 | descriptor[key] = value |
| 128 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 129 | # Read VBMeta info |
| 130 | for _, key, value in gen: |
| 131 | if key == 'Descriptors': |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 132 | ReadDescriptors(*next(gen)) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 133 | break |
| 134 | info[key] = value |
| 135 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 136 | return info, descriptors |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 137 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 138 | |
| 139 | # Look up a list of (key, value) with a key. Returns the value of the first matching pair. |
| 140 | def LookUp(pairs, key): |
| 141 | for k, v in pairs: |
| 142 | if key == k: |
| 143 | return v |
| 144 | return None |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 145 | |
| 146 | |
| 147 | def AddHashFooter(args, key, image_path): |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 148 | info, descriptors = AvbInfo(args, image_path) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 149 | if info: |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 150 | descriptor = LookUp(descriptors, 'Hash descriptor') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 151 | image_size = ReadBytesSize(info['Image size']) |
| 152 | algorithm = info['Algorithm'] |
| 153 | partition_name = descriptor['Partition Name'] |
| 154 | partition_size = str(image_size) |
| 155 | |
| 156 | cmd = ['avbtool', 'add_hash_footer', |
| 157 | '--key', key, |
| 158 | '--algorithm', algorithm, |
| 159 | '--partition_name', partition_name, |
| 160 | '--partition_size', partition_size, |
| 161 | '--image', image_path] |
| 162 | RunCommand(args, cmd) |
| 163 | |
| 164 | |
| 165 | def AddHashTreeFooter(args, key, image_path): |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 166 | info, descriptors = AvbInfo(args, image_path) |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 167 | if info: |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 168 | descriptor = LookUp(descriptors, 'Hashtree descriptor') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 169 | image_size = ReadBytesSize(info['Image size']) |
| 170 | algorithm = info['Algorithm'] |
| 171 | partition_name = descriptor['Partition Name'] |
| 172 | partition_size = str(image_size) |
| 173 | |
| 174 | cmd = ['avbtool', 'add_hashtree_footer', |
| 175 | '--key', key, |
| 176 | '--algorithm', algorithm, |
| 177 | '--partition_name', partition_name, |
| 178 | '--partition_size', partition_size, |
| 179 | '--do_not_generate_fec', |
| 180 | '--image', image_path] |
| 181 | RunCommand(args, cmd) |
| 182 | |
| 183 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 184 | def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None): |
| 185 | info, descriptors = AvbInfo(args, vbmeta_img) |
| 186 | if info is None: |
| 187 | return |
| 188 | |
| 189 | with TempDirectory() as work_dir: |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 190 | algorithm = info['Algorithm'] |
| 191 | rollback_index = info['Rollback Index'] |
| 192 | rollback_index_location = info['Rollback Index Location'] |
| 193 | |
| 194 | cmd = ['avbtool', 'make_vbmeta_image', |
| 195 | '--key', key, |
| 196 | '--algorithm', algorithm, |
| 197 | '--rollback_index', rollback_index, |
| 198 | '--rollback_index_location', rollback_index_location, |
| 199 | '--output', vbmeta_img] |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 200 | if images: |
| 201 | for img in images: |
| 202 | cmd.extend(['--include_descriptors_from_image', img]) |
| 203 | |
| 204 | # replace pubkeys of chained_partitions as well |
| 205 | for name, descriptor in descriptors: |
| 206 | if name == 'Chain Partition descriptor': |
| 207 | part_name = descriptor['Partition Name'] |
| 208 | ril = descriptor['Rollback Index Location'] |
| 209 | part_key = chained_partitions[part_name] |
| 210 | avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey') |
| 211 | ExtractAvbPubkey(args, part_key, avbpubkey) |
| 212 | cmd.extend(['--chain_partition', '%s:%s:%s' % |
| 213 | (part_name, ril, avbpubkey)]) |
| 214 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 215 | RunCommand(args, cmd) |
| 216 | # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition |
| 217 | # which matches this or the read will fail. |
| 218 | RunCommand(args, ['truncate', '-s', '65536', vbmeta_img]) |
| 219 | |
| 220 | |
| 221 | class TempDirectory(object): |
| 222 | |
| 223 | def __enter__(self): |
| 224 | self.name = tempfile.mkdtemp() |
| 225 | return self.name |
| 226 | |
| 227 | def __exit__(self, *unused): |
| 228 | shutil.rmtree(self.name) |
| 229 | |
| 230 | |
| 231 | def MakeSuperImage(args, partitions, output): |
| 232 | with TempDirectory() as work_dir: |
| 233 | cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B |
| 234 | '--metadata-size=65536', '--sparse', '--output=' + output] |
| 235 | |
| 236 | for part, img in partitions.items(): |
| 237 | tmp_img = os.path.join(work_dir, part) |
| 238 | RunCommand(args, ['img2simg', img, tmp_img]) |
| 239 | |
| 240 | image_arg = '--image=%s=%s' % (part, img) |
| 241 | partition_arg = '--partition=%s:readonly:%d:default' % ( |
| 242 | part, os.path.getsize(img)) |
| 243 | cmd.extend([image_arg, partition_arg]) |
| 244 | |
| 245 | RunCommand(args, cmd) |
| 246 | |
| 247 | |
Jooyung Han | 31b1c2b | 2021-10-27 03:35:42 +0900 | [diff] [blame] | 248 | def ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey): |
| 249 | # read old pubkey before replacement |
| 250 | with open(bootloader_pubkey, 'rb') as f: |
| 251 | old_pubkey = f.read() |
| 252 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 253 | # replace bootloader pubkey (overwrite the old one with the new one) |
| 254 | ExtractAvbPubkey(args, key, bootloader_pubkey) |
Jooyung Han | 31b1c2b | 2021-10-27 03:35:42 +0900 | [diff] [blame] | 255 | |
| 256 | # read new pubkey |
| 257 | with open(bootloader_pubkey, 'rb') as f: |
| 258 | new_pubkey = f.read() |
| 259 | |
| 260 | assert len(old_pubkey) == len(new_pubkey) |
| 261 | |
| 262 | # replace pubkey embedded in bootloader |
| 263 | with open(bootloader, 'r+b') as bl_f: |
| 264 | pos = bl_f.read().find(old_pubkey) |
| 265 | assert pos != -1 |
| 266 | bl_f.seek(pos) |
| 267 | bl_f.write(new_pubkey) |
| 268 | |
| 269 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 270 | def SignVirtApex(args): |
| 271 | key = args.key |
| 272 | input_dir = args.input_dir |
| 273 | |
| 274 | # target files in the Virt APEX |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 275 | bootloader_pubkey = os.path.join( |
| 276 | input_dir, 'etc', 'microdroid_bootloader.avbpubkey') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 277 | bootloader = os.path.join(input_dir, 'etc', 'microdroid_bootloader') |
| 278 | boot_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_boot-5.10.img') |
| 279 | vendor_boot_img = os.path.join( |
| 280 | input_dir, 'etc', 'fs', 'microdroid_vendor_boot-5.10.img') |
| 281 | super_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_super.img') |
| 282 | vbmeta_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_vbmeta.img') |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 283 | vbmeta_bootconfig_img = os.path.join( |
| 284 | input_dir, 'etc', 'fs', 'microdroid_vbmeta_bootconfig.img') |
| 285 | bootconfig_normal = os.path.join( |
| 286 | input_dir, 'etc', 'microdroid_bootconfig.normal') |
| 287 | bootconfig_app_debuggable = os.path.join( |
| 288 | input_dir, 'etc', 'microdroid_bootconfig.app_debuggable') |
| 289 | bootconfig_full_debuggable = os.path.join( |
| 290 | input_dir, 'etc', 'microdroid_bootconfig.full_debuggable') |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 291 | |
Jooyung Han | 31b1c2b | 2021-10-27 03:35:42 +0900 | [diff] [blame] | 292 | # Key(pubkey) for bootloader should match with the one used to make VBmeta below |
| 293 | # while it's okay to use different keys for other image files. |
| 294 | ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey) |
| 295 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 296 | # re-sign bootloader, boot.img, vendor_boot.img |
| 297 | AddHashFooter(args, key, bootloader) |
| 298 | AddHashFooter(args, key, boot_img) |
| 299 | AddHashFooter(args, key, vendor_boot_img) |
| 300 | |
| 301 | # re-sign super.img |
| 302 | with TempDirectory() as work_dir: |
| 303 | # unpack super.img |
| 304 | tmp_super_img = os.path.join(work_dir, 'super.img') |
| 305 | RunCommand(args, ['simg2img', super_img, tmp_super_img]) |
| 306 | RunCommand(args, ['lpunpack', tmp_super_img, work_dir]) |
| 307 | |
| 308 | system_a_img = os.path.join(work_dir, 'system_a.img') |
| 309 | vendor_a_img = os.path.join(work_dir, 'vendor_a.img') |
| 310 | partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img} |
| 311 | |
| 312 | # re-sign partitions in super.img |
| 313 | for img in partitions.values(): |
| 314 | AddHashTreeFooter(args, key, img) |
| 315 | |
| 316 | # re-pack super.img |
| 317 | MakeSuperImage(args, partitions, super_img) |
| 318 | |
| 319 | # re-generate vbmeta from re-signed {boot, vendor_boot, system_a, vendor_a}.img |
| 320 | # Ideally, making VBmeta should be done out of TempDirectory block. But doing it here |
| 321 | # to avoid unpacking re-signed super.img for system/vendor images which are available |
| 322 | # in this block. |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 323 | MakeVbmetaImage(args, key, vbmeta_img, images=[ |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 324 | boot_img, vendor_boot_img, system_a_img, vendor_a_img]) |
| 325 | |
Jooyung Han | 832d11d | 2021-11-08 12:51:47 +0900 | [diff] [blame^] | 326 | # Re-sign bootconfigs with the same key |
| 327 | bootconfig_sign_key = key |
| 328 | AddHashFooter(args, bootconfig_sign_key, bootconfig_normal) |
| 329 | AddHashFooter(args, bootconfig_sign_key, bootconfig_app_debuggable) |
| 330 | AddHashFooter(args, bootconfig_sign_key, bootconfig_full_debuggable) |
| 331 | |
| 332 | # Re-sign vbmeta_bootconfig with a chained_partition to "bootconfig" |
| 333 | # Note that, for now, `key` and `bootconfig_sign_key` are the same, but technically they |
| 334 | # can be different. Vbmeta records pubkeys which signed chained partitions. |
| 335 | MakeVbmetaImage(args, key, vbmeta_bootconfig_img, chained_partitions={ |
| 336 | 'bootconfig': bootconfig_sign_key}) |
| 337 | |
Jooyung Han | 504105f | 2021-10-26 15:54:50 +0900 | [diff] [blame] | 338 | |
| 339 | def main(argv): |
| 340 | try: |
| 341 | args = ParseArgs(argv) |
| 342 | SignVirtApex(args) |
| 343 | except Exception as e: |
| 344 | print(e) |
| 345 | sys.exit(1) |
| 346 | |
| 347 | |
| 348 | if __name__ == '__main__': |
| 349 | main(sys.argv[1:]) |