blob: e042f8dec94501d79cba2f4da2decdaa4c36b21e [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
Alice Wang2a6caf12024-01-11 08:14:05 +000030import binascii
Nikita Ioffee1112032023-11-13 15:09:39 +000031import builtins
Jooyung Han02dceed2021-11-08 17:50:22 +090032import hashlib
Jooyung Han504105f2021-10-26 15:54:50 +090033import os
34import re
Jooyung Han98498f42022-02-07 15:23:08 +090035import shlex
Jooyung Han504105f2021-10-26 15:54:50 +090036import subprocess
37import sys
38import tempfile
Jooyung Han486609f2022-04-20 11:38:00 +090039import traceback
40from concurrent import futures
41
42# pylint: disable=line-too-long,consider-using-with
43
44# Use executor to parallelize the invocation of external tools
45# If a task depends on another, pass the future object of the previous task as wait list.
46# Every future object created by a task should be consumed with AwaitAll()
47# so that exceptions are propagated .
48executor = futures.ThreadPoolExecutor()
49
50# Temporary directory for unpacked super.img.
51# We could put its creation/deletion into the task graph as well, but
52# having it as a global setup is much simpler.
53unpack_dir = tempfile.TemporaryDirectory()
54
55# tasks created with Async() are kept in a list so that they are awaited
56# before exit.
57tasks = []
58
59# create an async task and return a future value of it.
60def Async(fn, *args, wait=None, **kwargs):
61
62 # wrap a function with AwaitAll()
63 def wrapped():
64 AwaitAll(wait)
65 fn(*args, **kwargs)
66
67 task = executor.submit(wrapped)
68 tasks.append(task)
69 return task
70
71
72# waits for task (captured in fs as future values) with future.result()
73# so that any exception raised during task can be raised upward.
74def AwaitAll(fs):
75 if fs:
76 for f in fs:
77 f.result()
Jooyung Han504105f2021-10-26 15:54:50 +090078
79
80def ParseArgs(argv):
81 parser = argparse.ArgumentParser(description='Sign the Virt APEX')
Jooyung Han02dceed2021-11-08 17:50:22 +090082 parser.add_argument('--verify', action='store_true',
83 help='Verify the Virt APEX')
Jooyung Han504105f2021-10-26 15:54:50 +090084 parser.add_argument(
85 '-v', '--verbose',
86 action='store_true',
87 help='verbose execution')
88 parser.add_argument(
89 '--avbtool',
90 default='avbtool',
91 help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.')
92 parser.add_argument(
Jooyung Han98498f42022-02-07 15:23:08 +090093 '--signing_args',
94 help='the extra signing arguments passed to avbtool.'
95 )
96 parser.add_argument(
Jooyung Han1c3d2fa2022-02-24 02:35:59 +090097 '--key_override',
98 metavar="filename=key",
99 action='append',
100 help='Overrides a signing key for a file e.g. microdroid_bootloader=mykey (for testing)')
101 parser.add_argument(
Jooyung Han504105f2021-10-26 15:54:50 +0900102 'key',
103 help='path to the private key file.')
104 parser.add_argument(
105 'input_dir',
106 help='the directory having files to be packaged')
Shikha Panwara7605cf2023-01-12 09:29:39 +0000107 parser.add_argument(
108 '--do_not_update_bootconfigs',
109 action='store_true',
110 help='This will NOT update the vbmeta related bootconfigs while signing the apex.\
111 Used for testing only!!')
Nikita Ioffe314d7e32023-12-18 17:38:18 +0000112 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 +0900113 args = parser.parse_args(argv)
114 # preprocess --key_override into a map
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900115 args.key_overrides = {}
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900116 if args.key_override:
117 for pair in args.key_override:
118 name, key = pair.split('=')
119 args.key_overrides[name] = key
120 return args
Jooyung Han504105f2021-10-26 15:54:50 +0900121
122
Jooyung Han486609f2022-04-20 11:38:00 +0900123def RunCommand(args, cmd, env=None, expected_return_values=None):
124 expected_return_values = expected_return_values or {0}
Jooyung Han504105f2021-10-26 15:54:50 +0900125 env = env or {}
126 env.update(os.environ.copy())
127
128 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
129 # e.g. sign_apex.py, sign_target_files_apk.py
130 if cmd[0] == 'avbtool':
131 cmd[0] = args.avbtool
132
133 if args.verbose:
134 print('Running: ' + ' '.join(cmd))
135 p = subprocess.Popen(
136 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
137 output, _ = p.communicate()
138
139 if args.verbose or p.returncode not in expected_return_values:
140 print(output.rstrip())
141
142 assert p.returncode in expected_return_values, (
143 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
144 return (output, p.returncode)
145
146
147def ReadBytesSize(value):
148 return int(value.removesuffix(' bytes'))
149
150
Jooyung Han832d11d2021-11-08 12:51:47 +0900151def ExtractAvbPubkey(args, key, output):
152 RunCommand(args, ['avbtool', 'extract_public_key',
153 '--key', key, '--output', output])
154
155
Inseob Kim2e2f48a2024-02-21 22:56:08 +0900156def is_lz4(args, path):
157 # error 44: Unrecognized header
158 result = RunCommand(args, ['lz4', '-t', path], expected_return_values={0, 44})
159 return result[1] == 0
160
161
Jooyung Han832d11d2021-11-08 12:51:47 +0900162def AvbInfo(args, image_path):
Jooyung Han504105f2021-10-26 15:54:50 +0900163 """Parses avbtool --info image output
164
165 Args:
166 args: program arguments.
Inseob Kim2e2f48a2024-02-21 22:56:08 +0900167 image_path: The path to the image, either raw or lz4 compressed
Jooyung Han504105f2021-10-26 15:54:50 +0900168 descriptor_name: Descriptor name of interest.
169
170 Returns:
171 A pair of
172 - a dict that contains VBMeta info. None if there's no VBMeta info.
Jooyung Han832d11d2021-11-08 12:51:47 +0900173 - a list of descriptors.
Jooyung Han504105f2021-10-26 15:54:50 +0900174 """
175 if not os.path.exists(image_path):
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900176 raise ValueError(f'Failed to find image: {image_path}')
Jooyung Han504105f2021-10-26 15:54:50 +0900177
Inseob Kim2e2f48a2024-02-21 22:56:08 +0900178 if is_lz4(args, image_path):
179 with tempfile.NamedTemporaryFile() as decompressed_image:
180 RunCommand(args, ['lz4', '-d', '-f', image_path, decompressed_image.name])
181 return AvbInfo(args, decompressed_image.name)
182
Jooyung Han504105f2021-10-26 15:54:50 +0900183 output, ret_code = RunCommand(
184 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
185 if ret_code == 1:
186 return None, None
187
Jooyung Han832d11d2021-11-08 12:51:47 +0900188 info, descriptors = {}, []
Jooyung Han504105f2021-10-26 15:54:50 +0900189
190 # Read `avbtool info_image` output as "key:value" lines
191 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
192
193 def IterateLine(output):
194 for line in output.split('\n'):
195 line_info = matcher.match(line)
196 if not line_info:
197 continue
198 yield line_info.group(1), line_info.group(2), line_info.group(3)
199
200 gen = IterateLine(output)
Jooyung Han832d11d2021-11-08 12:51:47 +0900201
202 def ReadDescriptors(cur_indent, cur_name, cur_value):
203 descriptor = cur_value if cur_name == 'Prop' else {}
204 descriptors.append((cur_name, descriptor))
205 for indent, key, value in gen:
206 if indent <= cur_indent:
207 # read descriptors recursively to pass the read key as descriptor name
208 ReadDescriptors(indent, key, value)
209 break
210 descriptor[key] = value
211
Jooyung Han504105f2021-10-26 15:54:50 +0900212 # Read VBMeta info
213 for _, key, value in gen:
214 if key == 'Descriptors':
Jooyung Han832d11d2021-11-08 12:51:47 +0900215 ReadDescriptors(*next(gen))
Jooyung Han504105f2021-10-26 15:54:50 +0900216 break
217 info[key] = value
218
Jooyung Han832d11d2021-11-08 12:51:47 +0900219 return info, descriptors
Jooyung Han504105f2021-10-26 15:54:50 +0900220
Jooyung Han832d11d2021-11-08 12:51:47 +0900221
Alice Wang34c19232024-01-11 16:06:28 +0000222def find_all_values_by_key(pairs, key):
223 """Find all the values of the key in the pairs."""
Shikha Panwarc149d242023-01-20 16:23:04 +0000224 return [v for (k, v) in pairs if k == key]
Jooyung Han504105f2021-10-26 15:54:50 +0900225
Seungjae Yoob18d1632024-01-10 11:08:19 +0900226# Extract properties from the descriptors of original vbmeta image,
227# append to command as parameter.
228def AppendPropArgument(cmd, descriptors):
Alice Wang34c19232024-01-11 16:06:28 +0000229 for prop in find_all_values_by_key(descriptors, 'Prop'):
Seungjae Yoob18d1632024-01-10 11:08:19 +0900230 cmd.append('--prop')
231 result = re.match(r"(.+) -> '(.+)'", prop)
232 cmd.append(result.group(1) + ":" + result.group(2))
Jooyung Han504105f2021-10-26 15:54:50 +0900233
Seungjae Yoo3f46c7f2024-01-10 14:32:54 +0900234
Alice Wang34c19232024-01-11 16:06:28 +0000235def check_resigned_image_avb_info(image_path, original_info, original_descriptors, args):
236 updated_info, updated_descriptors = AvbInfo(args, image_path)
237 assert original_info is not None, f'no avbinfo on original image: {image_path}'
238 assert updated_info is not None, f'no avbinfo on resigned image: {image_path}'
239 assert_different_value(original_info, updated_info, "Public key (sha1)", image_path)
240 updated_public_key = updated_info.pop("Public key (sha1)")
241 if not hasattr(check_resigned_image_avb_info, "new_public_key"):
242 check_resigned_image_avb_info.new_public_key = updated_public_key
243 else:
244 assert check_resigned_image_avb_info.new_public_key == updated_public_key, \
245 "All images should be resigned with the same public key. Expected public key (sha1):" \
246 f" {check_resigned_image_avb_info.new_public_key}, actual public key (sha1): " \
247 f"{updated_public_key}, Path: {image_path}"
248 original_info.pop("Public key (sha1)")
249 assert original_info == updated_info, \
250 f"Original info and updated info should be the same for {image_path}. " \
251 f"Original info: {original_info}, updated info: {updated_info}"
Seungjae Yoo3f46c7f2024-01-10 14:32:54 +0900252
Alice Wang34c19232024-01-11 16:06:28 +0000253 # Verify the descriptors of the original and updated images.
254 assert len(original_descriptors) == len(updated_descriptors), \
255 f"Number of descriptors should be the same for {image_path}. " \
256 f"Original descriptors: {original_descriptors}, updated descriptors: {updated_descriptors}"
257 original_prop_descriptors = sorted(find_all_values_by_key(original_descriptors, "Prop"))
258 updated_prop_descriptors = sorted(find_all_values_by_key(updated_descriptors, "Prop"))
259 assert original_prop_descriptors == updated_prop_descriptors, \
260 f"Prop descriptors should be the same for {image_path}. " \
261 f"Original prop descriptors: {original_prop_descriptors}, " \
262 f"updated prop descriptors: {updated_prop_descriptors}"
263
264 # Remove digest from hash descriptors before comparing, since some digests should change.
265 original_hash_descriptors = extract_hash_descriptors(original_descriptors, drop_digest)
266 updated_hash_descriptors = extract_hash_descriptors(updated_descriptors, drop_digest)
267 assert original_hash_descriptors == updated_hash_descriptors, \
268 f"Hash descriptors' parameters should be the same for {image_path}. " \
269 f"Original hash descriptors: {original_hash_descriptors}, " \
270 f"updated hash descriptors: {updated_hash_descriptors}"
271
272def drop_digest(descriptor):
273 return {k: v for k, v in descriptor.items() if k != "Digest"}
274
275def AddHashFooter(args, key, image_path, additional_images=()):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900276 if os.path.basename(image_path) in args.key_overrides:
277 key = args.key_overrides[os.path.basename(image_path)]
Seungjae Yoob18d1632024-01-10 11:08:19 +0900278 info, descriptors = AvbInfo(args, image_path)
Alice Wang34c19232024-01-11 16:06:28 +0000279 assert info is not None, f'no avbinfo: {image_path}'
Seungjae Yoo43574482024-01-11 16:27:51 +0900280
Alice Wang34c19232024-01-11 16:06:28 +0000281 # Extract hash descriptor of original image.
282 hash_descriptors_original = extract_hash_descriptors(descriptors, drop_digest)
283 for additional_image in additional_images:
284 _, additional_desc = AvbInfo(args, additional_image)
285 hash_descriptors = extract_hash_descriptors(additional_desc, drop_digest)
286 for k, v in hash_descriptors.items():
287 assert v == hash_descriptors_original[k], \
288 f"Hash descriptor of {k} in {additional_image} and {image_path} should be " \
289 f"the same. {additional_image}: {v}, {image_path}: {hash_descriptors_original[k]}"
290 del hash_descriptors_original[k]
291 assert len(hash_descriptors_original) == 1, \
292 f"Only one hash descriptor is expected for {image_path} after removing " \
293 f"additional images. Hash descriptors: {hash_descriptors_original}"
294 [(original_image_partition_name, original_image_descriptor)] = hash_descriptors_original.items()
295 assert info["Original image size"] == original_image_descriptor["Image Size"], \
296 f"Original image size should be the same as the image size in the hash descriptor " \
297 f"for {image_path}. Original image size: {info['Original image size']}, " \
298 f"image size in the hash descriptor: {original_image_descriptor['Image Size']}"
Jooyung Han504105f2021-10-26 15:54:50 +0900299
Alice Wang34c19232024-01-11 16:06:28 +0000300 partition_size = str(ReadBytesSize(info['Image size']))
301 algorithm = info['Algorithm']
302 original_image_salt = original_image_descriptor['Salt']
Shikha Panwar2a788662023-09-11 14:04:24 +0000303
Alice Wang34c19232024-01-11 16:06:28 +0000304 cmd = ['avbtool', 'add_hash_footer',
305 '--key', key,
306 '--algorithm', algorithm,
307 '--partition_name', original_image_partition_name,
308 '--salt', original_image_salt,
309 '--partition_size', partition_size,
310 '--image', image_path]
311 AppendPropArgument(cmd, descriptors)
312 if args.signing_args:
313 cmd.extend(shlex.split(args.signing_args))
314 for additional_image in additional_images:
315 cmd.extend(['--include_descriptors_from_image', additional_image])
316 cmd.extend(['--rollback_index', info['Rollback Index']])
317
318 RunCommand(args, cmd)
319 check_resigned_image_avb_info(image_path, info, descriptors, args)
Jooyung Han504105f2021-10-26 15:54:50 +0900320
321def AddHashTreeFooter(args, key, image_path):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900322 if os.path.basename(image_path) in args.key_overrides:
323 key = args.key_overrides[os.path.basename(image_path)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900324 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900325 if info:
Alice Wang34c19232024-01-11 16:06:28 +0000326 descriptor = find_all_values_by_key(descriptors, 'Hashtree descriptor')[0]
Jooyung Han504105f2021-10-26 15:54:50 +0900327 image_size = ReadBytesSize(info['Image size'])
328 algorithm = info['Algorithm']
329 partition_name = descriptor['Partition Name']
Shikha Panwar638119b2023-01-03 06:00:26 +0000330 hash_algorithm = descriptor['Hash Algorithm']
Seungjae Yoo43574482024-01-11 16:27:51 +0900331 salt = descriptor['Salt']
Jooyung Han504105f2021-10-26 15:54:50 +0900332 partition_size = str(image_size)
Jooyung Han504105f2021-10-26 15:54:50 +0900333 cmd = ['avbtool', 'add_hashtree_footer',
334 '--key', key,
335 '--algorithm', algorithm,
336 '--partition_name', partition_name,
337 '--partition_size', partition_size,
338 '--do_not_generate_fec',
Shikha Panwar638119b2023-01-03 06:00:26 +0000339 '--hash_algorithm', hash_algorithm,
Seungjae Yoo43574482024-01-11 16:27:51 +0900340 '--salt', salt,
Jooyung Han504105f2021-10-26 15:54:50 +0900341 '--image', image_path]
Seungjae Yoob18d1632024-01-10 11:08:19 +0900342 AppendPropArgument(cmd, descriptors)
Jooyung Han98498f42022-02-07 15:23:08 +0900343 if args.signing_args:
344 cmd.extend(shlex.split(args.signing_args))
Jooyung Han504105f2021-10-26 15:54:50 +0900345 RunCommand(args, cmd)
Alice Wang34c19232024-01-11 16:06:28 +0000346 check_resigned_image_avb_info(image_path, info, descriptors, args)
Jooyung Han504105f2021-10-26 15:54:50 +0900347
348
Shikha Panwara7605cf2023-01-12 09:29:39 +0000349def UpdateVbmetaBootconfig(args, initrds, vbmeta_img):
350 # Update the bootconfigs in ramdisk
351 def detach_bootconfigs(initrd_bc, initrd, bc):
352 cmd = ['initrd_bootconfig', 'detach', initrd_bc, initrd, bc]
353 RunCommand(args, cmd)
354
355 def attach_bootconfigs(initrd_bc, initrd, bc):
356 cmd = ['initrd_bootconfig', 'attach',
357 initrd, bc, '--output', initrd_bc]
358 RunCommand(args, cmd)
359
360 # Validate that avb version used while signing the apex is the same as used by build server
361 def validate_avb_version(bootconfigs):
362 cmd = ['avbtool', 'version']
363 stdout, _ = RunCommand(args, cmd)
364 avb_version_curr = stdout.split(" ")[1].strip()
365 avb_version_curr = avb_version_curr[0:avb_version_curr.rfind('.')]
366
367 avb_version_bc = re.search(
368 r"androidboot.vbmeta.avb_version = \"([^\"]*)\"", bootconfigs).group(1)
369 if avb_version_curr != avb_version_bc:
Nikita Ioffee1112032023-11-13 15:09:39 +0000370 raise builtins.Exception(f'AVB version mismatch between current & one & \
Shikha Panwara7605cf2023-01-12 09:29:39 +0000371 used to build bootconfigs:{avb_version_curr}&{avb_version_bc}')
372
373 def calc_vbmeta_digest():
374 cmd = ['avbtool', 'calculate_vbmeta_digest', '--image',
375 vbmeta_img, '--hash_algorithm', 'sha256']
376 stdout, _ = RunCommand(args, cmd)
377 return stdout.strip()
378
379 def calc_vbmeta_size():
380 cmd = ['avbtool', 'info_image', '--image', vbmeta_img]
381 stdout, _ = RunCommand(args, cmd)
382 size = 0
383 for line in stdout.split("\n"):
384 line = line.split(":")
385 if line[0] in ['Header Block', 'Authentication Block', 'Auxiliary Block']:
386 size += int(line[1].strip()[0:-6])
387 return size
388
389 def update_vbmeta_digest(bootconfigs):
390 # Update androidboot.vbmeta.digest in bootconfigs
391 result = re.search(
392 r"androidboot.vbmeta.digest = \"[^\"]*\"", bootconfigs)
393 if not result:
394 raise ValueError("Failed to find androidboot.vbmeta.digest")
395
396 return bootconfigs.replace(result.group(),
397 f'androidboot.vbmeta.digest = "{calc_vbmeta_digest()}"')
398
399 def update_vbmeta_size(bootconfigs):
400 # Update androidboot.vbmeta.size in bootconfigs
401 result = re.search(r"androidboot.vbmeta.size = [0-9]+", bootconfigs)
402 if not result:
403 raise ValueError("Failed to find androidboot.vbmeta.size")
404 return bootconfigs.replace(result.group(),
405 f'androidboot.vbmeta.size = {calc_vbmeta_size()}')
406
407 with tempfile.TemporaryDirectory() as work_dir:
408 tmp_initrd = os.path.join(work_dir, 'initrd')
409 tmp_bc = os.path.join(work_dir, 'bc')
410
411 for initrd in initrds:
412 detach_bootconfigs(initrd, tmp_initrd, tmp_bc)
413 bc_file = open(tmp_bc, "rt", encoding="utf-8")
414 bc_data = bc_file.read()
Nikita Ioffe314d7e32023-12-18 17:38:18 +0000415 if not args.do_not_validate_avb_version:
416 validate_avb_version(bc_data)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000417 bc_data = update_vbmeta_digest(bc_data)
418 bc_data = update_vbmeta_size(bc_data)
419 bc_file.close()
420 bc_file = open(tmp_bc, "wt", encoding="utf-8")
421 bc_file.write(bc_data)
422 bc_file.flush()
423 attach_bootconfigs(initrd, tmp_initrd, tmp_bc)
424
425
Jooyung Han832d11d2021-11-08 12:51:47 +0900426def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
Jooyung Han1c3d2fa2022-02-24 02:35:59 +0900427 if os.path.basename(vbmeta_img) in args.key_overrides:
428 key = args.key_overrides[os.path.basename(vbmeta_img)]
Jooyung Han832d11d2021-11-08 12:51:47 +0900429 info, descriptors = AvbInfo(args, vbmeta_img)
430 if info is None:
431 return
432
Jooyung Han486609f2022-04-20 11:38:00 +0900433 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900434 algorithm = info['Algorithm']
435 rollback_index = info['Rollback Index']
436 rollback_index_location = info['Rollback Index Location']
437
438 cmd = ['avbtool', 'make_vbmeta_image',
439 '--key', key,
440 '--algorithm', algorithm,
441 '--rollback_index', rollback_index,
442 '--rollback_index_location', rollback_index_location,
443 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900444 if images:
445 for img in images:
446 cmd.extend(['--include_descriptors_from_image', img])
447
448 # replace pubkeys of chained_partitions as well
449 for name, descriptor in descriptors:
450 if name == 'Chain Partition descriptor':
451 part_name = descriptor['Partition Name']
452 ril = descriptor['Rollback Index Location']
453 part_key = chained_partitions[part_name]
454 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
455 ExtractAvbPubkey(args, part_key, avbpubkey)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900456 cmd.extend(['--chain_partition', f'{part_name}:{ril}:{avbpubkey}'])
Jooyung Han832d11d2021-11-08 12:51:47 +0900457
Jooyung Han98498f42022-02-07 15:23:08 +0900458 if args.signing_args:
459 cmd.extend(shlex.split(args.signing_args))
460
Jooyung Han504105f2021-10-26 15:54:50 +0900461 RunCommand(args, cmd)
Alice Wang34c19232024-01-11 16:06:28 +0000462 check_resigned_image_avb_info(vbmeta_img, info, descriptors, args)
Jooyung Han504105f2021-10-26 15:54:50 +0900463 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
464 # which matches this or the read will fail.
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900465 with open(vbmeta_img, 'a', encoding='utf8') as f:
Jooyung Handcb0b492022-02-26 09:04:17 +0900466 f.truncate(65536)
Jooyung Han504105f2021-10-26 15:54:50 +0900467
468
Jooyung Han486609f2022-04-20 11:38:00 +0900469def UnpackSuperImg(args, super_img, work_dir):
470 tmp_super_img = os.path.join(work_dir, 'super.img')
471 RunCommand(args, ['simg2img', super_img, tmp_super_img])
472 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
Jooyung Han504105f2021-10-26 15:54:50 +0900473
474
475def MakeSuperImage(args, partitions, output):
Jooyung Han486609f2022-04-20 11:38:00 +0900476 with tempfile.TemporaryDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900477 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
478 '--metadata-size=65536', '--sparse', '--output=' + output]
479
480 for part, img in partitions.items():
481 tmp_img = os.path.join(work_dir, part)
482 RunCommand(args, ['img2simg', img, tmp_img])
483
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900484 image_arg = f'--image={part}={img}'
485 partition_arg = f'--partition={part}:readonly:{os.path.getsize(img)}:default'
Jooyung Han504105f2021-10-26 15:54:50 +0900486 cmd.extend([image_arg, partition_arg])
487
488 RunCommand(args, cmd)
489
490
Seungjae Yoo43574482024-01-11 16:27:51 +0900491def GenVbmetaImage(args, image, output, partition_name, salt):
Shikha Panwarc149d242023-01-20 16:23:04 +0000492 cmd = ['avbtool', 'add_hash_footer', '--dynamic_partition_size',
493 '--do_not_append_vbmeta_image',
494 '--partition_name', partition_name,
Seungjae Yoo43574482024-01-11 16:27:51 +0900495 '--salt', salt,
Shikha Panwarc149d242023-01-20 16:23:04 +0000496 '--image', image,
497 '--output_vbmeta_image', output]
498 RunCommand(args, cmd)
499
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900500
Nikita Ioffe3776d612024-07-10 13:21:46 +0000501gki_versions = ['android15-6.6']
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900502
Jooyung Han486609f2022-04-20 11:38:00 +0900503# dict of (key, file) for re-sign/verification. keys are un-versioned for readability.
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900504virt_apex_non_gki_files = {
Shikha Panwara7605cf2023-01-12 09:29:39 +0000505 'kernel': 'etc/fs/microdroid_kernel',
Jooyung Han486609f2022-04-20 11:38:00 +0900506 'vbmeta.img': 'etc/fs/microdroid_vbmeta.img',
Shikha Panwara7605cf2023-01-12 09:29:39 +0000507 'super.img': 'etc/fs/microdroid_super.img',
508 'initrd_normal.img': 'etc/microdroid_initrd_normal.img',
509 'initrd_debuggable.img': 'etc/microdroid_initrd_debuggable.img',
Alice Wangbe8330c2023-10-19 08:55:07 +0000510 'rialto': 'etc/rialto.bin',
Jooyung Han486609f2022-04-20 11:38:00 +0900511}
512
Jooyung Han486609f2022-04-20 11:38:00 +0900513def TargetFiles(input_dir):
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900514 ret = {k: os.path.join(input_dir, v) for k, v in virt_apex_non_gki_files.items()}
515
516 for ver in gki_versions:
517 kernel = os.path.join(input_dir, f'etc/fs/microdroid_gki-{ver}_kernel')
518 initrd_normal = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_normal.img')
519 initrd_debug = os.path.join(input_dir, f'etc/microdroid_gki-{ver}_initrd_debuggable.img')
520
521 if os.path.isfile(kernel):
522 ret[f'gki-{ver}_kernel'] = kernel
523 ret[f'gki-{ver}_initrd_normal.img'] = initrd_normal
524 ret[f'gki-{ver}_initrd_debuggable.img'] = initrd_debug
525
Nikita Ioffef49350e2024-11-01 16:11:48 +0000526 kernel_16k = os.path.join(input_dir, 'etc/fs/microdroid_kernel_16k')
527 initrd_normal_16k = os.path.join(input_dir, 'etc/microdroid_16k_initrd_normal.img')
528 initrd_debug_16k = os.path.join(input_dir, 'etc/microdroid_16k_initrd_debuggable.img')
529 if os.path.isfile(kernel_16k):
530 ret['kernel_16k'] = kernel_16k
531 ret['16k_initrd_normal.img'] = initrd_normal_16k
532 ret['16k_initrd_debuggable.img'] = initrd_debug_16k
533
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900534 return ret
535
536def IsInitrdImage(path):
537 return path.endswith('initrd_normal.img') or path.endswith('initrd_debuggable.img')
Jooyung Han486609f2022-04-20 11:38:00 +0900538
539
Jooyung Han504105f2021-10-26 15:54:50 +0900540def SignVirtApex(args):
541 key = args.key
542 input_dir = args.input_dir
Jooyung Han486609f2022-04-20 11:38:00 +0900543 files = TargetFiles(input_dir)
Jooyung Han504105f2021-10-26 15:54:50 +0900544
Jooyung Han486609f2022-04-20 11:38:00 +0900545 # unpacked files (will be unpacked from super.img below)
546 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Nikita Ioffee1112032023-11-13 15:09:39 +0000547 vendor_a_img = os.path.join(unpack_dir.name, 'vendor_a.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900548
Jooyung Han504105f2021-10-26 15:54:50 +0900549 # re-sign super.img
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900550 # 1. unpack super.img
Nikita Ioffee1112032023-11-13 15:09:39 +0000551 # 2. resign system and vendor (if exists)
552 # 3. repack super.img out of resigned system and vendor (if exists)
Jooyung Hanbae6ce42022-09-13 15:15:18 +0900553 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
554 system_a_f = Async(AddHashTreeFooter, args, key, system_a_img)
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000555 partitions = {"system_a": system_a_img}
Nikita Ioffee1112032023-11-13 15:09:39 +0000556 images = [system_a_img]
557 images_f = [system_a_f]
558
559 # if vendor_a.img exists, resign it
560 if os.path.exists(vendor_a_img):
561 partitions.update({'vendor_a': vendor_a_img})
562 images.append(vendor_a_img)
563 vendor_a_f = Async(AddHashTreeFooter, args, key, vendor_a_img)
564 images_f.append(vendor_a_f)
565
Shikha Panwara7605cf2023-01-12 09:29:39 +0000566 Async(MakeSuperImage, args, partitions,
Nikita Ioffee1112032023-11-13 15:09:39 +0000567 files['super.img'], wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900568
Nikita Ioffebaf578d2023-06-14 20:29:37 +0000569 # re-generate vbmeta from re-signed system_a.img
Shikha Panwara7605cf2023-01-12 09:29:39 +0000570 vbmeta_f = Async(MakeVbmetaImage, args, key, files['vbmeta.img'],
Nikita Ioffee1112032023-11-13 15:09:39 +0000571 images=images,
572 wait=images_f)
Jooyung Han504105f2021-10-26 15:54:50 +0900573
Shikha Panwarc149d242023-01-20 16:23:04 +0000574 vbmeta_bc_f = None
Shikha Panwara7605cf2023-01-12 09:29:39 +0000575 if not args.do_not_update_bootconfigs:
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900576 initrd_files = [v for k, v in files.items() if IsInitrdImage(k)]
Inseob Kim77c7f712023-11-06 17:01:02 +0900577 vbmeta_bc_f = Async(UpdateVbmetaBootconfig, args, initrd_files,
578 files['vbmeta.img'],
Shikha Panwarc149d242023-01-20 16:23:04 +0000579 wait=[vbmeta_f])
Jooyung Han832d11d2021-11-08 12:51:47 +0900580
Shikha Panwarc149d242023-01-20 16:23:04 +0000581 # Re-sign kernel. Note kernel's vbmeta contain addition descriptor from ramdisk(s)
Inseob Kim2e2f48a2024-02-21 22:56:08 +0900582 def resign_decompressed_kernel(kernel_file, initrd_normal_file, initrd_debug_file):
Seungjae Yoo43574482024-01-11 16:27:51 +0900583 _, kernel_image_descriptors = AvbInfo(args, kernel_file)
Alice Wang34c19232024-01-11 16:06:28 +0000584 salts = extract_hash_descriptors(
585 kernel_image_descriptors, lambda descriptor: descriptor['Salt'])
Inseob Kim77c7f712023-11-06 17:01:02 +0900586 initrd_normal_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
587 initrd_debug_hashdesc = tempfile.NamedTemporaryFile(delete=False).name
588 initrd_n_f = Async(GenVbmetaImage, args, initrd_normal_file,
Seungjae Yoo43574482024-01-11 16:27:51 +0900589 initrd_normal_hashdesc, "initrd_normal", salts["initrd_normal"],
Inseob Kim77c7f712023-11-06 17:01:02 +0900590 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
591 initrd_d_f = Async(GenVbmetaImage, args, initrd_debug_file,
Seungjae Yoo43574482024-01-11 16:27:51 +0900592 initrd_debug_hashdesc, "initrd_debug", salts["initrd_debug"],
Inseob Kim77c7f712023-11-06 17:01:02 +0900593 wait=[vbmeta_bc_f] if vbmeta_bc_f is not None else [])
Alice Wang2a6caf12024-01-11 08:14:05 +0000594 return Async(AddHashFooter, args, key, kernel_file,
595 additional_images=[initrd_normal_hashdesc, initrd_debug_hashdesc],
Inseob Kim77c7f712023-11-06 17:01:02 +0900596 wait=[initrd_n_f, initrd_d_f])
597
Inseob Kim2e2f48a2024-02-21 22:56:08 +0900598 def resign_compressed_kernel(kernel_file, initrd_normal_file, initrd_debug_file):
599 # decompress, re-sign, compress again
600 with tempfile.TemporaryDirectory() as work_dir:
601 decompressed_kernel_file = os.path.join(work_dir, os.path.basename(kernel_file))
602 RunCommand(args, ['lz4', '-d', kernel_file, decompressed_kernel_file])
603 resign_decompressed_kernel(decompressed_kernel_file, initrd_normal_file,
604 initrd_debug_file).result()
605 RunCommand(args, ['lz4', '-9', '-f', decompressed_kernel_file, kernel_file])
606
607 def resign_kernel(kernel, initrd_normal, initrd_debug):
608 kernel_file = files[kernel]
609 initrd_normal_file = files[initrd_normal]
610 initrd_debug_file = files[initrd_debug]
611
612 # kernel may be compressed with lz4.
613 if is_lz4(args, kernel_file):
614 return Async(resign_compressed_kernel, kernel_file, initrd_normal_file,
615 initrd_debug_file)
616 else:
617 return resign_decompressed_kernel(kernel_file, initrd_normal_file, initrd_debug_file)
618
Alice Wang2a6caf12024-01-11 08:14:05 +0000619 _, original_kernel_descriptors = AvbInfo(args, files['kernel'])
Alice Wang2d061a22024-02-22 10:57:52 +0000620 resign_kernel_tasks = [resign_kernel('kernel', 'initrd_normal.img', 'initrd_debuggable.img')]
621 original_kernels = {"kernel" : original_kernel_descriptors}
Inseob Kim77c7f712023-11-06 17:01:02 +0900622
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900623 for ver in gki_versions:
624 if f'gki-{ver}_kernel' in files:
Alice Wang2d061a22024-02-22 10:57:52 +0000625 kernel_name = f'gki-{ver}_kernel'
626 _, original_kernel_descriptors = AvbInfo(args, files[kernel_name])
627 task = resign_kernel(
628 kernel_name,
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900629 f'gki-{ver}_initrd_normal.img',
630 f'gki-{ver}_initrd_debuggable.img')
Alice Wang2d061a22024-02-22 10:57:52 +0000631 resign_kernel_tasks.append(task)
632 original_kernels[kernel_name] = original_kernel_descriptors
Jooyung Han832d11d2021-11-08 12:51:47 +0900633
Alice Wangbe8330c2023-10-19 08:55:07 +0000634 # Re-sign rialto if it exists. Rialto only exists in arm64 environment.
635 if os.path.exists(files['rialto']):
Alice Wang34c19232024-01-11 16:06:28 +0000636 update_initrd_digests_task = Async(
Alice Wang2d061a22024-02-22 10:57:52 +0000637 update_initrd_digests_of_kernels_in_rialto, original_kernels, args, files,
638 wait=resign_kernel_tasks)
Alice Wang34c19232024-01-11 16:06:28 +0000639 Async(resign_rialto, args, key, files['rialto'], wait=[update_initrd_digests_task])
Alice Wangbe8330c2023-10-19 08:55:07 +0000640
Alice Wang2a6caf12024-01-11 08:14:05 +0000641def resign_rialto(args, key, rialto_path):
Alice Wang34c19232024-01-11 16:06:28 +0000642 _, original_descriptors = AvbInfo(args, rialto_path)
Alice Wang2a6caf12024-01-11 08:14:05 +0000643 AddHashFooter(args, key, rialto_path)
644
645 # Verify the new AVB footer.
646 updated_info, updated_descriptors = AvbInfo(args, rialto_path)
Alice Wang34c19232024-01-11 16:06:28 +0000647 assert len(updated_descriptors) == 2, \
648 f"There should be two descriptors for rialto. Updated descriptors: {updated_descriptors}"
649 updated_prop = find_all_values_by_key(updated_descriptors, "Prop")
650 assert len(updated_prop) == 1, "There should be only one Prop descriptor for rialto. " \
651 f"Updated descriptors: {updated_descriptors}"
652 assert updated_info["Rollback Index"] != "0", "Rollback index should not be zero for rialto."
653
654 # Verify the only hash descriptor of rialto.
655 updated_hash_descriptors = extract_hash_descriptors(updated_descriptors)
656 assert len(updated_hash_descriptors) == 1, \
657 f"There should be only one hash descriptor for rialto. " \
658 f"Updated hash descriptors: {updated_hash_descriptors}"
Alice Wang2a6caf12024-01-11 08:14:05 +0000659 # Since salt is not updated, the change of digest reflects the change of content of rialto
660 # kernel.
Alice Wang2a6caf12024-01-11 08:14:05 +0000661 if not args.do_not_update_bootconfigs:
Alice Wang34c19232024-01-11 16:06:28 +0000662 [(_, original_descriptor)] = extract_hash_descriptors(original_descriptors).items()
663 [(_, updated_descriptor)] = updated_hash_descriptors.items()
Alice Wang2a6caf12024-01-11 08:14:05 +0000664 assert_different_value(original_descriptor, updated_descriptor, "Digest",
665 "rialto_hash_descriptor")
666
Alice Wang2a6caf12024-01-11 08:14:05 +0000667def assert_different_value(original, updated, key, context):
668 assert original[key] != updated[key], \
669 f"Value of '{key}' should change for '{context}'" \
670 f"Original value: {original[key]}, updated value: {updated[key]}"
671
Alice Wang2d061a22024-02-22 10:57:52 +0000672def update_initrd_digests_of_kernels_in_rialto(original_kernels, args, files):
Alice Wang2a6caf12024-01-11 08:14:05 +0000673 # Update the hashes of initrd_normal and initrd_debug in rialto if the
674 # bootconfigs in them are updated.
675 if args.do_not_update_bootconfigs:
676 return
677
678 with open(files['rialto'], "rb") as file:
679 content = file.read()
680
Alice Wang2d061a22024-02-22 10:57:52 +0000681 for kernel_name, descriptors in original_kernels.items():
682 content = update_initrd_digests_in_rialto(
683 descriptors, args, files, kernel_name, content)
684
685 with open(files['rialto'], "wb") as file:
686 file.write(content)
687
688def update_initrd_digests_in_rialto(
689 original_descriptors, args, files, kernel_name, content):
690 _, updated_descriptors = AvbInfo(args, files[kernel_name])
691
692 original_digests = extract_hash_descriptors(
693 original_descriptors, lambda x: binascii.unhexlify(x['Digest']))
694 updated_digests = extract_hash_descriptors(
695 updated_descriptors, lambda x: binascii.unhexlify(x['Digest']))
696 assert original_digests.pop("boot") == updated_digests.pop("boot"), \
697 "Hash descriptor of boot should not change for " + kernel_name + \
698 f"\nOriginal descriptors: {original_descriptors}, " \
699 f"\nUpdated descriptors: {updated_descriptors}"
700
Alice Wang34c19232024-01-11 16:06:28 +0000701 # Check that the original and updated digests are different before updating rialto.
702 partition_names = {'initrd_normal', 'initrd_debug'}
703 assert set(original_digests.keys()) == set(updated_digests.keys()) == partition_names, \
704 f"Original digests' partitions should be {partition_names}. " \
705 f"Original digests: {original_digests}. Updated digests: {updated_digests}"
706 assert set(original_digests.values()).isdisjoint(updated_digests.values()), \
707 "Digests of initrd_normal and initrd_debug should change. " \
708 f"Original descriptors: {original_descriptors}, " \
709 f"updated descriptors: {updated_descriptors}"
Alice Wang2a6caf12024-01-11 08:14:05 +0000710
Alice Wang34c19232024-01-11 16:06:28 +0000711 for partition_name, original_digest in original_digests.items():
712 updated_digest = updated_digests[partition_name]
Alice Wang2a6caf12024-01-11 08:14:05 +0000713 assert len(original_digest) == len(updated_digest), \
714 f"Length of original_digest and updated_digest must be the same for {partition_name}." \
715 f" Original digest: {original_digest}, updated digest: {updated_digest}"
Alice Wang2a6caf12024-01-11 08:14:05 +0000716
717 new_content = content.replace(original_digest, updated_digest)
718 assert len(new_content) == len(content), \
719 "Length of new_content and content must be the same."
720 assert new_content != content, \
Alice Wang34c19232024-01-11 16:06:28 +0000721 f"original digest of the partition {partition_name} not found."
Alice Wang2a6caf12024-01-11 08:14:05 +0000722 content = new_content
723
Alice Wang2d061a22024-02-22 10:57:52 +0000724 return content
Alice Wang2a6caf12024-01-11 08:14:05 +0000725
Alice Wang34c19232024-01-11 16:06:28 +0000726def extract_hash_descriptors(descriptors, f=lambda x: x):
727 return {desc["Partition Name"]: f(desc) for desc in
728 find_all_values_by_key(descriptors, "Hash descriptor")}
Jooyung Han504105f2021-10-26 15:54:50 +0900729
Jooyung Han02dceed2021-11-08 17:50:22 +0900730def VerifyVirtApex(args):
Jooyung Han486609f2022-04-20 11:38:00 +0900731 key = args.key
732 input_dir = args.input_dir
733 files = TargetFiles(input_dir)
Jooyung Han02dceed2021-11-08 17:50:22 +0900734
Jooyung Han486609f2022-04-20 11:38:00 +0900735 # unpacked files
736 UnpackSuperImg(args, files['super.img'], unpack_dir.name)
737 system_a_img = os.path.join(unpack_dir.name, 'system_a.img')
Jooyung Han02dceed2021-11-08 17:50:22 +0900738
Jooyung Han486609f2022-04-20 11:38:00 +0900739 # Read pubkey digest from the input key
740 with tempfile.NamedTemporaryFile() as pubkey_file:
741 ExtractAvbPubkey(args, key, pubkey_file.name)
742 with open(pubkey_file.name, 'rb') as f:
743 pubkey = f.read()
744 pubkey_digest = hashlib.sha1(pubkey).hexdigest()
Jooyung Han02dceed2021-11-08 17:50:22 +0900745
Jooyung Han486609f2022-04-20 11:38:00 +0900746 def check_avb_pubkey(file):
747 info, _ = AvbInfo(args, file)
Jiyong Park40bf2dc2022-05-23 23:41:25 +0900748 assert info is not None, f'no avbinfo: {file}'
749 assert info['Public key (sha1)'] == pubkey_digest, f'pubkey mismatch: {file}'
Jooyung Han486609f2022-04-20 11:38:00 +0900750
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900751 for k, f in files.items():
752 if IsInitrdImage(k):
Shikha Panwara7605cf2023-01-12 09:29:39 +0000753 # TODO(b/245277660): Verify that ramdisks contain the correct vbmeta digest
754 continue
Alice Wangbe8330c2023-10-19 08:55:07 +0000755 if k == 'rialto' and not os.path.exists(f):
756 # Rialto only exists in arm64 environment.
757 continue
Inseob Kim7a1fc8f2023-11-22 18:45:28 +0900758 if k == 'super.img':
Jooyung Han486609f2022-04-20 11:38:00 +0900759 Async(check_avb_pubkey, system_a_img)
Jooyung Han486609f2022-04-20 11:38:00 +0900760 else:
761 # Check pubkey for other files using avbtool
762 Async(check_avb_pubkey, f)
Jooyung Han02dceed2021-11-08 17:50:22 +0900763
764
Jooyung Han504105f2021-10-26 15:54:50 +0900765def main(argv):
766 try:
767 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900768 if args.verify:
769 VerifyVirtApex(args)
770 else:
771 SignVirtApex(args)
Jooyung Han486609f2022-04-20 11:38:00 +0900772 # ensure all tasks are completed without exceptions
773 AwaitAll(tasks)
Shikha Panwara7605cf2023-01-12 09:29:39 +0000774 except: # pylint: disable=bare-except
Jooyung Han486609f2022-04-20 11:38:00 +0900775 traceback.print_exc()
Jooyung Han504105f2021-10-26 15:54:50 +0900776 sys.exit(1)
777
778
779if __name__ == '__main__':
780 main(sys.argv[1:])