blob: ffc16978c590c5bf9a19c1cd6d81d9462e53cc2e [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!!')
Nikita Ioffe314d7e32023-12-18 17:38:18 +0000111 parser.add_argument('--do_not_validate_avb_version', action='store_true', help='Do not validate the avb_version when updating vbmeta bootconfig. Only use in tests!')
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900112 args = parser.parse_args(argv)
113 # preprocess --key_override into a map
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900114 args.key_overrides = {}
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900115 if args.key_override:
116 for pair in args.key_override:
117 name, key = pair.split('=')
118 args.key_overrides[name] = key
119 return args
Jooyung Han504105f2021-10-26 15:54:50 +0900120
121
Jooyung Han486609f2022-04-20 11:38:00 +0900122def RunCommand(args, cmd, env=None, expected_return_values=None):
123 expected_return_values = expected_return_values or {0}
Jooyung Han504105f2021-10-26 15:54:50 +0900124 env = env or {}
125 env.update(os.environ.copy())
126
127 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
128 # e.g. sign_apex.py, sign_target_files_apk.py
129 if cmd[0] == 'avbtool':
130 cmd[0] = args.avbtool
131
132 if args.verbose:
133 print('Running: ' + ' '.join(cmd))
134 p = subprocess.Popen(
135 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
136 output, _ = p.communicate()
137
138 if args.verbose or p.returncode not in expected_return_values:
139 print(output.rstrip())
140
141 assert p.returncode in expected_return_values, (
142 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
143 return (output, p.returncode)
144
145
146def ReadBytesSize(value):
147 return int(value.removesuffix(' bytes'))
148
149
Jooyung Han832d11d2021-11-08 12:51:47 +0900150def ExtractAvbPubkey(args, key, output):
151 RunCommand(args, ['avbtool', 'extract_public_key',
152 '--key', key, '--output', output])
153
154
155def AvbInfo(args, image_path):
Jooyung Han504105f2021-10-26 15:54:50 +0900156 """Parses avbtool --info image output
157
158 Args:
159 args: program arguments.
160 image_path: The path to the image.
161 descriptor_name: Descriptor name of interest.
162
163 Returns:
164 A pair of
165 - a dict that contains VBMeta info. None if there's no VBMeta info.
Jooyung Han832d11d2021-11-08 12:51:47 +0900166 - a list of descriptors.
Jooyung Han504105f2021-10-26 15:54:50 +0900167 """
168 if not os.path.exists(image_path):
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900169 raise ValueError(f'Failed to find image: {image_path}')
Jooyung Han504105f2021-10-26 15:54:50 +0900170
171 output, ret_code = RunCommand(
172 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
173 if ret_code == 1:
174 return None, None
175
Jooyung Han832d11d2021-11-08 12:51:47 +0900176 info, descriptors = {}, []
Jooyung Han504105f2021-10-26 15:54:50 +0900177
178 # Read `avbtool info_image` output as "key:value" lines
179 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
180
181 def IterateLine(output):
182 for line in output.split('\n'):
183 line_info = matcher.match(line)
184 if not line_info:
185 continue
186 yield line_info.group(1), line_info.group(2), line_info.group(3)
187
188 gen = IterateLine(output)
Jooyung Han832d11d2021-11-08 12:51:47 +0900189
190 def ReadDescriptors(cur_indent, cur_name, cur_value):
191 descriptor = cur_value if cur_name == 'Prop' else {}
192 descriptors.append((cur_name, descriptor))
193 for indent, key, value in gen:
194 if indent <= cur_indent:
195 # read descriptors recursively to pass the read key as descriptor name
196 ReadDescriptors(indent, key, value)
197 break
198 descriptor[key] = value
199
Jooyung Han504105f2021-10-26 15:54:50 +0900200 # Read VBMeta info
201 for _, key, value in gen:
202 if key == 'Descriptors':
Jooyung Han832d11d2021-11-08 12:51:47 +0900203 ReadDescriptors(*next(gen))
Jooyung Han504105f2021-10-26 15:54:50 +0900204 break
205 info[key] = value
206
Jooyung Han832d11d2021-11-08 12:51:47 +0900207 return info, descriptors
Jooyung Han504105f2021-10-26 15:54:50 +0900208
Jooyung Han832d11d2021-11-08 12:51:47 +0900209
Shikha Panwarc149d242023-01-20 16:23:04 +0000210# Look up a list of (key, value) with a key. Returns the list of value(s) with the matching key.
211# The order of those values is maintained.
Jooyung Han832d11d2021-11-08 12:51:47 +0900212def LookUp(pairs, key):
Shikha Panwarc149d242023-01-20 16:23:04 +0000213 return [v for (k, v) in pairs if k == key]
Jooyung Han504105f2021-10-26 15:54:50 +0900214
Seungjae Yoob18d1632024-01-10 11:08:19 +0900215# Extract properties from the descriptors of original vbmeta image,
216# append to command as parameter.
217def AppendPropArgument(cmd, descriptors):
218 for prop in LookUp(descriptors, 'Prop'):
219 cmd.append('--prop')
220 result = re.match(r"(.+) -> '(.+)'", prop)
221 cmd.append(result.group(1) + ":" + result.group(2))
Jooyung Han504105f2021-10-26 15:54:50 +0900222
Shikha Panwarc149d242023-01-20 16:23:04 +0000223def AddHashFooter(args, key, image_path, partition_name, additional_descriptors=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900224 if os.path.basename(image_path) in args.key_overrides:
225 key = args.key_overrides[os.path.basename(image_path)]
Seungjae Yoob18d1632024-01-10 11:08:19 +0900226 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900227 if info:
228 image_size = ReadBytesSize(info['Image size'])
229 algorithm = info['Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900230 partition_size = str(image_size)
231
232 cmd = ['avbtool', 'add_hash_footer',
233 '--key', key,
234 '--algorithm', algorithm,
235 '--partition_name', partition_name,
236 '--partition_size', partition_size,
237 '--image', image_path]
Seungjae Yoob18d1632024-01-10 11:08:19 +0900238 AppendPropArgument(cmd, descriptors)
Jooyung Han98498f42022-02-07 15:23:08 +0900239 if args.signing_args:
240 cmd.extend(shlex.split(args.signing_args))
Shikha Panwarc149d242023-01-20 16:23:04 +0000241 if additional_descriptors:
242 for image in additional_descriptors:
243 cmd.extend(['--include_descriptors_from_image', image])
Shikha Panwar2a788662023-09-11 14:04:24 +0000244
245 if 'Rollback Index' in info:
246 cmd.extend(['--rollback_index', info['Rollback Index']])
Jooyung Han504105f2021-10-26 15:54:50 +0900247 RunCommand(args, cmd)
248
249
250def AddHashTreeFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900251 if os.path.basename(image_path) in args.key_overrides:
252 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900253 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900254 if info:
Shikha Panwarc149d242023-01-20 16:23:04 +0000255 descriptor = LookUp(descriptors, 'Hashtree descriptor')[0]
Jooyung Han504105f2021-10-26 15:54:50 +0900256 image_size = ReadBytesSize(info['Image size'])
257 algorithm = info['Algorithm']
258 partition_name = descriptor['Partition Name']
Shikha Panwar638119b2023-01-03 06:00:26 +0000259 hash_algorithm = descriptor['Hash Algorithm']
Jooyung Han504105f2021-10-26 15:54:50 +0900260 partition_size = str(image_size)
Jooyung Han504105f2021-10-26 15:54:50 +0900261 cmd = ['avbtool', 'add_hashtree_footer',
262 '--key', key,
263 '--algorithm', algorithm,
264 '--partition_name', partition_name,
265 '--partition_size', partition_size,
266 '--do_not_generate_fec',
Shikha Panwar638119b2023-01-03 06:00:26 +0000267 '--hash_algorithm', hash_algorithm,
Jooyung Han504105f2021-10-26 15:54:50 +0900268 '--image', image_path]
Seungjae Yoob18d1632024-01-10 11:08:19 +0900269 AppendPropArgument(cmd, descriptors)
Jooyung Han98498f42022-02-07 15:23:08 +0900270 if args.signing_args:
271 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900272 RunCommand(args, cmd)
273
274
Shikha Panwara7605cf2023-01-12 09:29:39 +0000275def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
276 # Update the bootconfigs in ramdisk
277 def detach_bootconfigs(initrd_bc, initrd, bc):
278 cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
279 RunCommand(args, cmd)
280
281 def attach_bootconfigs(initrd_bc, initrd, bc):
282 cmd = ['initrd_bootconfig', 'attach',
283 initrd, bc, '--output', initrd_bc]
284 RunCommand(args, cmd)
285
286 # Validate that avb version used while signing the apex is the same as used by build server
287 def validate_avb_version(bootconfigs):
288 cmd = ['avbtool', 'version']
289 stdout, _ = RunCommand(args, cmd)
290 avb_version_curr = stdout.split(" ")[1].strip()
291 avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
292
293 avb_version_bc = re.search(
294 r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
295 if avb_version_curr != avb_version_bc:
Nikita Ioffee1112032023-11-13 15:09:39 +0000296 raise builtins.Exception(f'AVB version mismatch between current & one & \
Shikha Panwara7605cf2023-01-12 09:29:39 +0000297 used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
298
299 def calc_vbmeta_digest():
300 cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
301 vbmeta_img, '--hash_algorithm', 'sha256']
302 stdout, _ = RunCommand(args, cmd)
303 return stdout.strip()
304
305 def calc_vbmeta_size():
306 cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
307 stdout, _ = RunCommand(args, cmd)
308 size = 0
309 for line in stdout.split("\n"):
310 line = line.split(":")
311 if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
312 size += int(line[1].strip()[0:-6])
313 return size
314
315 def update_vbmeta_digest(bootconfigs):
316 # Update androidboot.vbmeta.digest in bootconfigs
317 result = re.search(
318 r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
319 if not result:
320 raise ValueError("Failed to find androidboot.vbmeta.digest")
321
322 return bootconfigs.replace(result.group(),
323 f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
324
325 def update_vbmeta_size(bootconfigs):
326 # Update androidboot.vbmeta.size in bootconfigs
327 result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
328 if not result:
329 raise ValueError("Failed to find androidboot.vbmeta.size")
330 return bootconfigs.replace(result.group(),
331 f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
332
333 with tempfile.TemporaryDirectory() as work_dir:
334 tmp_initrd = os.path.join(work_dir, 'initrd')
335 tmp_bc = os.path.join(work_dir, 'bc')
336
337 for initrd in initrds:
338 detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
339 bc_file = open(tmp_bc, "rt", encoding="utf-8")
340 bc_data = bc_file.read()
Nikita Ioffe314d7e32023-12-18 17:38:18 +0000341 if not args.do_not_validate_avb_version:
342 validate_avb_version(bc_data)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000343 bc_data = update_vbmeta_digest(bc_data)
344 bc_data = update_vbmeta_size(bc_data)
345 bc_file.close()
346 bc_file = open(tmp_bc, "wt", encoding="utf-8")
347 bc_file.write(bc_data)
348 bc_file.flush()
349 attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
350
351
Jooyung Han832d11d2021-11-08 12:51:47 +0900352def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900353 if os.path.basename(vbmeta_img) in args.key_overrides:
354 key = args.key_overrides[os.path.basename(vbmeta_img)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900355 info, descriptors = AvbInfo(args, vbmeta_img)
356 if info is None:
357 return
358
Jooyung Han486609f2022-04-20 11:38:00 +0900359 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900360 algorithm = info['Algorithm']
361 rollback_index = info['Rollback Index']
362 rollback_index_location = info['Rollback Index Location']
363
364 cmd = ['avbtool', 'make_vbmeta_image',
365 '--key', key,
366 '--algorithm', algorithm,
367 '--rollback_index', rollback_index,
368 '--rollback_index_location', rollback_index_location,
369 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900370 if images:
371 for img in images:
372 cmd.extend(['--include_descriptors_from_image', img])
373
374 # replace pubkeys of chained_partitions as well
375 for name, descriptor in descriptors:
376 if name == 'Chain Partition descriptor':
377 part_name = descriptor['Partition Name']
378 ril = descriptor['Rollback Index Location']
379 part_key = chained_partitions[part_name]
380 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
381 ExtractAvbPubkey(args, part_key, avbpubkey)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900382 cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900383
Jooyung Han98498f42022-02-07 15:23:08 +0900384 if args.signing_args:
385 cmd.extend(shlex.split(args.signing_args))
386
Jooyung Han504105f2021-10-26 15:54:50 +0900387 RunCommand(args, cmd)
388 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
389 # which matches this or the read will fail.
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900390 with open(vbmeta_img, 'a', encoding='utf8') as f:
Jooyung Handcb0b492022-02-26 09:04:17 +0900391 f.truncate(65536)
Jooyung Han504105f2021-10-26 15:54:50 +0900392
393
Jooyung Han486609f2022-04-20 11:38:00 +0900394def UnpackSuperImg(args, super_img, work_dir):
395 tmp_super_img = os.path.join(work_dir, 'super.img')
396 RunCommand(args, ['simg2img', super_img, tmp_super_img])
397 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
Jooyung Han504105f2021-10-26 15:54:50 +0900398
399
400def MakeSuperImage(args, partitions, output):
Jooyung Han486609f2022-04-20 11:38:00 +0900401 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900402 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
403 '--metadata-size=65536', '--sparse', '--output=' + output]
404
405 for part, img in partitions.items():
406 tmp_img = os.path.join(work_dir, part)
407 RunCommand(args, ['img2simg', img, tmp_img])
408
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900409 image_arg = f'--image={part}={img}'
410 partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default'
Jooyung Han504105f2021-10-26 15:54:50 +0900411 cmd.extend([image_arg, partition_arg])
412
413 RunCommand(args, cmd)
414
415
Shikha Panwarc149d242023-01-20 16:23:04 +0000416def GenVbmetaImage(args, image, output, partition_name):
417 cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size',
418 '--do_not_append_vbmeta_image',
419 '--partition_name', partition_name,
420 '--image', image,
421 '--output_vbmeta_image', output]
422 RunCommand(args, cmd)
423
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900424
Inseob Kim0276f612023-12-07 17:25:18 +0900425gki_versions = ['android14-6.1']
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900426
Jooyung Han486609f2022-04-20 11:38:00 +0900427# dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900428virt_apex_non_gki_files = {
Shikha Panwara7605cf2023-01-12 09:29:39 +0000429 'kernel': 'etc/fs/microdroid_kernel',
Jooyung Han486609f2022-04-20 11:38:00 +0900430 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000431 'super.img': 'etc/fs/microdroid_super.img',
432 'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
433 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
Alice Wangbe8330c2023-10-19 08:55:07 +0000434 'rialto': 'etc/rialto.bin',
Jooyung Han486609f2022-04-20 11:38:00 +0900435}
436
Jooyung Han486609f2022-04-20 11:38:00 +0900437def TargetFiles(input_dir):
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900438 ret = {k: os.path.join(input_dir, v) for k, v in virt_apex_non_gki_files.items()}
439
440 for ver in gki_versions:
441 kernel = os.path.join(input_dir, f'etc/fs/microdroid_gki-{ver}_kernel')
442 initrd_normal = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_normal.img')
443 initrd_debug = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_debuggable.img')
444
445 if os.path.isfile(kernel):
446 ret[f'gki-{ver}_kernel'] = kernel
447 ret[f'gki-{ver}_initrd_normal.img'] = initrd_normal
448 ret[f'gki-{ver}_initrd_debuggable.img'] = initrd_debug
449
450 return ret
451
452def IsInitrdImage(path):
453 return path.endswith('initrd_normal.img') or path.endswith('initrd_debuggable.img')
Jooyung Han486609f2022-04-20 11:38:00 +0900454
455
Jooyung Han504105f2021-10-26 15:54:50 +0900456def SignVirtApex(args):
457 key = args.key
458 input_dir = args.input_dir
Jooyung Han486609f2022-04-20 11:38:00 +0900459 files = TargetFiles(input_dir)
Jooyung Han504105f2021-10-26 15:54:50 +0900460
Jooyung Han486609f2022-04-20 11:38:00 +0900461 # unpacked files (will be unpacked from super.img below)
462 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Nikita Ioffee1112032023-11-13 15:09:39 +0000463 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900464
Jooyung Han504105f2021-10-26 15:54:50 +0900465 # re-sign super.img
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900466 # 1. unpack super.img
Nikita Ioffee1112032023-11-13 15:09:39 +0000467 # 2. resign system and vendor (if exists)
468 # 3. repack super.img out of resigned system and vendor (if exists)
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900469 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
470 system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000471 partitions = {"system_a": system_a_img}
Nikita Ioffee1112032023-11-13 15:09:39 +0000472 images = [system_a_img]
473 images_f = [system_a_f]
474
475 # if vendor_a.img exists, resign it
476 if os.path.exists(vendor_a_img):
477 partitions.update({'vendor_a': vendor_a_img})
478 images.append(vendor_a_img)
479 vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
480 images_f.append(vendor_a_f)
481
Shikha Panwara7605cf2023-01-12 09:29:39 +0000482 Async(MakeSuperImage, args, partitions,
Nikita Ioffee1112032023-11-13 15:09:39 +0000483 files['super.img'], wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900484
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000485 # re-generate vbmeta from re-signed system_a.img
Shikha Panwara7605cf2023-01-12 09:29:39 +0000486 vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
Nikita Ioffee1112032023-11-13 15:09:39 +0000487 images=images,
488 wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900489
Shikha Panwarc149d242023-01-20 16:23:04 +0000490 vbmeta_bc_f = None
Shikha Panwara7605cf2023-01-12 09:29:39 +0000491 if not args.do_not_update_bootconfigs:
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900492 initrd_files = [v for k, v in files.items() if IsInitrdImage(k)]
Inseob Kim77c7f712023-11-06 17:01:02 +0900493 vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args, initrd_files,
494 files['vbmeta.img'],
Shikha Panwarc149d242023-01-20 16:23:04 +0000495 wait=[vbmeta_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900496
Shikha Panwarc149d242023-01-20 16:23:04 +0000497 # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s)
Inseob Kim77c7f712023-11-06 17:01:02 +0900498 def resign_kernel(kernel, initrd_normal, initrd_debug):
499 kernel_file = files[kernel]
500 initrd_normal_file = files[initrd_normal]
501 initrd_debug_file = files[initrd_debug]
502
503 initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
504 initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
505 initrd_n_f = Async(GenVbmetaImage, args, initrd_normal_file,
506 initrd_normal_hashdesc, "initrd_normal",
507 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
508 initrd_d_f = Async(GenVbmetaImage, args, initrd_debug_file,
509 initrd_debug_hashdesc, "initrd_debug",
510 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
511 Async(AddHashFooter, args, key, kernel_file, partition_name="boot",
512 additional_descriptors=[
513 initrd_normal_hashdesc, initrd_debug_hashdesc],
514 wait=[initrd_n_f, initrd_d_f])
515
516 resign_kernel('kernel', 'initrd_normal.img', 'initrd_debuggable.img')
517
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900518 for ver in gki_versions:
519 if f'gki-{ver}_kernel' in files:
520 resign_kernel(
521 f'gki-{ver}_kernel',
522 f'gki-{ver}_initrd_normal.img',
523 f'gki-{ver}_initrd_debuggable.img')
Jooyung Han832d11d2021-11-08 12:51:47 +0900524
Alice Wangbe8330c2023-10-19 08:55:07 +0000525 # Re-sign rialto if it exists. Rialto only exists in arm64 environment.
526 if os.path.exists(files['rialto']):
527 Async(AddHashFooter, args, key, files['rialto'], partition_name='boot')
528
Jooyung Han504105f2021-10-26 15:54:50 +0900529
Jooyung Han02dceed2021-11-08 17:50:22 +0900530def VerifyVirtApex(args):
Jooyung Han486609f2022-04-20 11:38:00 +0900531 key = args.key
532 input_dir = args.input_dir
533 files = TargetFiles(input_dir)
Jooyung Han02dceed2021-11-08 17:50:22 +0900534
Jooyung Han486609f2022-04-20 11:38:00 +0900535 # unpacked files
536 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
537 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Jooyung Han02dceed2021-11-08 17:50:22 +0900538
Jooyung Han486609f2022-04-20 11:38:00 +0900539 # Read pubkey digest from the input key
540 with tempfile.NamedTemporaryFile() as pubkey_file:
541 ExtractAvbPubkey(args, key, pubkey_file.name)
542 with open(pubkey_file.name, 'rb') as f:
543 pubkey = f.read()
544 pubkey_digest = hashlib.sha1(pubkey).hexdigest()
Jooyung Han02dceed2021-11-08 17:50:22 +0900545
Jooyung Han486609f2022-04-20 11:38:00 +0900546 def check_avb_pubkey(file):
547 info, _ = AvbInfo(args, file)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900548 assert info is not None, f'no avbinfo: {file}'
549 assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
Jooyung Han486609f2022-04-20 11:38:00 +0900550
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900551 for k, f in files.items():
552 if IsInitrdImage(k):
Shikha Panwara7605cf2023-01-12 09:29:39 +0000553 # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
554 continue
Alice Wangbe8330c2023-10-19 08:55:07 +0000555 if k == 'rialto' and not os.path.exists(f):
556 # Rialto only exists in arm64 environment.
557 continue
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900558 if k == 'super.img':
Jooyung Han486609f2022-04-20 11:38:00 +0900559 Async(check_avb_pubkey, system_a_img)
Jooyung Han486609f2022-04-20 11:38:00 +0900560 else:
561 # Check pubkey for other files using avbtool
562 Async(check_avb_pubkey, f)
Jooyung Han02dceed2021-11-08 17:50:22 +0900563
564
Jooyung Han504105f2021-10-26 15:54:50 +0900565def main(argv):
566 try:
567 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900568 if args.verify:
569 VerifyVirtApex(args)
570 else:
571 SignVirtApex(args)
Jooyung Han486609f2022-04-20 11:38:00 +0900572 # ensure all tasks are completed without exceptions
573 AwaitAll(tasks)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000574 except: # pylint: disable=bare-except
Jooyung Han486609f2022-04-20 11:38:00 +0900575 traceback.print_exc()
Jooyung Han504105f2021-10-26 15:54:50 +0900576 sys.exit(1)
577
578
579if __name__ == '__main__':
580 main(sys.argv[1:])