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 | |
| 79 | def AvbInfo(args, image_path, descriptor_name=None): |
| 80 | """Parses avbtool --info image output |
| 81 | |
| 82 | Args: |
| 83 | args: program arguments. |
| 84 | image_path: The path to the image. |
| 85 | descriptor_name: Descriptor name of interest. |
| 86 | |
| 87 | Returns: |
| 88 | A pair of |
| 89 | - a dict that contains VBMeta info. None if there's no VBMeta info. |
| 90 | - a dict that contains target descriptor info. None if name is not specified or not found. |
| 91 | """ |
| 92 | if not os.path.exists(image_path): |
| 93 | raise ValueError('Failed to find image: {}'.format(image_path)) |
| 94 | |
| 95 | output, ret_code = RunCommand( |
| 96 | args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1}) |
| 97 | if ret_code == 1: |
| 98 | return None, None |
| 99 | |
| 100 | info, descriptor = {}, None |
| 101 | |
| 102 | # Read `avbtool info_image` output as "key:value" lines |
| 103 | matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$') |
| 104 | |
| 105 | def IterateLine(output): |
| 106 | for line in output.split('\n'): |
| 107 | line_info = matcher.match(line) |
| 108 | if not line_info: |
| 109 | continue |
| 110 | yield line_info.group(1), line_info.group(2), line_info.group(3) |
| 111 | |
| 112 | gen = IterateLine(output) |
| 113 | # Read VBMeta info |
| 114 | for _, key, value in gen: |
| 115 | if key == 'Descriptors': |
| 116 | break |
| 117 | info[key] = value |
| 118 | |
| 119 | if descriptor_name: |
| 120 | for indent, key, _ in gen: |
| 121 | # Read a target descriptor |
| 122 | if key == descriptor_name: |
| 123 | cur_indent = indent |
| 124 | descriptor = {} |
| 125 | for indent, key, value in gen: |
| 126 | if indent == cur_indent: |
| 127 | break |
| 128 | descriptor[key] = value |
| 129 | break |
| 130 | |
| 131 | return info, descriptor |
| 132 | |
| 133 | |
| 134 | def AddHashFooter(args, key, image_path): |
| 135 | info, descriptor = AvbInfo(args, image_path, 'Hash descriptor') |
| 136 | if info: |
| 137 | image_size = ReadBytesSize(info['Image size']) |
| 138 | algorithm = info['Algorithm'] |
| 139 | partition_name = descriptor['Partition Name'] |
| 140 | partition_size = str(image_size) |
| 141 | |
| 142 | cmd = ['avbtool', 'add_hash_footer', |
| 143 | '--key', key, |
| 144 | '--algorithm', algorithm, |
| 145 | '--partition_name', partition_name, |
| 146 | '--partition_size', partition_size, |
| 147 | '--image', image_path] |
| 148 | RunCommand(args, cmd) |
| 149 | |
| 150 | |
| 151 | def AddHashTreeFooter(args, key, image_path): |
| 152 | info, descriptor = AvbInfo(args, image_path, 'Hashtree descriptor') |
| 153 | if info: |
| 154 | image_size = ReadBytesSize(info['Image size']) |
| 155 | algorithm = info['Algorithm'] |
| 156 | partition_name = descriptor['Partition Name'] |
| 157 | partition_size = str(image_size) |
| 158 | |
| 159 | cmd = ['avbtool', 'add_hashtree_footer', |
| 160 | '--key', key, |
| 161 | '--algorithm', algorithm, |
| 162 | '--partition_name', partition_name, |
| 163 | '--partition_size', partition_size, |
| 164 | '--do_not_generate_fec', |
| 165 | '--image', image_path] |
| 166 | RunCommand(args, cmd) |
| 167 | |
| 168 | |
| 169 | def MakeVbmetaImage(args, key, vbmeta_img, images): |
| 170 | info, _ = AvbInfo(args, vbmeta_img) |
| 171 | if info: |
| 172 | algorithm = info['Algorithm'] |
| 173 | rollback_index = info['Rollback Index'] |
| 174 | rollback_index_location = info['Rollback Index Location'] |
| 175 | |
| 176 | cmd = ['avbtool', 'make_vbmeta_image', |
| 177 | '--key', key, |
| 178 | '--algorithm', algorithm, |
| 179 | '--rollback_index', rollback_index, |
| 180 | '--rollback_index_location', rollback_index_location, |
| 181 | '--output', vbmeta_img] |
| 182 | for img in images: |
| 183 | cmd.extend(['--include_descriptors_from_image', img]) |
| 184 | RunCommand(args, cmd) |
| 185 | # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition |
| 186 | # which matches this or the read will fail. |
| 187 | RunCommand(args, ['truncate', '-s', '65536', vbmeta_img]) |
| 188 | |
| 189 | |
| 190 | class TempDirectory(object): |
| 191 | |
| 192 | def __enter__(self): |
| 193 | self.name = tempfile.mkdtemp() |
| 194 | return self.name |
| 195 | |
| 196 | def __exit__(self, *unused): |
| 197 | shutil.rmtree(self.name) |
| 198 | |
| 199 | |
| 200 | def MakeSuperImage(args, partitions, output): |
| 201 | with TempDirectory() as work_dir: |
| 202 | cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B |
| 203 | '--metadata-size=65536', '--sparse', '--output=' + output] |
| 204 | |
| 205 | for part, img in partitions.items(): |
| 206 | tmp_img = os.path.join(work_dir, part) |
| 207 | RunCommand(args, ['img2simg', img, tmp_img]) |
| 208 | |
| 209 | image_arg = '--image=%s=%s' % (part, img) |
| 210 | partition_arg = '--partition=%s:readonly:%d:default' % ( |
| 211 | part, os.path.getsize(img)) |
| 212 | cmd.extend([image_arg, partition_arg]) |
| 213 | |
| 214 | RunCommand(args, cmd) |
| 215 | |
| 216 | |
| 217 | def SignVirtApex(args): |
| 218 | key = args.key |
| 219 | input_dir = args.input_dir |
| 220 | |
| 221 | # target files in the Virt APEX |
| 222 | bootloader = os.path.join(input_dir, 'etc', 'microdroid_bootloader') |
| 223 | boot_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_boot-5.10.img') |
| 224 | vendor_boot_img = os.path.join( |
| 225 | input_dir, 'etc', 'fs', 'microdroid_vendor_boot-5.10.img') |
| 226 | super_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_super.img') |
| 227 | vbmeta_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_vbmeta.img') |
| 228 | |
| 229 | # re-sign bootloader, boot.img, vendor_boot.img |
| 230 | AddHashFooter(args, key, bootloader) |
| 231 | AddHashFooter(args, key, boot_img) |
| 232 | AddHashFooter(args, key, vendor_boot_img) |
| 233 | |
| 234 | # re-sign super.img |
| 235 | with TempDirectory() as work_dir: |
| 236 | # unpack super.img |
| 237 | tmp_super_img = os.path.join(work_dir, 'super.img') |
| 238 | RunCommand(args, ['simg2img', super_img, tmp_super_img]) |
| 239 | RunCommand(args, ['lpunpack', tmp_super_img, work_dir]) |
| 240 | |
| 241 | system_a_img = os.path.join(work_dir, 'system_a.img') |
| 242 | vendor_a_img = os.path.join(work_dir, 'vendor_a.img') |
| 243 | partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img} |
| 244 | |
| 245 | # re-sign partitions in super.img |
| 246 | for img in partitions.values(): |
| 247 | AddHashTreeFooter(args, key, img) |
| 248 | |
| 249 | # re-pack super.img |
| 250 | MakeSuperImage(args, partitions, super_img) |
| 251 | |
| 252 | # re-generate vbmeta from re-signed {boot, vendor_boot, system_a, vendor_a}.img |
| 253 | # Ideally, making VBmeta should be done out of TempDirectory block. But doing it here |
| 254 | # to avoid unpacking re-signed super.img for system/vendor images which are available |
| 255 | # in this block. |
| 256 | MakeVbmetaImage(args, key, vbmeta_img, [ |
| 257 | boot_img, vendor_boot_img, system_a_img, vendor_a_img]) |
| 258 | |
| 259 | |
| 260 | def main(argv): |
| 261 | try: |
| 262 | args = ParseArgs(argv) |
| 263 | SignVirtApex(args) |
| 264 | except Exception as e: |
| 265 | print(e) |
| 266 | sys.exit(1) |
| 267 | |
| 268 | |
| 269 | if __name__ == '__main__': |
| 270 | main(sys.argv[1:]) |