blob: 77f54c480665fb188100063b11d2e2959b878a82 [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
25import os
26import re
27import shutil
28import subprocess
29import sys
30import tempfile
31
32
33def ParseArgs(argv):
34 parser = argparse.ArgumentParser(description='Sign the Virt APEX')
35 parser.add_argument(
36 '-v', '--verbose',
37 action='store_true',
38 help='verbose execution')
39 parser.add_argument(
40 '--avbtool',
41 default='avbtool',
42 help='Optional flag that specifies the AVB tool to use. Defaults to `avbtool`.')
43 parser.add_argument(
44 'key',
45 help='path to the private key file.')
46 parser.add_argument(
47 'input_dir',
48 help='the directory having files to be packaged')
49 return parser.parse_args(argv)
50
51
52def RunCommand(args, cmd, env=None, expected_return_values={0}):
53 env = env or {}
54 env.update(os.environ.copy())
55
56 # TODO(b/193504286): we need a way to find other tool (cmd[0]) in various contexts
57 # e.g. sign_apex.py, sign_target_files_apk.py
58 if cmd[0] == 'avbtool':
59 cmd[0] = args.avbtool
60
61 if args.verbose:
62 print('Running: ' + ' '.join(cmd))
63 p = subprocess.Popen(
64 cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True)
65 output, _ = p.communicate()
66
67 if args.verbose or p.returncode not in expected_return_values:
68 print(output.rstrip())
69
70 assert p.returncode in expected_return_values, (
71 '%d Failed to execute: ' + ' '.join(cmd)) % p.returncode
72 return (output, p.returncode)
73
74
75def ReadBytesSize(value):
76 return int(value.removesuffix(' bytes'))
77
78
79def AvbInfo(args, image_path, descriptor_name=None):
80 """Parses avbtool --info image output
81
82 Args:
83 args: program arguments.
84 image_path: The path to the image.
85 descriptor_name: Descriptor name of interest.
86
87 Returns:
88 A pair of
89 - a dict that contains VBMeta info. None if there's no VBMeta info.
90 - a dict that contains target descriptor info. None if name is not specified or not found.
91 """
92 if not os.path.exists(image_path):
93 raise ValueError('Failed to find image: {}'.format(image_path))
94
95 output, ret_code = RunCommand(
96 args, ['avbtool', 'info_image', '--image', image_path], expected_return_values={0, 1})
97 if ret_code == 1:
98 return None, None
99
100 info, descriptor = {}, None
101
102 # Read `avbtool info_image` output as "key:value" lines
103 matcher = re.compile(r'^(\s*)([^:]+):\s*(.*)$')
104
105 def IterateLine(output):
106 for line in output.split('\n'):
107 line_info = matcher.match(line)
108 if not line_info:
109 continue
110 yield line_info.group(1), line_info.group(2), line_info.group(3)
111
112 gen = IterateLine(output)
113 # Read VBMeta info
114 for _, key, value in gen:
115 if key == 'Descriptors':
116 break
117 info[key] = value
118
119 if descriptor_name:
120 for indent, key, _ in gen:
121 # Read a target descriptor
122 if key == descriptor_name:
123 cur_indent = indent
124 descriptor = {}
125 for indent, key, value in gen:
126 if indent == cur_indent:
127 break
128 descriptor[key] = value
129 break
130
131 return info, descriptor
132
133
134def AddHashFooter(args, key, image_path):
135 info, descriptor = AvbInfo(args, image_path, 'Hash descriptor')
136 if info:
137 image_size = ReadBytesSize(info['Image size'])
138 algorithm = info['Algorithm']
139 partition_name = descriptor['Partition Name']
140 partition_size = str(image_size)
141
142 cmd = ['avbtool', 'add_hash_footer',
143 '--key', key,
144 '--algorithm', algorithm,
145 '--partition_name', partition_name,
146 '--partition_size', partition_size,
147 '--image', image_path]
148 RunCommand(args, cmd)
149
150
151def AddHashTreeFooter(args, key, image_path):
152 info, descriptor = AvbInfo(args, image_path, 'Hashtree descriptor')
153 if info:
154 image_size = ReadBytesSize(info['Image size'])
155 algorithm = info['Algorithm']
156 partition_name = descriptor['Partition Name']
157 partition_size = str(image_size)
158
159 cmd = ['avbtool', 'add_hashtree_footer',
160 '--key', key,
161 '--algorithm', algorithm,
162 '--partition_name', partition_name,
163 '--partition_size', partition_size,
164 '--do_not_generate_fec',
165 '--image', image_path]
166 RunCommand(args, cmd)
167
168
169def MakeVbmetaImage(args, key, vbmeta_img, images):
170 info, _ = AvbInfo(args, vbmeta_img)
171 if info:
172 algorithm = info['Algorithm']
173 rollback_index = info['Rollback Index']
174 rollback_index_location = info['Rollback Index Location']
175
176 cmd = ['avbtool', 'make_vbmeta_image',
177 '--key', key,
178 '--algorithm', algorithm,
179 '--rollback_index', rollback_index,
180 '--rollback_index_location', rollback_index_location,
181 '--output', vbmeta_img]
182 for img in images:
183 cmd.extend(['--include_descriptors_from_image', img])
184 RunCommand(args, cmd)
185 # libavb expects to be able to read the maximum vbmeta size, so we must provide a partition
186 # which matches this or the read will fail.
187 RunCommand(args, ['truncate', '-s', '65536', vbmeta_img])
188
189
190class TempDirectory(object):
191
192 def __enter__(self):
193 self.name = tempfile.mkdtemp()
194 return self.name
195
196 def __exit__(self, *unused):
197 shutil.rmtree(self.name)
198
199
200def MakeSuperImage(args, partitions, output):
201 with TempDirectory() as work_dir:
202 cmd = ['lpmake', '--device-size=auto', '--metadata-slots=2', # A/B
203 '--metadata-size=65536', '--sparse', '--output=' + output]
204
205 for part, img in partitions.items():
206 tmp_img = os.path.join(work_dir, part)
207 RunCommand(args, ['img2simg', img, tmp_img])
208
209 image_arg = '--image=%s=%s' % (part, img)
210 partition_arg = '--partition=%s:readonly:%d:default' % (
211 part, os.path.getsize(img))
212 cmd.extend([image_arg, partition_arg])
213
214 RunCommand(args, cmd)
215
216
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900217def ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey):
218 # read old pubkey before replacement
219 with open(bootloader_pubkey, 'rb') as f:
220 old_pubkey = f.read()
221
222 # replace bootloader pubkey
223 RunCommand(args, ['avbtool', 'extract_public_key', '--key', key, '--output', bootloader_pubkey])
224
225 # read new pubkey
226 with open(bootloader_pubkey, 'rb') as f:
227 new_pubkey = f.read()
228
229 assert len(old_pubkey) == len(new_pubkey)
230
231 # replace pubkey embedded in bootloader
232 with open(bootloader, 'r+b') as bl_f:
233 pos = bl_f.read().find(old_pubkey)
234 assert pos != -1
235 bl_f.seek(pos)
236 bl_f.write(new_pubkey)
237
238
Jooyung Han504105f2021-10-26 15:54:50 +0900239def SignVirtApex(args):
240 key = args.key
241 input_dir = args.input_dir
242
243 # target files in the Virt APEX
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900244 bootloader_pubkey = os.path.join(input_dir, 'etc', 'microdroid_bootloader.avbpubkey')
Jooyung Han504105f2021-10-26 15:54:50 +0900245 bootloader = os.path.join(input_dir, 'etc', 'microdroid_bootloader')
246 boot_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_boot-5.10.img')
247 vendor_boot_img = os.path.join(
248 input_dir, 'etc', 'fs', 'microdroid_vendor_boot-5.10.img')
249 super_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_super.img')
250 vbmeta_img = os.path.join(input_dir, 'etc', 'fs', 'microdroid_vbmeta.img')
251
Jooyung Han31b1c2b2021-10-27 03:35:42 +0900252 # Key(pubkey) for bootloader should match with the one used to make VBmeta below
253 # while it's okay to use different keys for other image files.
254 ReplaceBootloaderPubkey(args, key, bootloader, bootloader_pubkey)
255
Jooyung Han504105f2021-10-26 15:54:50 +0900256 # re-sign bootloader, boot.img, vendor_boot.img
257 AddHashFooter(args, key, bootloader)
258 AddHashFooter(args, key, boot_img)
259 AddHashFooter(args, key, vendor_boot_img)
260
261 # re-sign super.img
262 with TempDirectory() as work_dir:
263 # unpack super.img
264 tmp_super_img = os.path.join(work_dir, 'super.img')
265 RunCommand(args, ['simg2img', super_img, tmp_super_img])
266 RunCommand(args, ['lpunpack', tmp_super_img, work_dir])
267
268 system_a_img = os.path.join(work_dir, 'system_a.img')
269 vendor_a_img = os.path.join(work_dir, 'vendor_a.img')
270 partitions = {"system_a": system_a_img, "vendor_a": vendor_a_img}
271
272 # re-sign partitions in super.img
273 for img in partitions.values():
274 AddHashTreeFooter(args, key, img)
275
276 # re-pack super.img
277 MakeSuperImage(args, partitions, super_img)
278
279 # re-generate vbmeta from re-signed {boot, vendor_boot, system_a, vendor_a}.img
280 # Ideally, making VBmeta should be done out of TempDirectory block. But doing it here
281 # to avoid unpacking re-signed super.img for system/vendor images which are available
282 # in this block.
283 MakeVbmetaImage(args, key, vbmeta_img, [
284 boot_img, vendor_boot_img, system_a_img, vendor_a_img])
285
286
287def main(argv):
288 try:
289 args = ParseArgs(argv)
290 SignVirtApex(args)
291 except Exception as e:
292 print(e)
293 sys.exit(1)
294
295
296if __name__ == '__main__':
297 main(sys.argv[1:])