blob: 9a0fe1a9bacd6d885b09fc537ed36a19acfc9c4a [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
18Typical usage: sign_virt_apex [-v] [--avbtool path_to_avbtool] path_to_key payload_contents_dir
19
20sign_virt_apex uses external tools which are assumed to be available via PATH.
21- avbtool (--avbtool can override the tool)
22- lpmake, lpunpack, simg2img, img2simg
23"""
24import argparse
Jooyung Han02dceed2021-11-08 17:50:22 +090025import glob
26import hashlib
Jooyung Han504105f2021-10-26 15:54:50 +090027import os
28import re
29import shutil
30import subprocess
31import sys
32import tempfile
33
34
35def ParseArgs(argv):
36 parser = argparse.ArgumentParser(description='Sign the Virt APEX')
Jooyung Han02dceed2021-11-08 17:50:22 +090037 parser.add_argument('--verify', action='store_true',
38 help='Verify the Virt APEX')
Jooyung Han504105f2021-10-26 15:54:50 +090039 parser.add_argument(
40 '-v', '--verbose',
41 action='store_true',
42 help='verbose execution')
43 parser.add_argument(
44 '--avbtool',
45 default='avbtool',
46 help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.')
47 parser.add_argument(
48 'key',
49 help='path to the private key file.')
50 parser.add_argument(
51 'input_dir',
52 help='the directory having files to be packaged')
53 return parser.parse_args(argv)
54
55
56def RunCommand(args, cmd, env=None, expected_return_values={0}):
57 env = env or {}
58 env.update(os.environ.copy())
59
60 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
61 # e.g. sign_apex.py, sign_target_files_apk.py
62 if cmd[0] == 'avbtool':
63 cmd[0] = args.avbtool
64
65 if args.verbose:
66 print('Running: ' + ' '.join(cmd))
67 p = subprocess.Popen(
68 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
69 output, _ = p.communicate()
70
71 if args.verbose or p.returncode not in expected_return_values:
72 print(output.rstrip())
73
74 assert p.returncode in expected_return_values, (
75 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
76 return (output, p.returncode)
77
78
79def ReadBytesSize(value):
80 return int(value.removesuffix(' bytes'))
81
82
Jooyung Han832d11d2021-11-08 12:51:47 +090083def ExtractAvbPubkey(args, key, output):
84 RunCommand(args, ['avbtool', 'extract_public_key',
85 '--key', key, '--output', output])
86
87
88def AvbInfo(args, image_path):
Jooyung Han504105f2021-10-26 15:54:50 +090089 """Parses avbtool --info image output
90
91 Args:
92 args: program arguments.
93 image_path: The path to the image.
94 descriptor_name: Descriptor name of interest.
95
96 Returns:
97 A pair of
98 - a dict that contains VBMeta info. None if there's no VBMeta info.
Jooyung Han832d11d2021-11-08 12:51:47 +090099 - a list of descriptors.
Jooyung Han504105f2021-10-26 15:54:50 +0900100 """
101 if not os.path.exists(image_path):
102 raise ValueError('Failed to find image: {}'.format(image_path))
103
104 output, ret_code = RunCommand(
105 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
106 if ret_code == 1:
107 return None, None
108
Jooyung Han832d11d2021-11-08 12:51:47 +0900109 info, descriptors = {}, []
Jooyung Han504105f2021-10-26 15:54:50 +0900110
111 # Read `avbtool info_image` output as "key:value" lines
112 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
113
114 def IterateLine(output):
115 for line in output.split('\n'):
116 line_info = matcher.match(line)
117 if not line_info:
118 continue
119 yield line_info.group(1), line_info.group(2), line_info.group(3)
120
121 gen = IterateLine(output)
Jooyung Han832d11d2021-11-08 12:51:47 +0900122
123 def ReadDescriptors(cur_indent, cur_name, cur_value):
124 descriptor = cur_value if cur_name == 'Prop' else {}
125 descriptors.append((cur_name, descriptor))
126 for indent, key, value in gen:
127 if indent <= cur_indent:
128 # read descriptors recursively to pass the read key as descriptor name
129 ReadDescriptors(indent, key, value)
130 break
131 descriptor[key] = value
132
Jooyung Han504105f2021-10-26 15:54:50 +0900133 # Read VBMeta info
134 for _, key, value in gen:
135 if key == 'Descriptors':
Jooyung Han832d11d2021-11-08 12:51:47 +0900136 ReadDescriptors(*next(gen))
Jooyung Han504105f2021-10-26 15:54:50 +0900137 break
138 info[key] = value
139
Jooyung Han832d11d2021-11-08 12:51:47 +0900140 return info, descriptors
Jooyung Han504105f2021-10-26 15:54:50 +0900141
Jooyung Han832d11d2021-11-08 12:51:47 +0900142
143# Look up a list of (key, value) with a key. Returns the value of the first matching pair.
144def LookUp(pairs, key):
145 for k, v in pairs:
146 if key == k:
147 return v
148 return None
Jooyung Han504105f2021-10-26 15:54:50 +0900149
150
151def AddHashFooter(args, key, image_path):
Jooyung Han832d11d2021-11-08 12:51:47 +0900152 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900153 if info:
Jooyung Han832d11d2021-11-08 12:51:47 +0900154 descriptor = LookUp(descriptors, 'Hash descriptor')
Jooyung Han504105f2021-10-26 15:54:50 +0900155 image_size = ReadBytesSize(info['Image size'])
156 algorithm = info['Algorithm']
157 partition_name = descriptor['Partition Name']
158 partition_size = str(image_size)
159
160 cmd = ['avbtool', 'add_hash_footer',
161 '--key', key,
162 '--algorithm', algorithm,
163 '--partition_name', partition_name,
164 '--partition_size', partition_size,
165 '--image', image_path]
166 RunCommand(args, cmd)
167
168
169def AddHashTreeFooter(args, key, image_path):
Jooyung Han832d11d2021-11-08 12:51:47 +0900170 info, descriptors = AvbInfo(args, image_path)
Jooyung Han504105f2021-10-26 15:54:50 +0900171 if info:
Jooyung Han832d11d2021-11-08 12:51:47 +0900172 descriptor = LookUp(descriptors, 'Hashtree descriptor')
Jooyung Han504105f2021-10-26 15:54:50 +0900173 image_size = ReadBytesSize(info['Image size'])
174 algorithm = info['Algorithm']
175 partition_name = descriptor['Partition Name']
176 partition_size = str(image_size)
177
178 cmd = ['avbtool', 'add_hashtree_footer',
179 '--key', key,
180 '--algorithm', algorithm,
181 '--partition_name', partition_name,
182 '--partition_size', partition_size,
183 '--do_not_generate_fec',
184 '--image', image_path]
185 RunCommand(args, cmd)
186
187
Jooyung Han832d11d2021-11-08 12:51:47 +0900188def MakeVbmetaImage(args, key, vbmeta_img, images=None, chained_partitions=None):
189 info, descriptors = AvbInfo(args, vbmeta_img)
190 if info is None:
191 return
192
193 with TempDirectory() as work_dir:
Jooyung Han504105f2021-10-26 15:54:50 +0900194 algorithm = info['Algorithm']
195 rollback_index = info['Rollback Index']
196 rollback_index_location = info['Rollback Index Location']
197
198 cmd = ['avbtool', 'make_vbmeta_image',
199 '--key', key,
200 '--algorithm', algorithm,
201 '--rollback_index', rollback_index,
202 '--rollback_index_location', rollback_index_location,
203 '--output', vbmeta_img]
Jooyung Han832d11d2021-11-08 12:51:47 +0900204 if images:
205 for img in images:
206 cmd.extend(['--include_descriptors_from_image', img])
207
208 # replace pubkeys of chained_partitions as well
209 for name, descriptor in descriptors:
210 if name == 'Chain Partition descriptor':
211 part_name = descriptor['Partition Name']
212 ril = descriptor['Rollback Index Location']
213 part_key = chained_partitions[part_name]
214 avbpubkey = os.path.join(work_dir, part_name + '.avbpubkey')
215 ExtractAvbPubkey(args, part_key, avbpubkey)
216 cmd.extend(['--chain_partition', '%s:%s:%s' %
217 (part_name, ril, avbpubkey)])
218
Jooyung Han504105f2021-10-26 15:54:50 +0900219 RunCommand(args, cmd)
220 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
221 # which matches this or the read will fail.
222 RunCommand(args, ['truncate', '-s', '65536', vbmeta_img])
223
224
225class TempDirectory(object):
226
227 def __enter__(self):
228 self.name = tempfile.mkdtemp()
229 return self.name
230
231 def __exit__(self, *unused):
232 shutil.rmtree(self.name)
233
234
235def MakeSuperImage(args, partitions, output):
236 with TempDirectory() as work_dir:
237 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
238 '--metadata-size=65536', '--sparse', '--output=' + output]
239
240 for part, img in partitions.items():
241 tmp_img = os.path.join(work_dir, part)
242 RunCommand(args, ['img2simg', img, tmp_img])
243
244 image_arg = '--image=%s=%s' % (part, img)
245 partition_arg = '--partition=%s:readonly:%d:default' % (
246 part, os.path.getsize(img))
247 cmd.extend([image_arg, partition_arg])
248
249 RunCommand(args, cmd)
250
251
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900252def ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey):
253 # read old pubkey before replacement
254 with open(bootloader_pubkey, 'rb') as f:
255 old_pubkey = f.read()
256
Jooyung Han832d11d2021-11-08 12:51:47 +0900257 # replace bootloader pubkey (overwrite the old one with the new one)
258 ExtractAvbPubkey(args, key, bootloader_pubkey)
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900259
260 # read new pubkey
261 with open(bootloader_pubkey, 'rb') as f:
262 new_pubkey = f.read()
263
264 assert len(old_pubkey) == len(new_pubkey)
265
266 # replace pubkey embedded in bootloader
267 with open(bootloader, 'r+b') as bl_f:
268 pos = bl_f.read().find(old_pubkey)
269 assert pos != -1
270 bl_f.seek(pos)
271 bl_f.write(new_pubkey)
272
273
Jooyung Han504105f2021-10-26 15:54:50 +0900274def SignVirtApex(args):
275 key = args.key
276 input_dir = args.input_dir
277
278 # target files in the Virt APEX
Jooyung Han832d11d2021-11-08 12:51:47 +0900279 bootloader_pubkey = os.path.join(
280 input_dir, 'etc', 'microdroid_bootloader.avbpubkey')
Jooyung Han504105f2021-10-26 15:54:50 +0900281 bootloader = os.path.join(input_dir, 'etc', 'microdroid_bootloader')
282 boot_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_boot-5.10.img')
283 vendor_boot_img = os.path.join(
284 input_dir, 'etc', 'fs', 'microdroid_vendor_boot-5.10.img')
Jiyong Park01597312022-01-06 14:38:29 +0900285 init_boot_img = os.path.join(
286 input_dir, 'etc', 'fs', 'microdroid_init_boot.img')
Jooyung Han504105f2021-10-26 15:54:50 +0900287 super_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_super.img')
288 vbmeta_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_vbmeta.img')
Jooyung Han832d11d2021-11-08 12:51:47 +0900289 vbmeta_bootconfig_img = os.path.join(
290 input_dir, 'etc', 'fs', 'microdroid_vbmeta_bootconfig.img')
291 bootconfig_normal = os.path.join(
292 input_dir, 'etc', 'microdroid_bootconfig.normal')
293 bootconfig_app_debuggable = os.path.join(
294 input_dir, 'etc', 'microdroid_bootconfig.app_debuggable')
295 bootconfig_full_debuggable = os.path.join(
296 input_dir, 'etc', 'microdroid_bootconfig.full_debuggable')
Jooyung Han504105f2021-10-26 15:54:50 +0900297
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900298 # Key(pubkey) for bootloader should match with the one used to make VBmeta below
299 # while it's okay to use different keys for other image files.
300 ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey)
301
Jiyong Park01597312022-01-06 14:38:29 +0900302 # re-sign bootloader, boot.img, vendor_boot.img, and init_boot.img
Jooyung Han504105f2021-10-26 15:54:50 +0900303 AddHashFooter(args, key, bootloader)
304 AddHashFooter(args, key, boot_img)
305 AddHashFooter(args, key, vendor_boot_img)
Jiyong Park01597312022-01-06 14:38:29 +0900306 AddHashFooter(args, key, init_boot_img)
Jooyung Han504105f2021-10-26 15:54:50 +0900307
308 # re-sign super.img
309 with TempDirectory() as work_dir:
310 # unpack super.img
311 tmp_super_img = os.path.join(work_dir, 'super.img')
312 RunCommand(args, ['simg2img', super_img, tmp_super_img])
313 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
314
315 system_a_img = os.path.join(work_dir, 'system_a.img')
316 vendor_a_img = os.path.join(work_dir, 'vendor_a.img')
317 partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img}
318
319 # re-sign partitions in super.img
320 for img in partitions.values():
321 AddHashTreeFooter(args, key, img)
322
323 # re-pack super.img
324 MakeSuperImage(args, partitions, super_img)
325
Jiyong Park01597312022-01-06 14:38:29 +0900326 # re-generate vbmeta from re-signed {boot, vendor_boot, init_boot, system_a, vendor_a}.img
Jooyung Han504105f2021-10-26 15:54:50 +0900327 # Ideally, making VBmeta should be done out of TempDirectory block. But doing it here
328 # to avoid unpacking re-signed super.img for system/vendor images which are available
329 # in this block.
Jooyung Han832d11d2021-11-08 12:51:47 +0900330 MakeVbmetaImage(args, key, vbmeta_img, images=[
Jiyong Park01597312022-01-06 14:38:29 +0900331 boot_img, vendor_boot_img, init_boot_img, system_a_img, vendor_a_img])
Jooyung Han504105f2021-10-26 15:54:50 +0900332
Jooyung Han832d11d2021-11-08 12:51:47 +0900333 # Re-sign bootconfigs with the same key
334 bootconfig_sign_key = key
335 AddHashFooter(args, bootconfig_sign_key, bootconfig_normal)
336 AddHashFooter(args, bootconfig_sign_key, bootconfig_app_debuggable)
337 AddHashFooter(args, bootconfig_sign_key, bootconfig_full_debuggable)
338
339 # Re-sign vbmeta_bootconfig with a chained_partition to "bootconfig"
340 # Note that, for now, `key` and `bootconfig_sign_key` are the same, but technically they
341 # can be different. Vbmeta records pubkeys which signed chained partitions.
342 MakeVbmetaImage(args, key, vbmeta_bootconfig_img, chained_partitions={
343 'bootconfig': bootconfig_sign_key})
344
Jooyung Han504105f2021-10-26 15:54:50 +0900345
Jooyung Han02dceed2021-11-08 17:50:22 +0900346def VerifyVirtApex(args):
347 # Generator to emit avbtool-signed items along with its pubkey digest.
348 # This supports lpmake-packed images as well.
349 def Recur(target_dir):
350 for file in glob.glob(os.path.join(target_dir, 'etc', '**', '*'), recursive=True):
351 cur_item = os.path.relpath(file, target_dir)
352
353 if not os.path.isfile(file):
354 continue
355
356 # avbpubkey
357 if cur_item == 'etc/microdroid_bootloader.avbpubkey':
358 with open(file, 'rb') as f:
359 yield (cur_item, hashlib.sha1(f.read()).hexdigest())
360 continue
361
362 # avbtool signed
363 info, _ = AvbInfo(args, file)
364 if info:
365 yield (cur_item, info['Public key (sha1)'])
366 continue
367
368 # logical partition
369 with TempDirectory() as tmp_dir:
370 unsparsed = os.path.join(tmp_dir, os.path.basename(file))
371 _, rc = RunCommand(
372 # exit with 255 if it's not sparsed
373 args, ['simg2img', file, unsparsed], expected_return_values={0, 255})
374 if rc == 0:
375 with TempDirectory() as unpack_dir:
376 # exit with 64 if it's not a logical partition.
377 _, rc = RunCommand(
378 args, ['lpunpack', unsparsed, unpack_dir], expected_return_values={0, 64})
379 if rc == 0:
380 nested_items = list(Recur(unpack_dir))
381 if len(nested_items) > 0:
382 for (item, key) in nested_items:
383 yield ('%s!/%s' % (cur_item, item), key)
384 continue
385 # Read pubkey digest
386 with TempDirectory() as tmp_dir:
387 pubkey_file = os.path.join(tmp_dir, 'avbpubkey')
388 ExtractAvbPubkey(args, args.key, pubkey_file)
389 with open(pubkey_file, 'rb') as f:
390 pubkey_digest = hashlib.sha1(f.read()).hexdigest()
391
392 # Check every avbtool-signed item against the input key
393 for (item, pubkey) in Recur(args.input_dir):
394 assert pubkey == pubkey_digest, '%s: key mismatch: %s != %s' % (
395 item, pubkey, pubkey_digest)
396
397
Jooyung Han504105f2021-10-26 15:54:50 +0900398def main(argv):
399 try:
400 args = ParseArgs(argv)
Jooyung Han02dceed2021-11-08 17:50:22 +0900401 if args.verify:
402 VerifyVirtApex(args)
403 else:
404 SignVirtApex(args)
Jooyung Han504105f2021-10-26 15:54:50 +0900405 except Exception as e:
406 print(e)
407 sys.exit(1)
408
409
410if __name__ == '__main__':
411 main(sys.argv[1:])