blob: 739363643b098f24ffbc795999ea45c8aa01c0c8 [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
Nikita Ioffee1112032023-11-13 15:09:39 +000030import builtins
Jooyung Han02dceed2021-11-08 17:50:22 +090031import hashlib
Jooyung Han504105f2021-10-26 15:54:50 +090032import os
33import re
Jooyung Han98498f42022-02-07 15:23:08 +090034import shlex
Jooyung Han504105f2021-10-26 15:54:50 +090035import subprocess
36import sys
37import tempfile
Jooyung Han486609f2022-04-20 11:38:00 +090038import traceback
39from concurrent import futures
40
41# pylint: disable=line-too-long,consider-using-with
42
43# Use executor to parallelize the invocation of external tools
44# If a task depends on another, pass the future object of the previous task as wait list.
45# Every future object created by a task should be consumed with AwaitAll()
46# so that exceptions are propagated .
47executor = futures.ThreadPoolExecutor()
48
49# Temporary directory for unpacked super.img.
50# We could put its creation/deletion into the task graph as well, but
51# having it as a global setup is much simpler.
52unpack_dir = tempfile.TemporaryDirectory()
53
54# tasks created with Async() are kept in a list so that they are awaited
55# before exit.
56tasks = []
57
58# create an async task and return a future value of it.
59def Async(fn, *args, wait=None, **kwargs):
60
61 # wrap a function with AwaitAll()
62 def wrapped():
63 AwaitAll(wait)
64 fn(*args, **kwargs)
65
66 task = executor.submit(wrapped)
67 tasks.append(task)
68 return task
69
70
71# waits for task (captured in fs as future values) with future.result()
72# so that any exception raised during task can be raised upward.
73def AwaitAll(fs):
74 if fs:
75 for f in fs:
76 f.result()
Jooyung Han504105f2021-10-26 15:54:50 +090077
78
79def ParseArgs(argv):
80 parser = argparse.ArgumentParser(description='Sign the Virt APEX')
Jooyung Han02dceed2021-11-08 17:50:22 +090081 parser.add_argument('--verify', action='store_true',
82 help='Verify the Virt APEX')
Jooyung Han504105f2021-10-26 15:54:50 +090083 parser.add_argument(
84 '-v', '--verbose',
85 action='store_true',
86 help='verbose execution')
87 parser.add_argument(
88 '--avbtool',
89 default='avbtool',
90 help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.')
91 parser.add_argument(
Jooyung Han98498f42022-02-07 15:23:08 +090092 '--signing_args',
93 help='the extra signing arguments passed to avbtool.'
94 )
95 parser.add_argument(
Jooyung Han1c3d2fa2022-02-24 02:35:59 +090096 '--key_override',
97 metavar="filename=key",
98 action='append',
99 help='Overrides a signing key for a file e.g. microdroid_bootloader=mykey (for testing)')
100 parser.add_argument(
Jooyung Han504105f2021-10-26 15:54:50 +0900101 'key',
102 help='path to the private key file.')
103 parser.add_argument(
104 'input_dir',
105 help='the directory having files to be packaged')
Shikha Panwara7605cf2023-01-12 09:29:39 +0000106 parser.add_argument(
107 '--do_not_update_bootconfigs',
108 action='store_true',
109 help='This will NOT update the vbmeta related bootconfigs while signing the apex.\
110 Used for testing only!!')
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900111 args = parser.parse_args(argv)
112 # preprocess --key_override into a map
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900113 args.key_overrides = {}
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900114 if args.key_override:
115 for pair in args.key_override:
116 name, key = pair.split('=')
117 args.key_overrides[name] = key
118 return args
Jooyung Han504105f2021-10-26 15:54:50 +0900119
120
Jooyung Han486609f2022-04-20 11:38:00 +0900121def RunCommand(args, cmd, env=None, expected_return_values=None):
122 expected_return_values = expected_return_values or {0}
Jooyung Han504105f2021-10-26 15:54:50 +0900123 env = env or {}
124 env.update(os.environ.copy())
125
126 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
127 # e.g. sign_apex.py, sign_target_files_apk.py
128 if cmd[0] == 'avbtool':
129 cmd[0] = args.avbtool
130
131 if args.verbose:
132 print('Running: ' + ' '.join(cmd))
133 p = subprocess.Popen(
134 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
135 output, _ = p.communicate()
136
137 if args.verbose or p.returncode not in expected_return_values:
138 print(output.rstrip())
139
140 assert p.returncode in expected_return_values, (
141 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
142 return (output, p.returncode)
143
144
145def ReadBytesSize(value):
146 return int(value.removesuffix(' bytes'))
147
148
Jooyung Han832d11d2021-11-08 12:51:47 +0900149def ExtractAvbPubkey(args, key, output):
150 RunCommand(args, ['avbtool', 'extract_public_key',
151 '--key', key, '--output', output])
152
153
154def AvbInfo(args, image_path):
Jooyung Han504105f2021-10-26 15:54:50 +0900155 """Parses avbtool --info image output
156
157 Args:
158 args: program arguments.
159 image_path: The path to the image.
160 descriptor_name: Descriptor name of interest.
161
162 Returns:
163 A pair of
164 - a dict that contains VBMeta info. None if there's no VBMeta info.
Jooyung Han832d11d2021-11-08 12:51:47 +0900165 - a list of descriptors.
Jooyung Han504105f2021-10-26 15:54:50 +0900166 """
167 if not os.path.exists(image_path):
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900168 raise ValueError(f'Failed to find image: {image_path}')
Jooyung Han504105f2021-10-26 15:54:50 +0900169
170 output, ret_code = RunCommand(
171 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
172 if ret_code == 1:
173 return None, None
174
Jooyung Han832d11d2021-11-08 12:51:47 +0900175 info, descriptors = {}, []
Jooyung Han504105f2021-10-26 15:54:50 +0900176
177 # Read `avbtool info_image` output as "key:value" lines
178 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
179
180 def IterateLine(output):
181 for line in output.split('\n'):
182 line_info = matcher.match(line)
183 if not line_info:
184 continue
185 yield line_info.group(1), line_info.group(2), line_info.group(3)
186
187 gen = IterateLine(output)
Jooyung Han832d11d2021-11-08 12:51:47 +0900188
189 def ReadDescriptors(cur_indent, cur_name, cur_value):
190 descriptor = cur_value if cur_name == 'Prop' else {}
191 descriptors.append((cur_name, descriptor))
192 for indent, key, value in gen:
193 if indent <= cur_indent:
194 # read descriptors recursively to pass the read key as descriptor name
195 ReadDescriptors(indent, key, value)
196 break
197 descriptor[key] = value
198
Jooyung Han504105f2021-10-26 15:54:50 +0900199 # Read VBMeta info
200 for _, key, value in gen:
201 if key == 'Descriptors':
Jooyung Han832d11d2021-11-08 12:51:47 +0900202 ReadDescriptors(*next(gen))
Jooyung Han504105f2021-10-26 15:54:50 +0900203 break
204 info[key] = value
205
Jooyung Han832d11d2021-11-08 12:51:47 +0900206 return info, descriptors
Jooyung Han504105f2021-10-26 15:54:50 +0900207
Jooyung Han832d11d2021-11-08 12:51:47 +0900208
Shikha Panwarc149d242023-01-20 16:23:04 +0000209# Look up a list of (key, value) with a key. Returns the list of value(s) with the matching key.
210# The order of those values is maintained.
Jooyung Han832d11d2021-11-08 12:51:47 +0900211def LookUp(pairs, key):
Shikha Panwarc149d242023-01-20 16:23:04 +0000212 return [v for (k, v) in pairs if k == key]
Jooyung Han504105f2021-10-26 15:54:50 +0900213
214
Shikha Panwarc149d242023-01-20 16:23:04 +0000215def AddHashFooter(args, key, image_path, partition_name, additional_descriptors=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900216 if os.path.basename(image_path) in args.key_overrides:
217 key = args.key_overrides[os.path.basename(image_path)]
Shikha Panwarc149d242023-01-20 16:23:04 +0000218 info, _ = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900219 if info:
220 image_size = ReadBytesSize(info['Image size'])
221 algorithm = info['Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900222 partition_size = str(image_size)
223
224 cmd = ['avbtool', 'add_hash_footer',
225 '--key', key,
226 '--algorithm', algorithm,
227 '--partition_name', partition_name,
228 '--partition_size', partition_size,
229 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900230 if args.signing_args:
231 cmd.extend(shlex.split(args.signing_args))
Shikha Panwarc149d242023-01-20 16:23:04 +0000232 if additional_descriptors:
233 for image in additional_descriptors:
234 cmd.extend(['--include_descriptors_from_image', image])
Shikha Panwar2a788662023-09-11 14:04:24 +0000235
236 if 'Rollback Index' in info:
237 cmd.extend(['--rollback_index', info['Rollback Index']])
Jooyung Han504105f2021-10-26 15:54:50 +0900238 RunCommand(args, cmd)
239
240
241def AddHashTreeFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900242 if os.path.basename(image_path) in args.key_overrides:
243 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900244 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900245 if info:
Shikha Panwarc149d242023-01-20 16:23:04 +0000246 descriptor = LookUp(descriptors, 'Hashtree descriptor')[0]
Jooyung Han504105f2021-10-26 15:54:50 +0900247 image_size = ReadBytesSize(info['Image size'])
248 algorithm = info['Algorithm']
249 partition_name = descriptor['Partition Name']
Shikha Panwar638119b2023-01-03 06:00:26 +0000250 hash_algorithm = descriptor['Hash Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900251 partition_size = str(image_size)
Jooyung Han504105f2021-10-26 15:54:50 +0900252 cmd = ['avbtool', 'add_hashtree_footer',
253 '--key', key,
254 '--algorithm', algorithm,
255 '--partition_name', partition_name,
256 '--partition_size', partition_size,
257 '--do_not_generate_fec',
Shikha Panwar638119b2023-01-03 06:00:26 +0000258 '--hash_algorithm', hash_algorithm,
Jooyung Han504105f2021-10-26 15:54:50 +0900259 '--image', image_path]
Jooyung Han98498f42022-02-07 15:23:08 +0900260 if args.signing_args:
261 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900262 RunCommand(args, cmd)
263
264
Shikha Panwara7605cf2023-01-12 09:29:39 +0000265def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
266 # Update the bootconfigs in ramdisk
267 def detach_bootconfigs(initrd_bc, initrd, bc):
268 cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
269 RunCommand(args, cmd)
270
271 def attach_bootconfigs(initrd_bc, initrd, bc):
272 cmd = ['initrd_bootconfig', 'attach',
273 initrd, bc, '--output', initrd_bc]
274 RunCommand(args, cmd)
275
276 # Validate that avb version used while signing the apex is the same as used by build server
277 def validate_avb_version(bootconfigs):
278 cmd = ['avbtool', 'version']
279 stdout, _ = RunCommand(args, cmd)
280 avb_version_curr = stdout.split(" ")[1].strip()
281 avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
282
283 avb_version_bc = re.search(
284 r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
285 if avb_version_curr != avb_version_bc:
Nikita Ioffee1112032023-11-13 15:09:39 +0000286 raise builtins.Exception(f'AVB version mismatch between current & one & \
Shikha Panwara7605cf2023-01-12 09:29:39 +0000287 used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
288
289 def calc_vbmeta_digest():
290 cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
291 vbmeta_img, '--hash_algorithm', 'sha256']
292 stdout, _ = RunCommand(args, cmd)
293 return stdout.strip()
294
295 def calc_vbmeta_size():
296 cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
297 stdout, _ = RunCommand(args, cmd)
298 size = 0
299 for line in stdout.split("\n"):
300 line = line.split(":")
301 if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
302 size += int(line[1].strip()[0:-6])
303 return size
304
305 def update_vbmeta_digest(bootconfigs):
306 # Update androidboot.vbmeta.digest in bootconfigs
307 result = re.search(
308 r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
309 if not result:
310 raise ValueError("Failed to find androidboot.vbmeta.digest")
311
312 return bootconfigs.replace(result.group(),
313 f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
314
315 def update_vbmeta_size(bootconfigs):
316 # Update androidboot.vbmeta.size in bootconfigs
317 result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
318 if not result:
319 raise ValueError("Failed to find androidboot.vbmeta.size")
320 return bootconfigs.replace(result.group(),
321 f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
322
323 with tempfile.TemporaryDirectory() as work_dir:
324 tmp_initrd = os.path.join(work_dir, 'initrd')
325 tmp_bc = os.path.join(work_dir, 'bc')
326
327 for initrd in initrds:
328 detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
329 bc_file = open(tmp_bc, "rt", encoding="utf-8")
330 bc_data = bc_file.read()
331 validate_avb_version(bc_data)
332 bc_data = update_vbmeta_digest(bc_data)
333 bc_data = update_vbmeta_size(bc_data)
334 bc_file.close()
335 bc_file = open(tmp_bc, "wt", encoding="utf-8")
336 bc_file.write(bc_data)
337 bc_file.flush()
338 attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
339
340
Jooyung Han832d11d2021-11-08 12:51:47 +0900341def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900342 if os.path.basename(vbmeta_img) in args.key_overrides:
343 key = args.key_overrides[os.path.basename(vbmeta_img)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900344 info, descriptors = AvbInfo(args, vbmeta_img)
345 if info is None:
346 return
347
Jooyung Han486609f2022-04-20 11:38:00 +0900348 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900349 algorithm = info['Algorithm']
350 rollback_index = info['Rollback Index']
351 rollback_index_location = info['Rollback Index Location']
352
353 cmd = ['avbtool', 'make_vbmeta_image',
354 '--key', key,
355 '--algorithm', algorithm,
356 '--rollback_index', rollback_index,
357 '--rollback_index_location', rollback_index_location,
358 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900359 if images:
360 for img in images:
361 cmd.extend(['--include_descriptors_from_image', img])
362
363 # replace pubkeys of chained_partitions as well
364 for name, descriptor in descriptors:
365 if name == 'Chain Partition descriptor':
366 part_name = descriptor['Partition Name']
367 ril = descriptor['Rollback Index Location']
368 part_key = chained_partitions[part_name]
369 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
370 ExtractAvbPubkey(args, part_key, avbpubkey)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900371 cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900372
Jooyung Han98498f42022-02-07 15:23:08 +0900373 if args.signing_args:
374 cmd.extend(shlex.split(args.signing_args))
375
Jooyung Han504105f2021-10-26 15:54:50 +0900376 RunCommand(args, cmd)
377 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
378 # which matches this or the read will fail.
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900379 with open(vbmeta_img, 'a', encoding='utf8') as f:
Jooyung Handcb0b492022-02-26 09:04:17 +0900380 f.truncate(65536)
Jooyung Han504105f2021-10-26 15:54:50 +0900381
382
Jooyung Han486609f2022-04-20 11:38:00 +0900383def UnpackSuperImg(args, super_img, work_dir):
384 tmp_super_img = os.path.join(work_dir, 'super.img')
385 RunCommand(args, ['simg2img', super_img, tmp_super_img])
386 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
Jooyung Han504105f2021-10-26 15:54:50 +0900387
388
389def MakeSuperImage(args, partitions, output):
Jooyung Han486609f2022-04-20 11:38:00 +0900390 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900391 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
392 '--metadata-size=65536', '--sparse', '--output=' + output]
393
394 for part, img in partitions.items():
395 tmp_img = os.path.join(work_dir, part)
396 RunCommand(args, ['img2simg', img, tmp_img])
397
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900398 image_arg = f'--image={part}={img}'
399 partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default'
Jooyung Han504105f2021-10-26 15:54:50 +0900400 cmd.extend([image_arg, partition_arg])
401
402 RunCommand(args, cmd)
403
404
Shikha Panwarc149d242023-01-20 16:23:04 +0000405def GenVbmetaImage(args, image, output, partition_name):
406 cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size',
407 '--do_not_append_vbmeta_image',
408 '--partition_name', partition_name,
409 '--image', image,
410 '--output_vbmeta_image', output]
411 RunCommand(args, cmd)
412
Jooyung Han486609f2022-04-20 11:38:00 +0900413# dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
414virt_apex_files = {
Shikha Panwara7605cf2023-01-12 09:29:39 +0000415 'kernel': 'etc/fs/microdroid_kernel',
Inseob Kim77c7f712023-11-06 17:01:02 +0900416 'gki_kernel': 'etc/fs/microdroid_gki_kernel',
Jooyung Han486609f2022-04-20 11:38:00 +0900417 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000418 'super.img': 'etc/fs/microdroid_super.img',
419 'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
Inseob Kim77c7f712023-11-06 17:01:02 +0900420 'gki_initrd_normal.img': 'etc/microdroid_gki_initrd_normal.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000421 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
Inseob Kim77c7f712023-11-06 17:01:02 +0900422 'gki_initrd_debuggable.img': 'etc/microdroid_gki_initrd_debuggable.img',
Jooyung Han486609f2022-04-20 11:38:00 +0900423}
424
425
426def TargetFiles(input_dir):
427 return {k: os.path.join(input_dir, v) for k, v in virt_apex_files.items()}
428
429
Jooyung Han504105f2021-10-26 15:54:50 +0900430def SignVirtApex(args):
431 key = args.key
432 input_dir = args.input_dir
Jooyung Han486609f2022-04-20 11:38:00 +0900433 files = TargetFiles(input_dir)
Jooyung Han504105f2021-10-26 15:54:50 +0900434
Jooyung Han486609f2022-04-20 11:38:00 +0900435 # unpacked files (will be unpacked from super.img below)
436 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Nikita Ioffee1112032023-11-13 15:09:39 +0000437 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900438
Jooyung Han504105f2021-10-26 15:54:50 +0900439 # re-sign super.img
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900440 # 1. unpack super.img
Nikita Ioffee1112032023-11-13 15:09:39 +0000441 # 2. resign system and vendor (if exists)
442 # 3. repack super.img out of resigned system and vendor (if exists)
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900443 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
444 system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000445 partitions = {"system_a": system_a_img}
Nikita Ioffee1112032023-11-13 15:09:39 +0000446 images = [system_a_img]
447 images_f = [system_a_f]
448
449 # if vendor_a.img exists, resign it
450 if os.path.exists(vendor_a_img):
451 partitions.update({'vendor_a': vendor_a_img})
452 images.append(vendor_a_img)
453 vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
454 images_f.append(vendor_a_f)
455
Shikha Panwara7605cf2023-01-12 09:29:39 +0000456 Async(MakeSuperImage, args, partitions,
Nikita Ioffee1112032023-11-13 15:09:39 +0000457 files['super.img'], wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900458
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000459 # re-generate vbmeta from re-signed system_a.img
Shikha Panwara7605cf2023-01-12 09:29:39 +0000460 vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
Nikita Ioffee1112032023-11-13 15:09:39 +0000461 images=images,
462 wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900463
Inseob Kim77c7f712023-11-06 17:01:02 +0900464 has_gki_kernel = os.path.isfile(files['gki_kernel'])
465
Shikha Panwarc149d242023-01-20 16:23:04 +0000466 vbmeta_bc_f = None
Shikha Panwara7605cf2023-01-12 09:29:39 +0000467 if not args.do_not_update_bootconfigs:
Inseob Kim77c7f712023-11-06 17:01:02 +0900468 initrd_files = [files['initrd_normal.img'], files['initrd_debuggable.img']]
469 if has_gki_kernel:
470 initrd_files += [files['gki_initrd_normal.img'], files['gki_initrd_debuggable.img']]
471 vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args, initrd_files,
472 files['vbmeta.img'],
Shikha Panwarc149d242023-01-20 16:23:04 +0000473 wait=[vbmeta_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900474
Shikha Panwarc149d242023-01-20 16:23:04 +0000475 # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s)
Inseob Kim77c7f712023-11-06 17:01:02 +0900476 def resign_kernel(kernel, initrd_normal, initrd_debug):
477 kernel_file = files[kernel]
478 initrd_normal_file = files[initrd_normal]
479 initrd_debug_file = files[initrd_debug]
480
481 initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
482 initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
483 initrd_n_f = Async(GenVbmetaImage, args, initrd_normal_file,
484 initrd_normal_hashdesc, "initrd_normal",
485 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
486 initrd_d_f = Async(GenVbmetaImage, args, initrd_debug_file,
487 initrd_debug_hashdesc, "initrd_debug",
488 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
489 Async(AddHashFooter, args, key, kernel_file, partition_name="boot",
490 additional_descriptors=[
491 initrd_normal_hashdesc, initrd_debug_hashdesc],
492 wait=[initrd_n_f, initrd_d_f])
493
494 resign_kernel('kernel', 'initrd_normal.img', 'initrd_debuggable.img')
495
496 if has_gki_kernel:
497 resign_kernel('gki_kernel', 'gki_initrd_normal.img', 'gki_initrd_debuggable.img')
Jooyung Han832d11d2021-11-08 12:51:47 +0900498
Jooyung Han504105f2021-10-26 15:54:50 +0900499
Jooyung Han02dceed2021-11-08 17:50:22 +0900500def VerifyVirtApex(args):
Jooyung Han486609f2022-04-20 11:38:00 +0900501 key = args.key
502 input_dir = args.input_dir
503 files = TargetFiles(input_dir)
Jooyung Han02dceed2021-11-08 17:50:22 +0900504
Jooyung Han486609f2022-04-20 11:38:00 +0900505 # unpacked files
506 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
507 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Jooyung Han02dceed2021-11-08 17:50:22 +0900508
Jooyung Han486609f2022-04-20 11:38:00 +0900509 # Read pubkey digest from the input key
510 with tempfile.NamedTemporaryFile() as pubkey_file:
511 ExtractAvbPubkey(args, key, pubkey_file.name)
512 with open(pubkey_file.name, 'rb') as f:
513 pubkey = f.read()
514 pubkey_digest = hashlib.sha1(pubkey).hexdigest()
Jooyung Han02dceed2021-11-08 17:50:22 +0900515
Jooyung Han486609f2022-04-20 11:38:00 +0900516 def check_avb_pubkey(file):
517 info, _ = AvbInfo(args, file)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900518 assert info is not None, f'no avbinfo: {file}'
519 assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
Jooyung Han486609f2022-04-20 11:38:00 +0900520
521 for f in files.values():
Inseob Kim77c7f712023-11-06 17:01:02 +0900522 if f in (files['initrd_normal.img'], files['initrd_debuggable.img'],
523 files['gki_initrd_normal.img'], files['gki_initrd_debuggable.img']):
Shikha Panwara7605cf2023-01-12 09:29:39 +0000524 # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
525 continue
526 if f == files['super.img']:
Jooyung Han486609f2022-04-20 11:38:00 +0900527 Async(check_avb_pubkey, system_a_img)
Jooyung Han486609f2022-04-20 11:38:00 +0900528 else:
529 # Check pubkey for other files using avbtool
530 Async(check_avb_pubkey, f)
Jooyung Han02dceed2021-11-08 17:50:22 +0900531
532
Jooyung Han504105f2021-10-26 15:54:50 +0900533def main(argv):
534 try:
535 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900536 if args.verify:
537 VerifyVirtApex(args)
538 else:
539 SignVirtApex(args)
Jooyung Han486609f2022-04-20 11:38:00 +0900540 # ensure all tasks are completed without exceptions
541 AwaitAll(tasks)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000542 except: # pylint: disable=bare-except
Jooyung Han486609f2022-04-20 11:38:00 +0900543 traceback.print_exc()
Jooyung Han504105f2021-10-26 15:54:50 +0900544 sys.exit(1)
545
546
547if __name__ == '__main__':
548 main(sys.argv[1:])