blob: 65e8414cbb07df46e7ac92e8738beb2f1858433b [file] [log] [blame]
Jooyung Han504105f2021-10-26 15:54:50 +09001#!/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 Han98498f42022-02-07 15:23:08 +090018Typical usage:
Jooyung Han486609f2022-04-20 11:38:00 +090019 sign_virt_apex payload_key payload_dir
20 -v, --verbose
21 --verify
22 --avbtool path_to_avbtool
23 --signing_args args
Jooyung Han504105f2021-10-26 15:54:50 +090024
25sign_virt_apex uses external tools which are assumed to be available via PATH.
26- avbtool (--avbtool can override the tool)
Shikha Panwara7605cf2023-01-12 09:29:39 +000027- lpmake, lpunpack, simg2img, img2simg, initrd_bootconfig
Jooyung Han504105f2021-10-26 15:54:50 +090028"""
29import argparse
Jooyung Han02dceed2021-11-08 17:50:22 +090030import hashlib
Jooyung Han504105f2021-10-26 15:54:50 +090031import os
32import re
Jooyung Han98498f42022-02-07 15:23:08 +090033import shlex
Jooyung Han504105f2021-10-26 15:54:50 +090034import subprocess
35import sys
36import tempfile
Jooyung Han486609f2022-04-20 11:38:00 +090037import traceback
38from concurrent import futures
39
40# pylint: disable=line-too-long,consider-using-with
41
42# Use executor to parallelize the invocation of external tools
43# If a task depends on another, pass the future object of the previous task as wait list.
44# Every future object created by a task should be consumed with AwaitAll()
45# so that exceptions are propagated .
46executor = futures.ThreadPoolExecutor()
47
48# Temporary directory for unpacked super.img.
49# We could put its creation/deletion into the task graph as well, but
50# having it as a global setup is much simpler.
51unpack_dir = tempfile.TemporaryDirectory()
52
53# tasks created with Async() are kept in a list so that they are awaited
54# before exit.
55tasks = []
56
57# create an async task and return a future value of it.
58def Async(fn, *args, wait=None, **kwargs):
59
60 # wrap a function with AwaitAll()
61 def wrapped():
62 AwaitAll(wait)
63 fn(*args, **kwargs)
64
65 task = executor.submit(wrapped)
66 tasks.append(task)
67 return task
68
69
70# waits for task (captured in fs as future values) with future.result()
71# so that any exception raised during task can be raised upward.
72def AwaitAll(fs):
73 if fs:
74 for f in fs:
75 f.result()
Jooyung Han504105f2021-10-26 15:54:50 +090076
77
78def ParseArgs(argv):
79 parser = argparse.ArgumentParser(description='Sign the Virt APEX')
Jooyung Han02dceed2021-11-08 17:50:22 +090080 parser.add_argument('--verify', action='store_true',
81 help='Verify the Virt APEX')
Jooyung Han504105f2021-10-26 15:54:50 +090082 parser.add_argument(
83 '-v', '--verbose',
84 action='store_true',
85 help='verbose execution')
86 parser.add_argument(
87 '--avbtool',
88 default='avbtool',
89 help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.')
90 parser.add_argument(
Jooyung Han98498f42022-02-07 15:23:08 +090091 '--signing_args',
92 help='the extra signing arguments passed to avbtool.'
93 )
94 parser.add_argument(
Jooyung Han1c3d2fa2022-02-24 02:35:59 +090095 '--key_override',
96 metavar="filename=key",
97 action='append',
98 help='Overrides a signing key for a file e.g. microdroid_bootloader=mykey (for testing)')
99 parser.add_argument(
Jooyung Han504105f2021-10-26 15:54:50 +0900100 'key',
101 help='path to the private key file.')
102 parser.add_argument(
103 'input_dir',
104 help='the directory having files to be packaged')
Shikha Panwara7605cf2023-01-12 09:29:39 +0000105 parser.add_argument(
106 '--do_not_update_bootconfigs',
107 action='store_true',
108 help='This will NOT update the vbmeta related bootconfigs while signing the apex.\
109 Used for testing only!!')
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900110 args = parser.parse_args(argv)
111 # preprocess --key_override into a map
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900112 args.key_overrides = {}
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900113 if args.key_override:
114 for pair in args.key_override:
115 name, key = pair.split('=')
116 args.key_overrides[name] = key
117 return args
Jooyung Han504105f2021-10-26 15:54:50 +0900118
119
Jooyung Han486609f2022-04-20 11:38:00 +0900120def RunCommand(args, cmd, env=None, expected_return_values=None):
121 expected_return_values = expected_return_values or {0}
Jooyung Han504105f2021-10-26 15:54:50 +0900122 env = env or {}
123 env.update(os.environ.copy())
124
125 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
126 # e.g. sign_apex.py, sign_target_files_apk.py
127 if cmd[0] == 'avbtool':
128 cmd[0] = args.avbtool
129
130 if args.verbose:
131 print('Running: ' + ' '.join(cmd))
132 p = subprocess.Popen(
133 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
134 output, _ = p.communicate()
135
136 if args.verbose or p.returncode not in expected_return_values:
137 print(output.rstrip())
138
139 assert p.returncode in expected_return_values, (
140 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
141 return (output, p.returncode)
142
143
144def ReadBytesSize(value):
145 return int(value.removesuffix(' bytes'))
146
147
Jooyung Han832d11d2021-11-08 12:51:47 +0900148def ExtractAvbPubkey(args, key, output):
149 RunCommand(args, ['avbtool', 'extract_public_key',
150 '--key', key, '--output', output])
151
152
153def AvbInfo(args, image_path):
Jooyung Han504105f2021-10-26 15:54:50 +0900154 """Parses avbtool --info image output
155
156 Args:
157 args: program arguments.
158 image_path: The path to the image.
159 descriptor_name: Descriptor name of interest.
160
161 Returns:
162 A pair of
163 - a dict that contains VBMeta info. None if there's no VBMeta info.
Jooyung Han832d11d2021-11-08 12:51:47 +0900164 - a list of descriptors.
Jooyung Han504105f2021-10-26 15:54:50 +0900165 """
166 if not os.path.exists(image_path):
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900167 raise ValueError(f'Failed to find image: {image_path}')
Jooyung Han504105f2021-10-26 15:54:50 +0900168
169 output, ret_code = RunCommand(
170 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
171 if ret_code == 1:
172 return None, None
173
Jooyung Han832d11d2021-11-08 12:51:47 +0900174 info, descriptors = {}, []
Jooyung Han504105f2021-10-26 15:54:50 +0900175
176 # Read `avbtool info_image` output as "key:value" lines
177 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
178
179 def IterateLine(output):
180 for line in output.split('\n'):
181 line_info = matcher.match(line)
182 if not line_info:
183 continue
184 yield line_info.group(1), line_info.group(2), line_info.group(3)
185
186 gen = IterateLine(output)
Jooyung Han832d11d2021-11-08 12:51:47 +0900187
188 def ReadDescriptors(cur_indent, cur_name, cur_value):
189 descriptor = cur_value if cur_name == 'Prop' else {}
190 descriptors.append((cur_name, descriptor))
191 for indent, key, value in gen:
192 if indent <= cur_indent:
193 # read descriptors recursively to pass the read key as descriptor name
194 ReadDescriptors(indent, key, value)
195 break
196 descriptor[key] = value
197
Jooyung Han504105f2021-10-26 15:54:50 +0900198 # Read VBMeta info
199 for _, key, value in gen:
200 if key == 'Descriptors':
Jooyung Han832d11d2021-11-08 12:51:47 +0900201 ReadDescriptors(*next(gen))
Jooyung Han504105f2021-10-26 15:54:50 +0900202 break
203 info[key] = value
204
Jooyung Han832d11d2021-11-08 12:51:47 +0900205 return info, descriptors
Jooyung Han504105f2021-10-26 15:54:50 +0900206
Jooyung Han832d11d2021-11-08 12:51:47 +0900207
208# Look up a list of (key, value) with a key. Returns the value of the first matching pair.
209def LookUp(pairs, key):
210 for k, v in pairs:
211 if key == k:
212 return v
213 return None
Jooyung Han504105f2021-10-26 15:54:50 +0900214
215
216def AddHashFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900217 if os.path.basename(image_path) in args.key_overrides:
218 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900219 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900220 if info:
Jooyung Han832d11d2021-11-08 12:51:47 +0900221 descriptor = LookUp(descriptors, 'Hash descriptor')
Jooyung Han504105f2021-10-26 15:54:50 +0900222 image_size = ReadBytesSize(info['Image size'])
223 algorithm = info['Algorithm']
224 partition_name = descriptor['Partition Name']
225 partition_size = str(image_size)
226
227 cmd = ['avbtool', 'add_hash_footer',
228 '--key', key,
229 '--algorithm', algorithm,
230 '--partition_name', partition_name,
231 '--partition_size', partition_size,
232 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900233 if args.signing_args:
234 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900235 RunCommand(args, cmd)
236
237
238def AddHashTreeFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900239 if os.path.basename(image_path) in args.key_overrides:
240 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900241 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900242 if info:
Jooyung Han832d11d2021-11-08 12:51:47 +0900243 descriptor = LookUp(descriptors, 'Hashtree descriptor')
Jooyung Han504105f2021-10-26 15:54:50 +0900244 image_size = ReadBytesSize(info['Image size'])
245 algorithm = info['Algorithm']
246 partition_name = descriptor['Partition Name']
Shikha Panwar638119b2023-01-03 06:00:26 +0000247 hash_algorithm = descriptor['Hash Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900248 partition_size = str(image_size)
Jooyung Han504105f2021-10-26 15:54:50 +0900249 cmd = ['avbtool', 'add_hashtree_footer',
250 '--key', key,
251 '--algorithm', algorithm,
252 '--partition_name', partition_name,
253 '--partition_size', partition_size,
254 '--do_not_generate_fec',
Shikha Panwar638119b2023-01-03 06:00:26 +0000255 '--hash_algorithm', hash_algorithm,
Jooyung Han504105f2021-10-26 15:54:50 +0900256 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900257 if args.signing_args:
258 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900259 RunCommand(args, cmd)
260
261
Shikha Panwara7605cf2023-01-12 09:29:39 +0000262def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
263 # Update the bootconfigs in ramdisk
264 def detach_bootconfigs(initrd_bc, initrd, bc):
265 cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
266 RunCommand(args, cmd)
267
268 def attach_bootconfigs(initrd_bc, initrd, bc):
269 cmd = ['initrd_bootconfig', 'attach',
270 initrd, bc, '--output', initrd_bc]
271 RunCommand(args, cmd)
272
273 # Validate that avb version used while signing the apex is the same as used by build server
274 def validate_avb_version(bootconfigs):
275 cmd = ['avbtool', 'version']
276 stdout, _ = RunCommand(args, cmd)
277 avb_version_curr = stdout.split(" ")[1].strip()
278 avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
279
280 avb_version_bc = re.search(
281 r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
282 if avb_version_curr != avb_version_bc:
283 raise Exception(f'AVB version mismatch between current & one & \
284 used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
285
286 def calc_vbmeta_digest():
287 cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
288 vbmeta_img, '--hash_algorithm', 'sha256']
289 stdout, _ = RunCommand(args, cmd)
290 return stdout.strip()
291
292 def calc_vbmeta_size():
293 cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
294 stdout, _ = RunCommand(args, cmd)
295 size = 0
296 for line in stdout.split("\n"):
297 line = line.split(":")
298 if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
299 size += int(line[1].strip()[0:-6])
300 return size
301
302 def update_vbmeta_digest(bootconfigs):
303 # Update androidboot.vbmeta.digest in bootconfigs
304 result = re.search(
305 r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
306 if not result:
307 raise ValueError("Failed to find androidboot.vbmeta.digest")
308
309 return bootconfigs.replace(result.group(),
310 f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
311
312 def update_vbmeta_size(bootconfigs):
313 # Update androidboot.vbmeta.size in bootconfigs
314 result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
315 if not result:
316 raise ValueError("Failed to find androidboot.vbmeta.size")
317 return bootconfigs.replace(result.group(),
318 f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
319
320 with tempfile.TemporaryDirectory() as work_dir:
321 tmp_initrd = os.path.join(work_dir, 'initrd')
322 tmp_bc = os.path.join(work_dir, 'bc')
323
324 for initrd in initrds:
325 detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
326 bc_file = open(tmp_bc, "rt", encoding="utf-8")
327 bc_data = bc_file.read()
328 validate_avb_version(bc_data)
329 bc_data = update_vbmeta_digest(bc_data)
330 bc_data = update_vbmeta_size(bc_data)
331 bc_file.close()
332 bc_file = open(tmp_bc, "wt", encoding="utf-8")
333 bc_file.write(bc_data)
334 bc_file.flush()
335 attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
336
337
Jooyung Han832d11d2021-11-08 12:51:47 +0900338def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900339 if os.path.basename(vbmeta_img) in args.key_overrides:
340 key = args.key_overrides[os.path.basename(vbmeta_img)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900341 info, descriptors = AvbInfo(args, vbmeta_img)
342 if info is None:
343 return
344
Jooyung Han486609f2022-04-20 11:38:00 +0900345 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900346 algorithm = info['Algorithm']
347 rollback_index = info['Rollback Index']
348 rollback_index_location = info['Rollback Index Location']
349
350 cmd = ['avbtool', 'make_vbmeta_image',
351 '--key', key,
352 '--algorithm', algorithm,
353 '--rollback_index', rollback_index,
354 '--rollback_index_location', rollback_index_location,
355 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900356 if images:
357 for img in images:
358 cmd.extend(['--include_descriptors_from_image', img])
359
360 # replace pubkeys of chained_partitions as well
361 for name, descriptor in descriptors:
362 if name == 'Chain Partition descriptor':
363 part_name = descriptor['Partition Name']
364 ril = descriptor['Rollback Index Location']
365 part_key = chained_partitions[part_name]
366 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
367 ExtractAvbPubkey(args, part_key, avbpubkey)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900368 cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900369
Jooyung Han98498f42022-02-07 15:23:08 +0900370 if args.signing_args:
371 cmd.extend(shlex.split(args.signing_args))
372
Jooyung Han504105f2021-10-26 15:54:50 +0900373 RunCommand(args, cmd)
374 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
375 # which matches this or the read will fail.
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900376 with open(vbmeta_img, 'a', encoding='utf8') as f:
Jooyung Handcb0b492022-02-26 09:04:17 +0900377 f.truncate(65536)
Jooyung Han504105f2021-10-26 15:54:50 +0900378
379
Jooyung Han486609f2022-04-20 11:38:00 +0900380def UnpackSuperImg(args, super_img, work_dir):
381 tmp_super_img = os.path.join(work_dir, 'super.img')
382 RunCommand(args, ['simg2img', super_img, tmp_super_img])
383 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
Jooyung Han504105f2021-10-26 15:54:50 +0900384
385
386def MakeSuperImage(args, partitions, output):
Jooyung Han486609f2022-04-20 11:38:00 +0900387 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900388 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
389 '--metadata-size=65536', '--sparse', '--output=' + output]
390
391 for part, img in partitions.items():
392 tmp_img = os.path.join(work_dir, part)
393 RunCommand(args, ['img2simg', img, tmp_img])
394
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900395 image_arg = f'--image={part}={img}'
396 partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default'
Jooyung Han504105f2021-10-26 15:54:50 +0900397 cmd.extend([image_arg, partition_arg])
398
399 RunCommand(args, cmd)
400
401
Jooyung Han486609f2022-04-20 11:38:00 +0900402# dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
403virt_apex_files = {
Shikha Panwara7605cf2023-01-12 09:29:39 +0000404 'kernel': 'etc/fs/microdroid_kernel',
Jooyung Han486609f2022-04-20 11:38:00 +0900405 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000406 'super.img': 'etc/fs/microdroid_super.img',
407 'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
408 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
Jooyung Han486609f2022-04-20 11:38:00 +0900409}
410
411
412def TargetFiles(input_dir):
413 return {k: os.path.join(input_dir, v) for k, v in virt_apex_files.items()}
414
415
Jooyung Han504105f2021-10-26 15:54:50 +0900416def SignVirtApex(args):
417 key = args.key
418 input_dir = args.input_dir
Jooyung Han486609f2022-04-20 11:38:00 +0900419 files = TargetFiles(input_dir)
Jooyung Han504105f2021-10-26 15:54:50 +0900420
Jooyung Han486609f2022-04-20 11:38:00 +0900421 # unpacked files (will be unpacked from super.img below)
422 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
423 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900424
Jooyung Han504105f2021-10-26 15:54:50 +0900425 # re-sign super.img
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900426 # 1. unpack super.img
427 # 2. resign system and vendor
428 # 3. repack super.img out of resigned system and vendor
429 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
430 system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
431 vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
432 partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img}
Shikha Panwara7605cf2023-01-12 09:29:39 +0000433 Async(MakeSuperImage, args, partitions,
434 files['super.img'], wait=[system_a_f, vendor_a_f])
Jooyung Han504105f2021-10-26 15:54:50 +0900435
Shikha Panwar9b870da2022-09-28 12:52:16 +0000436 # re-generate vbmeta from re-signed {system_a, vendor_a}.img
Shikha Panwara7605cf2023-01-12 09:29:39 +0000437 vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
438 images=[system_a_img, vendor_a_img],
439 wait=[system_a_f, vendor_a_f])
Jooyung Han504105f2021-10-26 15:54:50 +0900440
Shikha Panwara7605cf2023-01-12 09:29:39 +0000441 if not args.do_not_update_bootconfigs:
442 Async(UpdateVbmetaBootconfig, args, [files['initrd_normal.img'],
443 files['initrd_debuggable.img']], files['vbmeta.img'],
444 wait=[vbmeta_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900445
Shikha Panwara7605cf2023-01-12 09:29:39 +0000446 # Re-sign kernel
447 # TODO(b/265382249): Kernel's vbmeta should contain hashes of initrd
448 Async(AddHashFooter, args, key, files['kernel'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900449
Jooyung Han504105f2021-10-26 15:54:50 +0900450
Jooyung Han02dceed2021-11-08 17:50:22 +0900451def VerifyVirtApex(args):
Jooyung Han486609f2022-04-20 11:38:00 +0900452 key = args.key
453 input_dir = args.input_dir
454 files = TargetFiles(input_dir)
Jooyung Han02dceed2021-11-08 17:50:22 +0900455
Jooyung Han486609f2022-04-20 11:38:00 +0900456 # unpacked files
457 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
458 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
459 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han02dceed2021-11-08 17:50:22 +0900460
Jooyung Han486609f2022-04-20 11:38:00 +0900461 # Read pubkey digest from the input key
462 with tempfile.NamedTemporaryFile() as pubkey_file:
463 ExtractAvbPubkey(args, key, pubkey_file.name)
464 with open(pubkey_file.name, 'rb') as f:
465 pubkey = f.read()
466 pubkey_digest = hashlib.sha1(pubkey).hexdigest()
Jooyung Han02dceed2021-11-08 17:50:22 +0900467
Jooyung Han486609f2022-04-20 11:38:00 +0900468 def check_avb_pubkey(file):
469 info, _ = AvbInfo(args, file)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900470 assert info is not None, f'no avbinfo: {file}'
471 assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
Jooyung Han486609f2022-04-20 11:38:00 +0900472
473 for f in files.values():
Shikha Panwara7605cf2023-01-12 09:29:39 +0000474 if f in (files['initrd_normal.img'], files['initrd_debuggable.img']):
475 # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
476 continue
477 if f == files['super.img']:
Jooyung Han486609f2022-04-20 11:38:00 +0900478 Async(check_avb_pubkey, system_a_img)
479 Async(check_avb_pubkey, vendor_a_img)
480 else:
481 # Check pubkey for other files using avbtool
482 Async(check_avb_pubkey, f)
Jooyung Han02dceed2021-11-08 17:50:22 +0900483
484
Jooyung Han504105f2021-10-26 15:54:50 +0900485def main(argv):
486 try:
487 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900488 if args.verify:
489 VerifyVirtApex(args)
490 else:
491 SignVirtApex(args)
Jooyung Han486609f2022-04-20 11:38:00 +0900492 # ensure all tasks are completed without exceptions
493 AwaitAll(tasks)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000494 except: # pylint: disable=bare-except
Jooyung Han486609f2022-04-20 11:38:00 +0900495 traceback.print_exc()
Jooyung Han504105f2021-10-26 15:54:50 +0900496 sys.exit(1)
497
498
499if __name__ == '__main__':
500 main(sys.argv[1:])