blob: 54df955e9f39be4812c32d7b29b26b89bfd69055 [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
Jooyung Han1e45baf2024-08-15 07:38:17 +000039# Partitions supporting APEXes
40PARTITIONS = ['system', 'system_ext', 'product', 'vendor', 'odm']
Tao Bao1cd59f22019-03-15 15:13:01 -070041
42class ApexInfoError(Exception):
43 """An Exception raised during Apex Information command."""
44
45 def __init__(self, message):
46 Exception.__init__(self, message)
47
48
49class ApexSigningError(Exception):
50 """An Exception raised during Apex Payload signing."""
51
52 def __init__(self, message):
53 Exception.__init__(self, message)
54
55
Tianjie Xu88a759d2020-01-23 10:47:54 -080056class ApexApkSigner(object):
Jooyung Han0f5a41d2021-10-27 03:53:21 +090057 """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 -080058
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +000059 def __init__(self, apex_path, key_passwords, codename_to_api_level_map, avbtool=None, sign_tool=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080060 self.apex_path = apex_path
Oleh Cherpake555ab12020-10-05 17:04:59 +030061 if not key_passwords:
62 self.key_passwords = dict()
63 else:
64 self.key_passwords = key_passwords
Tianjie Xu88a759d2020-01-23 10:47:54 -080065 self.codename_to_api_level_map = codename_to_api_level_map
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040066 self.debugfs_path = os.path.join(
67 OPTIONS.search_path, "bin", "debugfs_static")
Dennis Shenf58e5482022-10-10 21:19:46 +000068 self.fsckerofs_path = os.path.join(
69 OPTIONS.search_path, "bin", "fsck.erofs")
Jooyung Han0f5a41d2021-10-27 03:53:21 +090070 self.avbtool = avbtool if avbtool else "avbtool"
71 self.sign_tool = sign_tool
Tianjie Xu88a759d2020-01-23 10:47:54 -080072
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +110073 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Jooyung Han0f5a41d2021-10-27 03:53:21 +090074 """Scans and signs the payload files and repack the apex
Tianjie Xu88a759d2020-01-23 10:47:54 -080075
76 Args:
77 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080078
79 Returns:
80 The repacked apex file containing the signed apk files.
81 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040082 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040083 raise ApexSigningError(
84 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000085 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040086 "Make sure bin/debugfs_static can be found in -p <path>")
Dennis Shenf58e5482022-10-10 21:19:46 +000087 list_cmd = ['deapexer', '--debugfs_path', self.debugfs_path,
Dennis Shena8d11432022-11-07 21:37:06 +000088 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080089 entries_names = common.RunAndCheckOutput(list_cmd).split()
90 apk_entries = [name for name in entries_names if name.endswith('.apk')]
91
92 # No need to sign and repack, return the original apex path.
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +110093 if not apk_entries and self.sign_tool is None:
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +000094 logger.info('No apk file to sign in %s', self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -080095 return self.apex_path
96
97 for entry in apk_entries:
98 apk_name = os.path.basename(entry)
99 if apk_name not in apk_keys:
100 raise ApexSigningError('Failed to find signing keys for apk file {} in'
101 ' apex {}. Use "-e <apkname>=" to specify a key'
102 .format(entry, self.apex_path))
103 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
104 'overlay/']):
105 logger.warning('Apk path does not contain the intended directory name:'
106 ' %s', entry)
107
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +0000108 payload_dir, has_signed_content = self.ExtractApexPayloadAndSignContents(
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100109 apk_entries, apk_keys, payload_key, signing_args)
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900110 if not has_signed_content:
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100111 logger.info('No contents has been signed in %s', self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800112 return self.apex_path
113
Baligh Uddin639b3b72020-03-25 20:50:23 -0700114 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800115
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100116 def ExtractApexPayloadAndSignContents(self, apk_entries, apk_keys, payload_key, signing_args):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800117 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400118 if not os.path.exists(self.debugfs_path):
119 raise ApexSigningError(
120 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000121 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400122 "Make sure bin/debugfs_static can be found in -p <path>")
Dennis Shenf58e5482022-10-10 21:19:46 +0000123 if not os.path.exists(self.fsckerofs_path):
124 raise ApexSigningError(
125 "Couldn't find location of fsck.erofs: " +
126 "Path {} does not exist. ".format(self.fsckerofs_path) +
127 "Make sure bin/fsck.erofs can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800128 payload_dir = common.MakeTempDir()
Dennis Shenf58e5482022-10-10 21:19:46 +0000129 extract_cmd = ['deapexer', '--debugfs_path', self.debugfs_path,
Dennis Shena8d11432022-11-07 21:37:06 +0000130 '--fsckerofs_path', self.fsckerofs_path,
Jooyung Han62949022023-06-14 15:16:34 +0900131 'extract',
Dennis Shenf58e5482022-10-10 21:19:46 +0000132 self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800133 common.RunAndCheckOutput(extract_cmd)
134
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900135 has_signed_content = False
Tianjie Xu88a759d2020-01-23 10:47:54 -0800136 for entry in apk_entries:
137 apk_path = os.path.join(payload_dir, entry)
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100138 assert os.path.exists(self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800139
140 key_name = apk_keys.get(os.path.basename(entry))
141 if key_name in common.SPECIAL_CERT_STRINGS:
142 logger.info('Not signing: %s due to special cert string', apk_path)
143 continue
144
145 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
146 # Rename the unsigned apk and overwrite the original apk path with the
147 # signed apk file.
148 unsigned_apk = common.MakeTempFile()
149 os.rename(apk_path, unsigned_apk)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000150 common.SignFile(
151 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
152 codename_to_api_level_map=self.codename_to_api_level_map)
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900153 has_signed_content = True
154
155 if self.sign_tool:
Jooyung Han8caba5e2021-10-27 03:58:09 +0900156 logger.info('Signing payload contents in apex %s with %s', self.apex_path, self.sign_tool)
Jooyung Han39259ec2022-02-07 15:56:53 +0900157 # Pass avbtool to the custom signing tool
158 cmd = [self.sign_tool, '--avbtool', self.avbtool]
159 # Pass signing_args verbatim which will be forwarded to avbtool (e.g. --signing_helper=...)
160 if signing_args:
161 cmd.extend(['--signing_args', '"{}"'.format(signing_args)])
162 cmd.extend([payload_key, payload_dir])
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900163 common.RunAndCheckOutput(cmd)
164 has_signed_content = True
165
166 return payload_dir, has_signed_content
Tianjie Xu88a759d2020-01-23 10:47:54 -0800167
Baligh Uddin639b3b72020-03-25 20:50:23 -0700168 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800169 """Rebuilds the apex file with the updated payload directory."""
170 apex_dir = common.MakeTempDir()
171 # Extract the apex file and reuse its meta files as repack parameters.
172 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800173 arguments_dict = {
174 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
175 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800176 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800177 }
178 for filename in arguments_dict.values():
179 assert os.path.exists(filename), 'file {} not found'.format(filename)
180
181 # The repack process will add back these files later in the payload image.
182 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
183 path = os.path.join(payload_dir, name)
184 if os.path.isfile(path):
185 os.remove(path)
186 elif os.path.isdir(path):
Baligh Uddinbe2d7d02022-02-26 02:34:06 +0000187 shutil.rmtree(path, ignore_errors=True)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800188
Tianjiec180a5d2020-03-23 18:14:09 -0700189 # TODO(xunchang) the signing process can be improved by using
190 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
191 # the signing arguments, e.g. algorithm, salt, etc.
192 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
193 generate_image_cmd = ['apexer', '--force', '--payload_only',
194 '--do_not_check_keyname', '--apexer_tool_path',
195 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800196 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700197 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700198
199 # Add quote to the signing_args as we will pass
200 # --signing_args "--signing_helper_with_files=%path" to apexer
201 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400202 generate_image_cmd.extend(
203 ['--signing_args', '"{}"'.format(signing_args)])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700204
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800205 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800206 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
207 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700208 generate_image_cmd.extend(['--manifest_json', manifest_json])
209 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800210 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700211 generate_image_cmd.append('-v')
212 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800213
Tianjiec180a5d2020-03-23 18:14:09 -0700214 # Add the payload image back to the apex file.
215 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400216 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700217 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
218 compress_type=zipfile.ZIP_STORED)
219 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800220
221
Tao Bao1ac886e2019-06-26 11:58:22 -0700222def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900223 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700224 """Signs a given payload_file with the payload key."""
225 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700226 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700227 '--do_not_generate_fec',
228 '--algorithm', algorithm,
229 '--key', payload_key_path,
230 '--prop', 'apex.key:{}'.format(payload_key_name),
231 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900232 '--salt', salt,
233 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700234 if no_hashtree:
235 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700236 if signing_args:
237 cmd.extend(shlex.split(signing_args))
238
239 try:
240 common.RunAndCheckOutput(cmd)
241 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700242 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700243 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700244 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700245
246 # Verify the signed payload image with specified public key.
247 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700248 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700249
250
Tao Bao448004a2019-09-19 07:55:02 -0700251def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700252 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700253 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700254 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700255 if no_hashtree:
256 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700257 try:
258 common.RunAndCheckOutput(cmd)
259 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700260 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700261 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700262 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700263
264
Tao Bao1ac886e2019-06-26 11:58:22 -0700265def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700266 """Parses the APEX payload info.
267
268 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700269 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700270 payload_path: The path to the payload image.
271
272 Raises:
273 ApexInfoError on parsing errors.
274
275 Returns:
276 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700277 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700278 """
279 if not os.path.exists(payload_path):
280 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
281
Tao Bao1ac886e2019-06-26 11:58:22 -0700282 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700283 try:
284 output = common.RunAndCheckOutput(cmd)
285 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700286 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700287 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700288 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700289
Jiyong Parka1887f32020-05-19 23:18:03 +0900290 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
291 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700292 # Algorithm: SHA256_RSA4096
293 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900294 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700295 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
296
297 payload_info = {}
298 for line in output.split('\n'):
299 line_info = payload_info_matcher.match(line)
300 if not line_info:
301 continue
302
303 key, value = line_info.group('key'), line_info.group('value')
304
305 if key == 'Prop':
306 # Further extract the property key-value pair, from a 'Prop:' line. For
307 # example,
308 # Prop: apex.key -> 'com.android.runtime'
309 # Note that avbtool writes single or double quotes around values.
310 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
311
312 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
313 prop = prop_matcher.match(value)
314 if not prop:
315 raise ApexInfoError(
316 'Failed to parse prop string {}'.format(value))
317
318 prop_key, prop_value = prop.group('key'), prop.group('value')
319 if prop_key == 'apex.key':
320 # avbtool dumps the prop value with repr(), which contains single /
321 # double quotes that we don't want.
322 payload_info[prop_key] = prop_value.strip('\"\'')
323
324 else:
325 payload_info[key] = value
326
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400327 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900328 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700329 if key not in payload_info:
330 raise ApexInfoError(
331 'Failed to find {} prop in {}'.format(key, payload_path))
332
333 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700334
335
Nikita Ioffe36081482021-01-20 01:32:28 +0000336def SignUncompressedApex(avbtool, apex_file, payload_key, container_key,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000337 container_pw, apk_keys, codename_to_api_level_map,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100338 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000339 """Signs the current uncompressed APEX with the given payload/container keys.
Tao Baoe7354ba2019-05-09 16:54:15 -0700340
341 Args:
Nikita Ioffe36081482021-01-20 01:32:28 +0000342 apex_file: Uncompressed APEX file.
Tao Baoe7354ba2019-05-09 16:54:15 -0700343 payload_key: The path to payload signing key (w/ extension).
344 container_key: The path to container signing key (w/o extension).
345 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800346 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700347 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700348 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700349 signing_args: Additional args to be passed to the payload signer.
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900350 sign_tool: A tool to sign the contents of the APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700351
352 Returns:
353 The path to the signed APEX file.
354 """
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900355 # 1. Extract the apex payload image and sign the files (e.g. APKs). Repack
Tianjie Xu88a759d2020-01-23 10:47:54 -0800356 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800357 apk_signer = ApexApkSigner(apex_file, container_pw,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900358 codename_to_api_level_map,
Melisa Carranza Zúñiga8e3198a2022-04-13 16:23:45 +0000359 avbtool, sign_tool)
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100360 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800361
362 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700363 # payload_key.
364 payload_dir = common.MakeTempDir(prefix='apex-payload-')
365 with zipfile.ZipFile(apex_file) as apex_fd:
366 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700367 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700368
Tao Bao1ac886e2019-06-26 11:58:22 -0700369 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400370 if no_hashtree is None:
371 no_hashtree = payload_info.get("Tree Size", 0) == 0
Tao Baoe7354ba2019-05-09 16:54:15 -0700372 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700373 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700374 payload_file,
375 payload_key,
376 payload_info['apex.key'],
377 payload_info['Algorithm'],
378 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900379 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700380 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700381 signing_args)
382
Tianjie Xu88a759d2020-01-23 10:47:54 -0800383 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700384 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700385 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700386 if APEX_PUBKEY in zip_items:
387 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400388 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700389 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
390 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
Kelvin Zhangf92f7f02023-04-14 21:32:54 +0000391 common.ZipClose(apex_zip)
Tao Baoe7354ba2019-05-09 16:54:15 -0700392
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900393 # 3. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700394 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
395
396 # Specify the 4K alignment when calling SignApk.
397 extra_signapk_args = OPTIONS.extra_signapk_args[:]
Jooyung Hanebe9afe2021-07-12 13:23:52 +0900398 extra_signapk_args.extend(['-a', '4096', '--align-file-size'])
Tao Baoe7354ba2019-05-09 16:54:15 -0700399
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000400 password = container_pw.get(container_key) if container_pw else None
Tao Baoe7354ba2019-05-09 16:54:15 -0700401 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900402 apex_file,
Tao Baoe7354ba2019-05-09 16:54:15 -0700403 signed_apex,
404 container_key,
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000405 password,
Tao Baoe7354ba2019-05-09 16:54:15 -0700406 codename_to_api_level_map=codename_to_api_level_map,
407 extra_signapk_args=extra_signapk_args)
408
409 return signed_apex
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000410
411
Nikita Ioffe36081482021-01-20 01:32:28 +0000412def SignCompressedApex(avbtool, apex_file, payload_key, container_key,
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400413 container_pw, apk_keys, codename_to_api_level_map,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100414 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe36081482021-01-20 01:32:28 +0000415 """Signs the current compressed APEX with the given payload/container keys.
416
417 Args:
418 apex_file: Raw uncompressed APEX data.
419 payload_key: The path to payload signing key (w/ extension).
420 container_key: The path to container signing key (w/o extension).
421 container_pw: The matching password of the container_key, or None.
422 apk_keys: A dict that holds the signing keys for apk files.
423 codename_to_api_level_map: A dict that maps from codename to API level.
424 no_hashtree: Don't include hashtree in the signed APEX.
425 signing_args: Additional args to be passed to the payload signer.
426
427 Returns:
428 The path to the signed APEX file.
429 """
430 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
431
432 # 1. Decompress original_apex inside compressed apex.
433 original_apex_file = common.MakeTempFile(prefix='original-apex-',
434 suffix='.apex')
435 # Decompression target path should not exist
436 os.remove(original_apex_file)
437 common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path,
438 'decompress', '--input', apex_file,
439 '--output', original_apex_file])
440
441 # 2. Sign original_apex
442 signed_original_apex_file = SignUncompressedApex(
443 avbtool,
444 original_apex_file,
445 payload_key,
446 container_key,
447 container_pw,
448 apk_keys,
449 codename_to_api_level_map,
450 no_hashtree,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900451 signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100452 sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000453
454 # 3. Compress signed original apex.
455 compressed_apex_file = common.MakeTempFile(prefix='apex-container-',
456 suffix='.capex')
457 common.RunAndCheckOutput(['apex_compression_tool',
458 'compress',
459 '--apex_compression_tool_path', os.getenv('PATH'),
460 '--input', signed_original_apex_file,
461 '--output', compressed_apex_file])
462
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900463 # 4. Sign the APEX container with container_key.
Nikita Ioffe36081482021-01-20 01:32:28 +0000464 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex')
465
Nikita Ioffe36081482021-01-20 01:32:28 +0000466 password = container_pw.get(container_key) if container_pw else None
467 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900468 compressed_apex_file,
Nikita Ioffe36081482021-01-20 01:32:28 +0000469 signed_apex,
470 container_key,
471 password,
472 codename_to_api_level_map=codename_to_api_level_map,
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900473 extra_signapk_args=OPTIONS.extra_signapk_args)
Nikita Ioffe36081482021-01-20 01:32:28 +0000474
475 return signed_apex
476
477
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000478def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100479 apk_keys, codename_to_api_level_map,
480 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000481 """Signs the current APEX with the given payload/container keys.
482
483 Args:
484 apex_file: Path to apex file path.
485 payload_key: The path to payload signing key (w/ extension).
486 container_key: The path to container signing key (w/o extension).
487 container_pw: The matching password of the container_key, or None.
488 apk_keys: A dict that holds the signing keys for apk files.
489 codename_to_api_level_map: A dict that maps from codename to API level.
490 no_hashtree: Don't include hashtree in the signed APEX.
491 signing_args: Additional args to be passed to the payload signer.
492
493 Returns:
494 The path to the signed APEX file.
495 """
496 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
497 with open(apex_file, 'wb') as output_fp:
498 output_fp.write(apex_data)
499
Nikita Ioffe36081482021-01-20 01:32:28 +0000500 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000501 cmd = ['deapexer', '--debugfs_path', debugfs_path,
502 'info', '--print-type', apex_file]
503
504 try:
505 apex_type = common.RunAndCheckOutput(cmd).strip()
506 if apex_type == 'UNCOMPRESSED':
507 return SignUncompressedApex(
508 avbtool,
Nikita Ioffe36081482021-01-20 01:32:28 +0000509 apex_file,
510 payload_key=payload_key,
511 container_key=container_key,
Kelvin Zhang137807d2022-09-14 15:02:46 -0700512 container_pw=container_pw,
Nikita Ioffe36081482021-01-20 01:32:28 +0000513 codename_to_api_level_map=codename_to_api_level_map,
514 no_hashtree=no_hashtree,
515 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900516 signing_args=signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100517 sign_tool=sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000518 elif apex_type == 'COMPRESSED':
519 return SignCompressedApex(
520 avbtool,
521 apex_file,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000522 payload_key=payload_key,
523 container_key=container_key,
Kelvin Zhang137807d2022-09-14 15:02:46 -0700524 container_pw=container_pw,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000525 codename_to_api_level_map=codename_to_api_level_map,
526 no_hashtree=no_hashtree,
527 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900528 signing_args=signing_args,
Thiébaud Weksteen62865ca2023-10-18 11:08:47 +1100529 sign_tool=sign_tool)
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000530 else:
531 # TODO(b/172912232): support signing compressed apex
532 raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
533
534 except common.ExternalError as e:
535 raise ApexInfoError(
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000536 'Failed to get type for {}:\n{}'.format(apex_file, e))
537
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400538
Jooyung Han750aad52024-01-19 08:35:21 +0900539def GetApexInfoFromTargetFiles(input_file):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000540 """
Jooyung Han750aad52024-01-19 08:35:21 +0900541 Get information about APEXes stored in the input_file zip
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000542
543 Args:
544 input_file: The filename of the target build target-files zip or directory.
545
546 Return:
547 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
Jooyung Han750aad52024-01-19 08:35:21 +0900548 each partition of the input_file
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000549 """
550
551 # Extract the apex files so that we can run checks on them
552 if not isinstance(input_file, str):
553 raise RuntimeError("must pass filepath to target-files zip or directory")
Jooyung Han750aad52024-01-19 08:35:21 +0900554 apex_infos = []
Jooyung Han1e45baf2024-08-15 07:38:17 +0000555 for partition in PARTITIONS:
Jooyung Han750aad52024-01-19 08:35:21 +0900556 apex_infos.extend(GetApexInfoForPartition(input_file, partition))
557 return apex_infos
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000558
Jooyung Han750aad52024-01-19 08:35:21 +0900559
560def GetApexInfoForPartition(input_file, partition):
Daniel Normane9af70a2021-04-15 16:39:22 -0700561 apex_subdir = os.path.join(partition.upper(), 'apex')
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000562 if os.path.isdir(input_file):
563 tmp_dir = input_file
564 else:
Daniel Normane9af70a2021-04-15 16:39:22 -0700565 tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')])
566 target_dir = os.path.join(tmp_dir, apex_subdir)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000567
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800568 # Partial target-files packages for vendor-only builds may not contain
569 # a system apex directory.
570 if not os.path.exists(target_dir):
Daniel Normane9af70a2021-04-15 16:39:22 -0700571 logger.info('No APEX directory at path: %s', target_dir)
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800572 return []
573
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000574 apex_infos = []
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500575
576 debugfs_path = "debugfs"
577 if OPTIONS.search_path:
578 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
Dennis Shenf58e5482022-10-10 21:19:46 +0000579
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500580 deapexer = 'deapexer'
581 if OPTIONS.search_path:
Kelvin Zhang05a3f682021-01-29 14:38:24 -0500582 deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer")
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500583 if os.path.isfile(deapexer_path):
584 deapexer = deapexer_path
Dennis Shenf58e5482022-10-10 21:19:46 +0000585
Håkan Kvist01e38192023-04-13 21:49:19 +0200586 for apex_filename in sorted(os.listdir(target_dir)):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000587 apex_filepath = os.path.join(target_dir, apex_filename)
588 if not os.path.isfile(apex_filepath) or \
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400589 not zipfile.is_zipfile(apex_filepath):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000590 logger.info("Skipping %s because it's not a zipfile", apex_filepath)
591 continue
592 apex_info = ota_metadata_pb2.ApexInfo()
593 # Open the apex file to retrieve information
594 manifest = apex_manifest.fromApex(apex_filepath)
595 apex_info.package_name = manifest.name
596 apex_info.version = manifest.version
597 # Check if the file is compressed or not
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000598 apex_type = RunAndCheckOutput([
599 deapexer, "--debugfs_path", debugfs_path,
600 'info', '--print-type', apex_filepath]).rstrip()
601 if apex_type == 'COMPRESSED':
602 apex_info.is_compressed = True
603 elif apex_type == 'UNCOMPRESSED':
604 apex_info.is_compressed = False
605 else:
606 raise RuntimeError('Not an APEX file: ' + apex_type)
607
608 # Decompress compressed APEX to determine its size
609 if apex_info.is_compressed:
610 decompressed_file_path = MakeTempFile(prefix="decompressed-",
611 suffix=".apex")
612 # Decompression target path should not exist
613 os.remove(decompressed_file_path)
614 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
615 '--output', decompressed_file_path])
616 apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
617
Jooyung Han750aad52024-01-19 08:35:21 +0900618 apex_infos.append(apex_info)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000619
620 return apex_infos