blob: 1b0b89a2cc7038e3e4cd234ba4c722dcf57d420b [file] [log] [blame]
Tao Bao1cd59f22019-03-15 15:13:01 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2019 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
17import logging
18import os.path
19import re
20import shlex
Tianjie Xu88a759d2020-01-23 10:47:54 -080021import shutil
Tao Baoe7354ba2019-05-09 16:54:15 -070022import zipfile
Tao Bao1cd59f22019-03-15 15:13:01 -070023
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000024import apex_manifest
Tao Bao1cd59f22019-03-15 15:13:01 -070025import common
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000026from common import UnzipTemp, RunAndCheckOutput, MakeTempFile, OPTIONS
27
28import ota_metadata_pb2
29
Tao Bao1cd59f22019-03-15 15:13:01 -070030
31logger = logging.getLogger(__name__)
32
Tao Baoe7354ba2019-05-09 16:54:15 -070033OPTIONS = common.OPTIONS
34
Tianjiec180a5d2020-03-23 18:14:09 -070035APEX_PAYLOAD_IMAGE = 'apex_payload.img'
36
Nikita Ioffe36081482021-01-20 01:32:28 +000037APEX_PUBKEY = 'apex_pubkey'
38
Tao Bao1cd59f22019-03-15 15:13:01 -070039
40class ApexInfoError(Exception):
41 """An Exception raised during Apex Information command."""
42
43 def __init__(self, message):
44 Exception.__init__(self, message)
45
46
47class ApexSigningError(Exception):
48 """An Exception raised during Apex Payload signing."""
49
50 def __init__(self, message):
51 Exception.__init__(self, message)
52
53
Tianjie Xu88a759d2020-01-23 10:47:54 -080054class ApexApkSigner(object):
Jooyung Han0f5a41d2021-10-27 03:53:21 +090055 """Class to sign the apk files and other files in an apex payload image and repack the apex"""
Tianjie Xu88a759d2020-01-23 10:47:54 -080056
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +000057 def __init__(self, apex_path, key_passwords, codename_to_api_level_map, avbtool=None, sign_tool=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080058 self.apex_path = apex_path
Oleh Cherpake555ab12020-10-05 17:04:59 +030059 if not key_passwords:
60 self.key_passwords = dict()
61 else:
62 self.key_passwords = key_passwords
Tianjie Xu88a759d2020-01-23 10:47:54 -080063 self.codename_to_api_level_map = codename_to_api_level_map
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040064 self.debugfs_path = os.path.join(
65 OPTIONS.search_path, "bin", "debugfs_static")
Dennis Shenf58e5482022-10-10 21:19:46 +000066 self.fsckerofs_path = os.path.join(
67 OPTIONS.search_path, "bin", "fsck.erofs")
Jooyung Han0f5a41d2021-10-27 03:53:21 +090068 self.avbtool = avbtool if avbtool else "avbtool"
69 self.sign_tool = sign_tool
Tianjie Xu88a759d2020-01-23 10:47:54 -080070
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +110071 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Jooyung Han0f5a41d2021-10-27 03:53:21 +090072 """Scans and signs the payload files and repack the apex
Tianjie Xu88a759d2020-01-23 10:47:54 -080073
74 Args:
75 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080076
77 Returns:
78 The repacked apex file containing the signed apk files.
79 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040080 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040081 raise ApexSigningError(
82 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000083 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040084 "Make sure bin/debugfs_static can be found in -p <path>")
Dennis Shenf58e5482022-10-10 21:19:46 +000085 list_cmd = ['deapexer', '--debugfs_path', self.debugfs_path,
Dennis Shena8d11432022-11-07 21:37:06 +000086 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080087 entries_names = common.RunAndCheckOutput(list_cmd).split()
88 apk_entries = [name for name in entries_names if name.endswith('.apk')]
89
90 # No need to sign and repack, return the original apex path.
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +110091 if not apk_entries and self.sign_tool is None:
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +000092 logger.info('No apk file to sign in %s', self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -080093 return self.apex_path
94
95 for entry in apk_entries:
96 apk_name = os.path.basename(entry)
97 if apk_name not in apk_keys:
98 raise ApexSigningError('Failed to find signing keys for apk file {} in'
99 ' apex {}. Use "-e <apkname>=" to specify a key'
100 .format(entry, self.apex_path))
101 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
102 'overlay/']):
103 logger.warning('Apk path does not contain the intended directory name:'
104 ' %s', entry)
105
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +0000106 payload_dir, has_signed_content = self.ExtractApexPayloadAndSignContents(
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100107 apk_entries, apk_keys, payload_key, signing_args)
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900108 if not has_signed_content:
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100109 logger.info('No contents has been signed in %s', self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800110 return self.apex_path
111
Baligh Uddin639b3b72020-03-25 20:50:23 -0700112 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800113
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100114 def ExtractApexPayloadAndSignContents(self, apk_entries, apk_keys, payload_key, signing_args):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800115 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400116 if not os.path.exists(self.debugfs_path):
117 raise ApexSigningError(
118 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000119 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400120 "Make sure bin/debugfs_static can be found in -p <path>")
Dennis Shenf58e5482022-10-10 21:19:46 +0000121 if not os.path.exists(self.fsckerofs_path):
122 raise ApexSigningError(
123 "Couldn't find location of fsck.erofs: " +
124 "Path {} does not exist. ".format(self.fsckerofs_path) +
125 "Make sure bin/fsck.erofs can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800126 payload_dir = common.MakeTempDir()
Dennis Shenf58e5482022-10-10 21:19:46 +0000127 extract_cmd = ['deapexer', '--debugfs_path', self.debugfs_path,
Dennis Shena8d11432022-11-07 21:37:06 +0000128 '--fsckerofs_path', self.fsckerofs_path,
Jooyung Han62949022023-06-14 15:16:34 +0900129 'extract',
Dennis Shenf58e5482022-10-10 21:19:46 +0000130 self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800131 common.RunAndCheckOutput(extract_cmd)
132
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900133 has_signed_content = False
Tianjie Xu88a759d2020-01-23 10:47:54 -0800134 for entry in apk_entries:
135 apk_path = os.path.join(payload_dir, entry)
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100136 assert os.path.exists(self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800137
138 key_name = apk_keys.get(os.path.basename(entry))
139 if key_name in common.SPECIAL_CERT_STRINGS:
140 logger.info('Not signing: %s due to special cert string', apk_path)
141 continue
142
143 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
144 # Rename the unsigned apk and overwrite the original apk path with the
145 # signed apk file.
146 unsigned_apk = common.MakeTempFile()
147 os.rename(apk_path, unsigned_apk)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000148 common.SignFile(
149 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
150 codename_to_api_level_map=self.codename_to_api_level_map)
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900151 has_signed_content = True
152
153 if self.sign_tool:
Jooyung Han8caba5e2021-10-27 03:58:09 +0900154 logger.info('Signing payload contents in apex %s with %s', self.apex_path, self.sign_tool)
Jooyung Han39259ec2022-02-07 15:56:53 +0900155 # Pass avbtool to the custom signing tool
156 cmd = [self.sign_tool, '--avbtool', self.avbtool]
157 # Pass signing_args verbatim which will be forwarded to avbtool (e.g. --signing_helper=...)
158 if signing_args:
159 cmd.extend(['--signing_args', '"{}"'.format(signing_args)])
160 cmd.extend([payload_key, payload_dir])
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900161 common.RunAndCheckOutput(cmd)
162 has_signed_content = True
163
164 return payload_dir, has_signed_content
Tianjie Xu88a759d2020-01-23 10:47:54 -0800165
Baligh Uddin639b3b72020-03-25 20:50:23 -0700166 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800167 """Rebuilds the apex file with the updated payload directory."""
168 apex_dir = common.MakeTempDir()
169 # Extract the apex file and reuse its meta files as repack parameters.
170 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800171 arguments_dict = {
172 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
173 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800174 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800175 }
176 for filename in arguments_dict.values():
177 assert os.path.exists(filename), 'file {} not found'.format(filename)
178
179 # The repack process will add back these files later in the payload image.
180 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
181 path = os.path.join(payload_dir, name)
182 if os.path.isfile(path):
183 os.remove(path)
184 elif os.path.isdir(path):
Baligh Uddinbe2d7d02022-02-26 02:34:06 +0000185 shutil.rmtree(path, ignore_errors=True)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800186
Tianjiec180a5d2020-03-23 18:14:09 -0700187 # TODO(xunchang) the signing process can be improved by using
188 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
189 # the signing arguments, e.g. algorithm, salt, etc.
190 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
191 generate_image_cmd = ['apexer', '--force', '--payload_only',
192 '--do_not_check_keyname', '--apexer_tool_path',
193 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800194 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700195 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700196
197 # Add quote to the signing_args as we will pass
198 # --signing_args "--signing_helper_with_files=%path" to apexer
199 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400200 generate_image_cmd.extend(
Hieu Nguyen5ebc4fe2024-08-15 13:35:20 -0400201 ['--signing_args', signing_args])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700202
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800203 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800204 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
205 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700206 generate_image_cmd.extend(['--manifest_json', manifest_json])
207 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800208 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700209 generate_image_cmd.append('-v')
210 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800211
Tianjiec180a5d2020-03-23 18:14:09 -0700212 # Add the payload image back to the apex file.
213 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400214 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700215 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
216 compress_type=zipfile.ZIP_STORED)
217 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800218
219
Tao Bao1ac886e2019-06-26 11:58:22 -0700220def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900221 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700222 """Signs a given payload_file with the payload key."""
223 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700224 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700225 '--do_not_generate_fec',
226 '--algorithm', algorithm,
227 '--key', payload_key_path,
228 '--prop', 'apex.key:{}'.format(payload_key_name),
229 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900230 '--salt', salt,
231 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700232 if no_hashtree:
233 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700234 if signing_args:
235 cmd.extend(shlex.split(signing_args))
236
237 try:
238 common.RunAndCheckOutput(cmd)
239 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700240 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700241 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700242 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700243
244 # Verify the signed payload image with specified public key.
245 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700246 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700247
248
Tao Bao448004a2019-09-19 07:55:02 -0700249def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700250 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700251 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700252 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700253 if no_hashtree:
254 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700255 try:
256 common.RunAndCheckOutput(cmd)
257 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700258 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700259 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700260 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700261
262
Tao Bao1ac886e2019-06-26 11:58:22 -0700263def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700264 """Parses the APEX payload info.
265
266 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700267 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700268 payload_path: The path to the payload image.
269
270 Raises:
271 ApexInfoError on parsing errors.
272
273 Returns:
274 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700275 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700276 """
277 if not os.path.exists(payload_path):
278 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
279
Tao Bao1ac886e2019-06-26 11:58:22 -0700280 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700281 try:
282 output = common.RunAndCheckOutput(cmd)
283 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700284 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700285 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700286 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700287
Jiyong Parka1887f32020-05-19 23:18:03 +0900288 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
289 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700290 # Algorithm: SHA256_RSA4096
291 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900292 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700293 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
294
295 payload_info = {}
296 for line in output.split('\n'):
297 line_info = payload_info_matcher.match(line)
298 if not line_info:
299 continue
300
301 key, value = line_info.group('key'), line_info.group('value')
302
303 if key == 'Prop':
304 # Further extract the property key-value pair, from a 'Prop:' line. For
305 # example,
306 # Prop: apex.key -> 'com.android.runtime'
307 # Note that avbtool writes single or double quotes around values.
308 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
309
310 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
311 prop = prop_matcher.match(value)
312 if not prop:
313 raise ApexInfoError(
314 'Failed to parse prop string {}'.format(value))
315
316 prop_key, prop_value = prop.group('key'), prop.group('value')
317 if prop_key == 'apex.key':
318 # avbtool dumps the prop value with repr(), which contains single /
319 # double quotes that we don't want.
320 payload_info[prop_key] = prop_value.strip('\"\'')
321
322 else:
323 payload_info[key] = value
324
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400325 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900326 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700327 if key not in payload_info:
328 raise ApexInfoError(
329 'Failed to find {} prop in {}'.format(key, payload_path))
330
331 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700332
333
Nikita Ioffe36081482021-01-20 01:32:28 +0000334def SignUncompressedApex(avbtool, apex_file, payload_key, container_key,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000335 container_pw, apk_keys, codename_to_api_level_map,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100336 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000337 """Signs the current uncompressed APEX with the given payload/container keys.
Tao Baoe7354ba2019-05-09 16:54:15 -0700338
339 Args:
Nikita Ioffe36081482021-01-20 01:32:28 +0000340 apex_file: Uncompressed APEX file.
Tao Baoe7354ba2019-05-09 16:54:15 -0700341 payload_key: The path to payload signing key (w/ extension).
342 container_key: The path to container signing key (w/o extension).
343 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800344 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700345 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700346 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700347 signing_args: Additional args to be passed to the payload signer.
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900348 sign_tool: A tool to sign the contents of the APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700349
350 Returns:
351 The path to the signed APEX file.
352 """
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900353 # 1. Extract the apex payload image and sign the files (e.g. APKs). Repack
Tianjie Xu88a759d2020-01-23 10:47:54 -0800354 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800355 apk_signer = ApexApkSigner(apex_file, container_pw,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900356 codename_to_api_level_map,
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +0000357 avbtool, sign_tool)
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100358 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800359
360 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700361 # payload_key.
362 payload_dir = common.MakeTempDir(prefix='apex-payload-')
363 with zipfile.ZipFile(apex_file) as apex_fd:
364 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700365 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700366
Tao Bao1ac886e2019-06-26 11:58:22 -0700367 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400368 if no_hashtree is None:
369 no_hashtree = payload_info.get("Tree Size", 0) == 0
Tao Baoe7354ba2019-05-09 16:54:15 -0700370 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700371 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700372 payload_file,
373 payload_key,
374 payload_info['apex.key'],
375 payload_info['Algorithm'],
376 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900377 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700378 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700379 signing_args)
380
Tianjie Xu88a759d2020-01-23 10:47:54 -0800381 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700382 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700383 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700384 if APEX_PUBKEY in zip_items:
385 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400386 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700387 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
388 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
Kelvin Zhangf92f7f02023-04-14 21:32:54 +0000389 common.ZipClose(apex_zip)
Tao Baoe7354ba2019-05-09 16:54:15 -0700390
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900391 # 3. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700392 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
393
394 # Specify the 4K alignment when calling SignApk.
395 extra_signapk_args = OPTIONS.extra_signapk_args[:]
Jooyung Hanebe9afe2021-07-12 13:23:52 +0900396 extra_signapk_args.extend(['-a', '4096', '--align-file-size'])
Tao Baoe7354ba2019-05-09 16:54:15 -0700397
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000398 password = container_pw.get(container_key) if container_pw else None
Tao Baoe7354ba2019-05-09 16:54:15 -0700399 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900400 apex_file,
Tao Baoe7354ba2019-05-09 16:54:15 -0700401 signed_apex,
402 container_key,
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000403 password,
Tao Baoe7354ba2019-05-09 16:54:15 -0700404 codename_to_api_level_map=codename_to_api_level_map,
405 extra_signapk_args=extra_signapk_args)
406
407 return signed_apex
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000408
409
Nikita Ioffe36081482021-01-20 01:32:28 +0000410def SignCompressedApex(avbtool, apex_file, payload_key, container_key,
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400411 container_pw, apk_keys, codename_to_api_level_map,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100412 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe36081482021-01-20 01:32:28 +0000413 """Signs the current compressed APEX with the given payload/container keys.
414
415 Args:
416 apex_file: Raw uncompressed APEX data.
417 payload_key: The path to payload signing key (w/ extension).
418 container_key: The path to container signing key (w/o extension).
419 container_pw: The matching password of the container_key, or None.
420 apk_keys: A dict that holds the signing keys for apk files.
421 codename_to_api_level_map: A dict that maps from codename to API level.
422 no_hashtree: Don't include hashtree in the signed APEX.
423 signing_args: Additional args to be passed to the payload signer.
424
425 Returns:
426 The path to the signed APEX file.
427 """
428 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
429
430 # 1. Decompress original_apex inside compressed apex.
431 original_apex_file = common.MakeTempFile(prefix='original-apex-',
432 suffix='.apex')
433 # Decompression target path should not exist
434 os.remove(original_apex_file)
435 common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path,
436 'decompress', '--input', apex_file,
437 '--output', original_apex_file])
438
439 # 2. Sign original_apex
440 signed_original_apex_file = SignUncompressedApex(
441 avbtool,
442 original_apex_file,
443 payload_key,
444 container_key,
445 container_pw,
446 apk_keys,
447 codename_to_api_level_map,
448 no_hashtree,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900449 signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100450 sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000451
452 # 3. Compress signed original apex.
453 compressed_apex_file = common.MakeTempFile(prefix='apex-container-',
454 suffix='.capex')
455 common.RunAndCheckOutput(['apex_compression_tool',
456 'compress',
457 '--apex_compression_tool_path', os.getenv('PATH'),
458 '--input', signed_original_apex_file,
459 '--output', compressed_apex_file])
460
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900461 # 4. Sign the APEX container with container_key.
Nikita Ioffe36081482021-01-20 01:32:28 +0000462 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex')
463
Nikita Ioffe36081482021-01-20 01:32:28 +0000464 password = container_pw.get(container_key) if container_pw else None
465 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900466 compressed_apex_file,
Nikita Ioffe36081482021-01-20 01:32:28 +0000467 signed_apex,
468 container_key,
469 password,
470 codename_to_api_level_map=codename_to_api_level_map,
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900471 extra_signapk_args=OPTIONS.extra_signapk_args)
Nikita Ioffe36081482021-01-20 01:32:28 +0000472
473 return signed_apex
474
475
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000476def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100477 apk_keys, codename_to_api_level_map,
478 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000479 """Signs the current APEX with the given payload/container keys.
480
481 Args:
482 apex_file: Path to apex file path.
483 payload_key: The path to payload signing key (w/ extension).
484 container_key: The path to container signing key (w/o extension).
485 container_pw: The matching password of the container_key, or None.
486 apk_keys: A dict that holds the signing keys for apk files.
487 codename_to_api_level_map: A dict that maps from codename to API level.
488 no_hashtree: Don't include hashtree in the signed APEX.
489 signing_args: Additional args to be passed to the payload signer.
490
491 Returns:
492 The path to the signed APEX file.
493 """
494 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
495 with open(apex_file, 'wb') as output_fp:
496 output_fp.write(apex_data)
497
Nikita Ioffe36081482021-01-20 01:32:28 +0000498 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000499 cmd = ['deapexer', '--debugfs_path', debugfs_path,
500 'info', '--print-type', apex_file]
501
502 try:
503 apex_type = common.RunAndCheckOutput(cmd).strip()
504 if apex_type == 'UNCOMPRESSED':
505 return SignUncompressedApex(
506 avbtool,
Nikita Ioffe36081482021-01-20 01:32:28 +0000507 apex_file,
508 payload_key=payload_key,
509 container_key=container_key,
Kelvin Zhang137807d2022-09-14 15:02:46 -0700510 container_pw=container_pw,
Nikita Ioffe36081482021-01-20 01:32:28 +0000511 codename_to_api_level_map=codename_to_api_level_map,
512 no_hashtree=no_hashtree,
513 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900514 signing_args=signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100515 sign_tool=sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000516 elif apex_type == 'COMPRESSED':
517 return SignCompressedApex(
518 avbtool,
519 apex_file,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000520 payload_key=payload_key,
521 container_key=container_key,
Kelvin Zhang137807d2022-09-14 15:02:46 -0700522 container_pw=container_pw,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000523 codename_to_api_level_map=codename_to_api_level_map,
524 no_hashtree=no_hashtree,
525 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900526 signing_args=signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100527 sign_tool=sign_tool)
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000528 else:
529 # TODO(b/172912232): support signing compressed apex
530 raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
531
532 except common.ExternalError as e:
533 raise ApexInfoError(
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000534 'Failed to get type for {}:\n{}'.format(apex_file, e))
535
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400536
Jooyung Han750aad52024-01-19 08:35:21 +0900537def GetApexInfoFromTargetFiles(input_file):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000538 """
Jooyung Han750aad52024-01-19 08:35:21 +0900539 Get information about APEXes stored in the input_file zip
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000540
541 Args:
542 input_file: The filename of the target build target-files zip or directory.
543
544 Return:
545 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
Jooyung Han750aad52024-01-19 08:35:21 +0900546 each partition of the input_file
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000547 """
548
549 # Extract the apex files so that we can run checks on them
550 if not isinstance(input_file, str):
551 raise RuntimeError("must pass filepath to target-files zip or directory")
Jooyung Han750aad52024-01-19 08:35:21 +0900552 apex_infos = []
553 for partition in ['system', 'system_ext', 'product', 'vendor']:
554 apex_infos.extend(GetApexInfoForPartition(input_file, partition))
555 return apex_infos
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000556
Jooyung Han750aad52024-01-19 08:35:21 +0900557
558def GetApexInfoForPartition(input_file, partition):
Daniel Normane9af70a2021-04-15 16:39:22 -0700559 apex_subdir = os.path.join(partition.upper(), 'apex')
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000560 if os.path.isdir(input_file):
561 tmp_dir = input_file
562 else:
Daniel Normane9af70a2021-04-15 16:39:22 -0700563 tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')])
564 target_dir = os.path.join(tmp_dir, apex_subdir)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000565
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800566 # Partial target-files packages for vendor-only builds may not contain
567 # a system apex directory.
568 if not os.path.exists(target_dir):
Daniel Normane9af70a2021-04-15 16:39:22 -0700569 logger.info('No APEX directory at path: %s', target_dir)
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800570 return []
571
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000572 apex_infos = []
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500573
574 debugfs_path = "debugfs"
575 if OPTIONS.search_path:
576 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
Dennis Shenf58e5482022-10-10 21:19:46 +0000577
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500578 deapexer = 'deapexer'
579 if OPTIONS.search_path:
Kelvin Zhang05a3f682021-01-29 14:38:24 -0500580 deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer")
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500581 if os.path.isfile(deapexer_path):
582 deapexer = deapexer_path
Dennis Shenf58e5482022-10-10 21:19:46 +0000583
Håkan Kvist01e38192023-04-13 21:49:19 +0200584 for apex_filename in sorted(os.listdir(target_dir)):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000585 apex_filepath = os.path.join(target_dir, apex_filename)
586 if not os.path.isfile(apex_filepath) or \
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400587 not zipfile.is_zipfile(apex_filepath):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000588 logger.info("Skipping %s because it's not a zipfile", apex_filepath)
589 continue
590 apex_info = ota_metadata_pb2.ApexInfo()
591 # Open the apex file to retrieve information
592 manifest = apex_manifest.fromApex(apex_filepath)
593 apex_info.package_name = manifest.name
594 apex_info.version = manifest.version
595 # Check if the file is compressed or not
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000596 apex_type = RunAndCheckOutput([
597 deapexer, "--debugfs_path", debugfs_path,
598 'info', '--print-type', apex_filepath]).rstrip()
599 if apex_type == 'COMPRESSED':
600 apex_info.is_compressed = True
601 elif apex_type == 'UNCOMPRESSED':
602 apex_info.is_compressed = False
603 else:
604 raise RuntimeError('Not an APEX file: ' + apex_type)
605
606 # Decompress compressed APEX to determine its size
607 if apex_info.is_compressed:
608 decompressed_file_path = MakeTempFile(prefix="decompressed-",
609 suffix=".apex")
610 # Decompression target path should not exist
611 os.remove(decompressed_file_path)
612 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
613 '--output', decompressed_file_path])
614 apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
615
Jooyung Han750aad52024-01-19 08:35:21 +0900616 apex_infos.append(apex_info)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000617
618 return apex_infos