blob: 3f3600d08216d8dd8321e084bd74ebb43346f999 [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
Shikha Panwarc149d242023-01-20 16:23:04 +0000208# Look up a list of (key, value) with a key. Returns the list of value(s) with the matching key.
209# The order of those values is maintained.
Jooyung Han832d11d2021-11-08 12:51:47 +0900210def LookUp(pairs, key):
Shikha Panwarc149d242023-01-20 16:23:04 +0000211 return [v for (k, v) in pairs if k == key]
Jooyung Han504105f2021-10-26 15:54:50 +0900212
213
Shikha Panwarc149d242023-01-20 16:23:04 +0000214def AddHashFooter(args, key, image_path, partition_name, additional_descriptors=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900215 if os.path.basename(image_path) in args.key_overrides:
216 key = args.key_overrides[os.path.basename(image_path)]
Shikha Panwarc149d242023-01-20 16:23:04 +0000217 info, _ = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900218 if info:
219 image_size = ReadBytesSize(info['Image size'])
220 algorithm = info['Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900221 partition_size = str(image_size)
222
223 cmd = ['avbtool', 'add_hash_footer',
224 '--key', key,
225 '--algorithm', algorithm,
226 '--partition_name', partition_name,
227 '--partition_size', partition_size,
228 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900229 if args.signing_args:
230 cmd.extend(shlex.split(args.signing_args))
Shikha Panwarc149d242023-01-20 16:23:04 +0000231 if additional_descriptors:
232 for image in additional_descriptors:
233 cmd.extend(['--include_descriptors_from_image', image])
Jooyung Han504105f2021-10-26 15:54:50 +0900234 RunCommand(args, cmd)
235
236
237def AddHashTreeFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900238 if os.path.basename(image_path) in args.key_overrides:
239 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900240 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900241 if info:
Shikha Panwarc149d242023-01-20 16:23:04 +0000242 descriptor = LookUp(descriptors, 'Hashtree descriptor')[0]
Jooyung Han504105f2021-10-26 15:54:50 +0900243 image_size = ReadBytesSize(info['Image size'])
244 algorithm = info['Algorithm']
245 partition_name = descriptor['Partition Name']
Shikha Panwar638119b2023-01-03 06:00:26 +0000246 hash_algorithm = descriptor['Hash Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900247 partition_size = str(image_size)
Jooyung Han504105f2021-10-26 15:54:50 +0900248 cmd = ['avbtool', 'add_hashtree_footer',
249 '--key', key,
250 '--algorithm', algorithm,
251 '--partition_name', partition_name,
252 '--partition_size', partition_size,
253 '--do_not_generate_fec',
Shikha Panwar638119b2023-01-03 06:00:26 +0000254 '--hash_algorithm', hash_algorithm,
Jooyung Han504105f2021-10-26 15:54:50 +0900255 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900256 if args.signing_args:
257 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900258 RunCommand(args, cmd)
259
260
Shikha Panwara7605cf2023-01-12 09:29:39 +0000261def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
262 # Update the bootconfigs in ramdisk
263 def detach_bootconfigs(initrd_bc, initrd, bc):
264 cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
265 RunCommand(args, cmd)
266
267 def attach_bootconfigs(initrd_bc, initrd, bc):
268 cmd = ['initrd_bootconfig', 'attach',
269 initrd, bc, '--output', initrd_bc]
270 RunCommand(args, cmd)
271
272 # Validate that avb version used while signing the apex is the same as used by build server
273 def validate_avb_version(bootconfigs):
274 cmd = ['avbtool', 'version']
275 stdout, _ = RunCommand(args, cmd)
276 avb_version_curr = stdout.split(" ")[1].strip()
277 avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
278
279 avb_version_bc = re.search(
280 r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
281 if avb_version_curr != avb_version_bc:
282 raise Exception(f'AVB version mismatch between current & one & \
283 used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
284
285 def calc_vbmeta_digest():
286 cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
287 vbmeta_img, '--hash_algorithm', 'sha256']
288 stdout, _ = RunCommand(args, cmd)
289 return stdout.strip()
290
291 def calc_vbmeta_size():
292 cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
293 stdout, _ = RunCommand(args, cmd)
294 size = 0
295 for line in stdout.split("\n"):
296 line = line.split(":")
297 if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
298 size += int(line[1].strip()[0:-6])
299 return size
300
301 def update_vbmeta_digest(bootconfigs):
302 # Update androidboot.vbmeta.digest in bootconfigs
303 result = re.search(
304 r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
305 if not result:
306 raise ValueError("Failed to find androidboot.vbmeta.digest")
307
308 return bootconfigs.replace(result.group(),
309 f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
310
311 def update_vbmeta_size(bootconfigs):
312 # Update androidboot.vbmeta.size in bootconfigs
313 result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
314 if not result:
315 raise ValueError("Failed to find androidboot.vbmeta.size")
316 return bootconfigs.replace(result.group(),
317 f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
318
319 with tempfile.TemporaryDirectory() as work_dir:
320 tmp_initrd = os.path.join(work_dir, 'initrd')
321 tmp_bc = os.path.join(work_dir, 'bc')
322
323 for initrd in initrds:
324 detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
325 bc_file = open(tmp_bc, "rt", encoding="utf-8")
326 bc_data = bc_file.read()
327 validate_avb_version(bc_data)
328 bc_data = update_vbmeta_digest(bc_data)
329 bc_data = update_vbmeta_size(bc_data)
330 bc_file.close()
331 bc_file = open(tmp_bc, "wt", encoding="utf-8")
332 bc_file.write(bc_data)
333 bc_file.flush()
334 attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
335
336
Jooyung Han832d11d2021-11-08 12:51:47 +0900337def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900338 if os.path.basename(vbmeta_img) in args.key_overrides:
339 key = args.key_overrides[os.path.basename(vbmeta_img)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900340 info, descriptors = AvbInfo(args, vbmeta_img)
341 if info is None:
342 return
343
Jooyung Han486609f2022-04-20 11:38:00 +0900344 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900345 algorithm = info['Algorithm']
346 rollback_index = info['Rollback Index']
347 rollback_index_location = info['Rollback Index Location']
348
349 cmd = ['avbtool', 'make_vbmeta_image',
350 '--key', key,
351 '--algorithm', algorithm,
352 '--rollback_index', rollback_index,
353 '--rollback_index_location', rollback_index_location,
354 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900355 if images:
356 for img in images:
357 cmd.extend(['--include_descriptors_from_image', img])
358
359 # replace pubkeys of chained_partitions as well
360 for name, descriptor in descriptors:
361 if name == 'Chain Partition descriptor':
362 part_name = descriptor['Partition Name']
363 ril = descriptor['Rollback Index Location']
364 part_key = chained_partitions[part_name]
365 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
366 ExtractAvbPubkey(args, part_key, avbpubkey)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900367 cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900368
Jooyung Han98498f42022-02-07 15:23:08 +0900369 if args.signing_args:
370 cmd.extend(shlex.split(args.signing_args))
371
Jooyung Han504105f2021-10-26 15:54:50 +0900372 RunCommand(args, cmd)
373 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
374 # which matches this or the read will fail.
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900375 with open(vbmeta_img, 'a', encoding='utf8') as f:
Jooyung Handcb0b492022-02-26 09:04:17 +0900376 f.truncate(65536)
Jooyung Han504105f2021-10-26 15:54:50 +0900377
378
Jooyung Han486609f2022-04-20 11:38:00 +0900379def UnpackSuperImg(args, super_img, work_dir):
380 tmp_super_img = os.path.join(work_dir, 'super.img')
381 RunCommand(args, ['simg2img', super_img, tmp_super_img])
382 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
Jooyung Han504105f2021-10-26 15:54:50 +0900383
384
385def MakeSuperImage(args, partitions, output):
Jooyung Han486609f2022-04-20 11:38:00 +0900386 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900387 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
388 '--metadata-size=65536', '--sparse', '--output=' + output]
389
390 for part, img in partitions.items():
391 tmp_img = os.path.join(work_dir, part)
392 RunCommand(args, ['img2simg', img, tmp_img])
393
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900394 image_arg = f'--image={part}={img}'
395 partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default'
Jooyung Han504105f2021-10-26 15:54:50 +0900396 cmd.extend([image_arg, partition_arg])
397
398 RunCommand(args, cmd)
399
400
Shikha Panwarc149d242023-01-20 16:23:04 +0000401def GenVbmetaImage(args, image, output, partition_name):
402 cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size',
403 '--do_not_append_vbmeta_image',
404 '--partition_name', partition_name,
405 '--image', image,
406 '--output_vbmeta_image', output]
407 RunCommand(args, cmd)
408
Jooyung Han486609f2022-04-20 11:38:00 +0900409# dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
410virt_apex_files = {
Shikha Panwara7605cf2023-01-12 09:29:39 +0000411 'kernel': 'etc/fs/microdroid_kernel',
Jooyung Han486609f2022-04-20 11:38:00 +0900412 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000413 'super.img': 'etc/fs/microdroid_super.img',
414 'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
415 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
Jooyung Han486609f2022-04-20 11:38:00 +0900416}
417
418
419def TargetFiles(input_dir):
420 return {k: os.path.join(input_dir, v) for k, v in virt_apex_files.items()}
421
422
Jooyung Han504105f2021-10-26 15:54:50 +0900423def SignVirtApex(args):
424 key = args.key
425 input_dir = args.input_dir
Jooyung Han486609f2022-04-20 11:38:00 +0900426 files = TargetFiles(input_dir)
Jooyung Han504105f2021-10-26 15:54:50 +0900427
Jooyung Han486609f2022-04-20 11:38:00 +0900428 # unpacked files (will be unpacked from super.img below)
429 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
430 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900431
Jooyung Han504105f2021-10-26 15:54:50 +0900432 # re-sign super.img
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900433 # 1. unpack super.img
434 # 2. resign system and vendor
435 # 3. repack super.img out of resigned system and vendor
436 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
437 system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
438 vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
439 partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img}
Shikha Panwara7605cf2023-01-12 09:29:39 +0000440 Async(MakeSuperImage, args, partitions,
441 files['super.img'], wait=[system_a_f, vendor_a_f])
Jooyung Han504105f2021-10-26 15:54:50 +0900442
Shikha Panwar9b870da2022-09-28 12:52:16 +0000443 # re-generate vbmeta from re-signed {system_a, vendor_a}.img
Shikha Panwara7605cf2023-01-12 09:29:39 +0000444 vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
445 images=[system_a_img, vendor_a_img],
446 wait=[system_a_f, vendor_a_f])
Jooyung Han504105f2021-10-26 15:54:50 +0900447
Shikha Panwarc149d242023-01-20 16:23:04 +0000448 vbmeta_bc_f = None
Shikha Panwara7605cf2023-01-12 09:29:39 +0000449 if not args.do_not_update_bootconfigs:
Shikha Panwarc149d242023-01-20 16:23:04 +0000450 vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args,
451 [files['initrd_normal.img'],
452 files['initrd_debuggable.img']], files['vbmeta.img'],
453 wait=[vbmeta_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900454
Shikha Panwarc149d242023-01-20 16:23:04 +0000455 # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s)
456 initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
457 initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
458 initrd_n_f = Async(GenVbmetaImage, args, files['initrd_normal.img'],
459 initrd_normal_hashdesc, "initrd_normal",
460 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
461 initrd_d_f = Async(GenVbmetaImage, args, files['initrd_debuggable.img'],
462 initrd_debug_hashdesc, "initrd_debug",
463 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
464 Async(AddHashFooter, args, key, files['kernel'], partition_name="boot",
465 additional_descriptors=[
466 initrd_normal_hashdesc, initrd_debug_hashdesc],
467 wait=[initrd_n_f, initrd_d_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900468
Jooyung Han504105f2021-10-26 15:54:50 +0900469
Jooyung Han02dceed2021-11-08 17:50:22 +0900470def VerifyVirtApex(args):
Jooyung Han486609f2022-04-20 11:38:00 +0900471 key = args.key
472 input_dir = args.input_dir
473 files = TargetFiles(input_dir)
Jooyung Han02dceed2021-11-08 17:50:22 +0900474
Jooyung Han486609f2022-04-20 11:38:00 +0900475 # unpacked files
476 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
477 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
478 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han02dceed2021-11-08 17:50:22 +0900479
Jooyung Han486609f2022-04-20 11:38:00 +0900480 # Read pubkey digest from the input key
481 with tempfile.NamedTemporaryFile() as pubkey_file:
482 ExtractAvbPubkey(args, key, pubkey_file.name)
483 with open(pubkey_file.name, 'rb') as f:
484 pubkey = f.read()
485 pubkey_digest = hashlib.sha1(pubkey).hexdigest()
Jooyung Han02dceed2021-11-08 17:50:22 +0900486
Jooyung Han486609f2022-04-20 11:38:00 +0900487 def check_avb_pubkey(file):
488 info, _ = AvbInfo(args, file)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900489 assert info is not None, f'no avbinfo: {file}'
490 assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
Jooyung Han486609f2022-04-20 11:38:00 +0900491
492 for f in files.values():
Shikha Panwara7605cf2023-01-12 09:29:39 +0000493 if f in (files['initrd_normal.img'], files['initrd_debuggable.img']):
494 # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
495 continue
496 if f == files['super.img']:
Jooyung Han486609f2022-04-20 11:38:00 +0900497 Async(check_avb_pubkey, system_a_img)
498 Async(check_avb_pubkey, vendor_a_img)
499 else:
500 # Check pubkey for other files using avbtool
501 Async(check_avb_pubkey, f)
Jooyung Han02dceed2021-11-08 17:50:22 +0900502
503
Jooyung Han504105f2021-10-26 15:54:50 +0900504def main(argv):
505 try:
506 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900507 if args.verify:
508 VerifyVirtApex(args)
509 else:
510 SignVirtApex(args)
Jooyung Han486609f2022-04-20 11:38:00 +0900511 # ensure all tasks are completed without exceptions
512 AwaitAll(tasks)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000513 except: # pylint: disable=bare-except
Jooyung Han486609f2022-04-20 11:38:00 +0900514 traceback.print_exc()
Jooyung Han504105f2021-10-26 15:54:50 +0900515 sys.exit(1)
516
517
518if __name__ == '__main__':
519 main(sys.argv[1:])