blob: 211af0a0d1aef8d5a5405a24527625d5e63e32eb [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
Jooyung Han0f5a41d2021-10-27 03:53:21 +090057 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")
Jooyung Han0f5a41d2021-10-27 03:53:21 +090066 self.avbtool = avbtool if avbtool else "avbtool"
67 self.sign_tool = sign_tool
Tianjie Xu88a759d2020-01-23 10:47:54 -080068
Baligh Uddin639b3b72020-03-25 20:50:23 -070069 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Jooyung Han0f5a41d2021-10-27 03:53:21 +090070 """Scans and signs the payload files and repack the apex
Tianjie Xu88a759d2020-01-23 10:47:54 -080071
72 Args:
73 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080074
75 Returns:
76 The repacked apex file containing the signed apk files.
77 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040078 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040079 raise ApexSigningError(
80 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000081 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040082 "Make sure bin/debugfs_static can be found in -p <path>")
83 list_cmd = ['deapexer', '--debugfs_path',
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040084 self.debugfs_path, 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080085 entries_names = common.RunAndCheckOutput(list_cmd).split()
86 apk_entries = [name for name in entries_names if name.endswith('.apk')]
87
88 # No need to sign and repack, return the original apex path.
Jooyung Han0f5a41d2021-10-27 03:53:21 +090089 if not apk_entries and self.sign_tool is None:
Tianjie Xu88a759d2020-01-23 10:47:54 -080090 logger.info('No apk file to sign in %s', self.apex_path)
91 return self.apex_path
92
93 for entry in apk_entries:
94 apk_name = os.path.basename(entry)
95 if apk_name not in apk_keys:
96 raise ApexSigningError('Failed to find signing keys for apk file {} in'
97 ' apex {}. Use "-e <apkname>=" to specify a key'
98 .format(entry, self.apex_path))
99 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
100 'overlay/']):
101 logger.warning('Apk path does not contain the intended directory name:'
102 ' %s', entry)
103
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900104 payload_dir, has_signed_content = self.ExtractApexPayloadAndSignContents(
105 apk_entries, apk_keys, payload_key)
106 if not has_signed_content:
107 logger.info('No contents has been signed in %s', self.apex_path)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800108 return self.apex_path
109
Baligh Uddin639b3b72020-03-25 20:50:23 -0700110 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800111
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900112 def ExtractApexPayloadAndSignContents(self, apk_entries, apk_keys, payload_key):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800113 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400114 if not os.path.exists(self.debugfs_path):
115 raise ApexSigningError(
116 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000117 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400118 "Make sure bin/debugfs_static can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800119 payload_dir = common.MakeTempDir()
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400120 extract_cmd = ['deapexer', '--debugfs_path',
121 self.debugfs_path, 'extract', self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800122 common.RunAndCheckOutput(extract_cmd)
123
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900124 has_signed_content = False
Tianjie Xu88a759d2020-01-23 10:47:54 -0800125 for entry in apk_entries:
126 apk_path = os.path.join(payload_dir, entry)
127 assert os.path.exists(self.apex_path)
128
129 key_name = apk_keys.get(os.path.basename(entry))
130 if key_name in common.SPECIAL_CERT_STRINGS:
131 logger.info('Not signing: %s due to special cert string', apk_path)
132 continue
133
134 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
135 # Rename the unsigned apk and overwrite the original apk path with the
136 # signed apk file.
137 unsigned_apk = common.MakeTempFile()
138 os.rename(apk_path, unsigned_apk)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000139 common.SignFile(
140 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
141 codename_to_api_level_map=self.codename_to_api_level_map)
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900142 has_signed_content = True
143
144 if self.sign_tool:
145 cmd = [self.sign_tool, '--avbtool', self.avbtool, payload_key, payload_dir]
146 common.RunAndCheckOutput(cmd)
147 has_signed_content = True
148
149 return payload_dir, has_signed_content
Tianjie Xu88a759d2020-01-23 10:47:54 -0800150
Baligh Uddin639b3b72020-03-25 20:50:23 -0700151 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800152 """Rebuilds the apex file with the updated payload directory."""
153 apex_dir = common.MakeTempDir()
154 # Extract the apex file and reuse its meta files as repack parameters.
155 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800156 arguments_dict = {
157 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
158 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800159 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800160 }
161 for filename in arguments_dict.values():
162 assert os.path.exists(filename), 'file {} not found'.format(filename)
163
164 # The repack process will add back these files later in the payload image.
165 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
166 path = os.path.join(payload_dir, name)
167 if os.path.isfile(path):
168 os.remove(path)
169 elif os.path.isdir(path):
170 shutil.rmtree(path)
171
Tianjiec180a5d2020-03-23 18:14:09 -0700172 # TODO(xunchang) the signing process can be improved by using
173 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
174 # the signing arguments, e.g. algorithm, salt, etc.
175 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
176 generate_image_cmd = ['apexer', '--force', '--payload_only',
177 '--do_not_check_keyname', '--apexer_tool_path',
178 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800179 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700180 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700181
182 # Add quote to the signing_args as we will pass
183 # --signing_args "--signing_helper_with_files=%path" to apexer
184 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400185 generate_image_cmd.extend(
186 ['--signing_args', '"{}"'.format(signing_args)])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700187
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800188 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800189 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
190 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700191 generate_image_cmd.extend(['--manifest_json', manifest_json])
192 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800193 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700194 generate_image_cmd.append('-v')
195 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800196
Tianjiec180a5d2020-03-23 18:14:09 -0700197 # Add the payload image back to the apex file.
198 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400199 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700200 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
201 compress_type=zipfile.ZIP_STORED)
202 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800203
204
Tao Bao1ac886e2019-06-26 11:58:22 -0700205def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900206 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700207 """Signs a given payload_file with the payload key."""
208 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700209 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700210 '--do_not_generate_fec',
211 '--algorithm', algorithm,
212 '--key', payload_key_path,
213 '--prop', 'apex.key:{}'.format(payload_key_name),
214 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900215 '--salt', salt,
216 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700217 if no_hashtree:
218 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700219 if signing_args:
220 cmd.extend(shlex.split(signing_args))
221
222 try:
223 common.RunAndCheckOutput(cmd)
224 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700225 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700226 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700227 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700228
229 # Verify the signed payload image with specified public key.
230 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700231 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700232
233
Tao Bao448004a2019-09-19 07:55:02 -0700234def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700235 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700236 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700237 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700238 if no_hashtree:
239 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700240 try:
241 common.RunAndCheckOutput(cmd)
242 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700243 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700244 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700245 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700246
247
Tao Bao1ac886e2019-06-26 11:58:22 -0700248def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700249 """Parses the APEX payload info.
250
251 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700252 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700253 payload_path: The path to the payload image.
254
255 Raises:
256 ApexInfoError on parsing errors.
257
258 Returns:
259 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700260 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700261 """
262 if not os.path.exists(payload_path):
263 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
264
Tao Bao1ac886e2019-06-26 11:58:22 -0700265 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700266 try:
267 output = common.RunAndCheckOutput(cmd)
268 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700269 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700270 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700271 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700272
Jiyong Parka1887f32020-05-19 23:18:03 +0900273 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
274 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700275 # Algorithm: SHA256_RSA4096
276 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900277 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700278 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
279
280 payload_info = {}
281 for line in output.split('\n'):
282 line_info = payload_info_matcher.match(line)
283 if not line_info:
284 continue
285
286 key, value = line_info.group('key'), line_info.group('value')
287
288 if key == 'Prop':
289 # Further extract the property key-value pair, from a 'Prop:' line. For
290 # example,
291 # Prop: apex.key -> 'com.android.runtime'
292 # Note that avbtool writes single or double quotes around values.
293 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
294
295 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
296 prop = prop_matcher.match(value)
297 if not prop:
298 raise ApexInfoError(
299 'Failed to parse prop string {}'.format(value))
300
301 prop_key, prop_value = prop.group('key'), prop.group('value')
302 if prop_key == 'apex.key':
303 # avbtool dumps the prop value with repr(), which contains single /
304 # double quotes that we don't want.
305 payload_info[prop_key] = prop_value.strip('\"\'')
306
307 else:
308 payload_info[key] = value
309
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400310 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900311 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700312 if key not in payload_info:
313 raise ApexInfoError(
314 'Failed to find {} prop in {}'.format(key, payload_path))
315
316 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700317
318
Nikita Ioffe36081482021-01-20 01:32:28 +0000319def SignUncompressedApex(avbtool, apex_file, payload_key, container_key,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000320 container_pw, apk_keys, codename_to_api_level_map,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900321 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000322 """Signs the current uncompressed APEX with the given payload/container keys.
Tao Baoe7354ba2019-05-09 16:54:15 -0700323
324 Args:
Nikita Ioffe36081482021-01-20 01:32:28 +0000325 apex_file: Uncompressed APEX file.
Tao Baoe7354ba2019-05-09 16:54:15 -0700326 payload_key: The path to payload signing key (w/ extension).
327 container_key: The path to container signing key (w/o extension).
328 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800329 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700330 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700331 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700332 signing_args: Additional args to be passed to the payload signer.
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900333 sign_tool: A tool to sign the contents of the APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700334
335 Returns:
336 The path to the signed APEX file.
337 """
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900338 # 1. Extract the apex payload image and sign the files (e.g. APKs). Repack
Tianjie Xu88a759d2020-01-23 10:47:54 -0800339 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800340 apk_signer = ApexApkSigner(apex_file, container_pw,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900341 codename_to_api_level_map,
342 avbtool, sign_tool)
Baligh Uddin639b3b72020-03-25 20:50:23 -0700343 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800344
345 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700346 # payload_key.
347 payload_dir = common.MakeTempDir(prefix='apex-payload-')
348 with zipfile.ZipFile(apex_file) as apex_fd:
349 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700350 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700351
Tao Bao1ac886e2019-06-26 11:58:22 -0700352 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400353 if no_hashtree is None:
354 no_hashtree = payload_info.get("Tree Size", 0) == 0
Tao Baoe7354ba2019-05-09 16:54:15 -0700355 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700356 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700357 payload_file,
358 payload_key,
359 payload_info['apex.key'],
360 payload_info['Algorithm'],
361 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900362 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700363 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700364 signing_args)
365
Tianjie Xu88a759d2020-01-23 10:47:54 -0800366 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700367 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700368 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700369 if APEX_PUBKEY in zip_items:
370 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400371 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700372 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
373 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
374 common.ZipClose(apex_zip)
375
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900376 # 3. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700377 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
378
379 # Specify the 4K alignment when calling SignApk.
380 extra_signapk_args = OPTIONS.extra_signapk_args[:]
Jooyung Hanebe9afe2021-07-12 13:23:52 +0900381 extra_signapk_args.extend(['-a', '4096', '--align-file-size'])
Tao Baoe7354ba2019-05-09 16:54:15 -0700382
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000383 password = container_pw.get(container_key) if container_pw else None
Tao Baoe7354ba2019-05-09 16:54:15 -0700384 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900385 apex_file,
Tao Baoe7354ba2019-05-09 16:54:15 -0700386 signed_apex,
387 container_key,
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000388 password,
Tao Baoe7354ba2019-05-09 16:54:15 -0700389 codename_to_api_level_map=codename_to_api_level_map,
390 extra_signapk_args=extra_signapk_args)
391
392 return signed_apex
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000393
394
Nikita Ioffe36081482021-01-20 01:32:28 +0000395def SignCompressedApex(avbtool, apex_file, payload_key, container_key,
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400396 container_pw, apk_keys, codename_to_api_level_map,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900397 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe36081482021-01-20 01:32:28 +0000398 """Signs the current compressed APEX with the given payload/container keys.
399
400 Args:
401 apex_file: Raw uncompressed APEX data.
402 payload_key: The path to payload signing key (w/ extension).
403 container_key: The path to container signing key (w/o extension).
404 container_pw: The matching password of the container_key, or None.
405 apk_keys: A dict that holds the signing keys for apk files.
406 codename_to_api_level_map: A dict that maps from codename to API level.
407 no_hashtree: Don't include hashtree in the signed APEX.
408 signing_args: Additional args to be passed to the payload signer.
409
410 Returns:
411 The path to the signed APEX file.
412 """
413 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
414
415 # 1. Decompress original_apex inside compressed apex.
416 original_apex_file = common.MakeTempFile(prefix='original-apex-',
417 suffix='.apex')
418 # Decompression target path should not exist
419 os.remove(original_apex_file)
420 common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path,
421 'decompress', '--input', apex_file,
422 '--output', original_apex_file])
423
424 # 2. Sign original_apex
425 signed_original_apex_file = SignUncompressedApex(
426 avbtool,
427 original_apex_file,
428 payload_key,
429 container_key,
430 container_pw,
431 apk_keys,
432 codename_to_api_level_map,
433 no_hashtree,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900434 signing_args,
435 sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000436
437 # 3. Compress signed original apex.
438 compressed_apex_file = common.MakeTempFile(prefix='apex-container-',
439 suffix='.capex')
440 common.RunAndCheckOutput(['apex_compression_tool',
441 'compress',
442 '--apex_compression_tool_path', os.getenv('PATH'),
443 '--input', signed_original_apex_file,
444 '--output', compressed_apex_file])
445
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900446 # 4. Sign the APEX container with container_key.
Nikita Ioffe36081482021-01-20 01:32:28 +0000447 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex')
448
Nikita Ioffe36081482021-01-20 01:32:28 +0000449 password = container_pw.get(container_key) if container_pw else None
450 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900451 compressed_apex_file,
Nikita Ioffe36081482021-01-20 01:32:28 +0000452 signed_apex,
453 container_key,
454 password,
455 codename_to_api_level_map=codename_to_api_level_map,
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900456 extra_signapk_args=OPTIONS.extra_signapk_args)
Nikita Ioffe36081482021-01-20 01:32:28 +0000457
458 return signed_apex
459
460
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000461def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
462 apk_keys, codename_to_api_level_map,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900463 no_hashtree, signing_args=None, sign_tool=None):
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000464 """Signs the current APEX with the given payload/container keys.
465
466 Args:
467 apex_file: Path to apex file path.
468 payload_key: The path to payload signing key (w/ extension).
469 container_key: The path to container signing key (w/o extension).
470 container_pw: The matching password of the container_key, or None.
471 apk_keys: A dict that holds the signing keys for apk files.
472 codename_to_api_level_map: A dict that maps from codename to API level.
473 no_hashtree: Don't include hashtree in the signed APEX.
474 signing_args: Additional args to be passed to the payload signer.
475
476 Returns:
477 The path to the signed APEX file.
478 """
479 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
480 with open(apex_file, 'wb') as output_fp:
481 output_fp.write(apex_data)
482
Nikita Ioffe36081482021-01-20 01:32:28 +0000483 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000484 cmd = ['deapexer', '--debugfs_path', debugfs_path,
485 'info', '--print-type', apex_file]
486
487 try:
488 apex_type = common.RunAndCheckOutput(cmd).strip()
489 if apex_type == 'UNCOMPRESSED':
490 return SignUncompressedApex(
491 avbtool,
Nikita Ioffe36081482021-01-20 01:32:28 +0000492 apex_file,
493 payload_key=payload_key,
494 container_key=container_key,
495 container_pw=None,
496 codename_to_api_level_map=codename_to_api_level_map,
497 no_hashtree=no_hashtree,
498 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900499 signing_args=signing_args,
500 sign_tool=sign_tool)
Nikita Ioffe36081482021-01-20 01:32:28 +0000501 elif apex_type == 'COMPRESSED':
502 return SignCompressedApex(
503 avbtool,
504 apex_file,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000505 payload_key=payload_key,
506 container_key=container_key,
507 container_pw=None,
508 codename_to_api_level_map=codename_to_api_level_map,
509 no_hashtree=no_hashtree,
510 apk_keys=apk_keys,
Jooyung Han0f5a41d2021-10-27 03:53:21 +0900511 signing_args=signing_args,
512 sign_tool=sign_tool)
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000513 else:
514 # TODO(b/172912232): support signing compressed apex
515 raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
516
517 except common.ExternalError as e:
518 raise ApexInfoError(
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000519 'Failed to get type for {}:\n{}'.format(apex_file, e))
520
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400521
Daniel Normane9af70a2021-04-15 16:39:22 -0700522def GetApexInfoFromTargetFiles(input_file, partition, compressed_only=True):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000523 """
524 Get information about system APEX stored in the input_file zip
525
526 Args:
527 input_file: The filename of the target build target-files zip or directory.
528
529 Return:
530 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
531 /system partition of the input_file
532 """
533
534 # Extract the apex files so that we can run checks on them
535 if not isinstance(input_file, str):
536 raise RuntimeError("must pass filepath to target-files zip or directory")
537
Daniel Normane9af70a2021-04-15 16:39:22 -0700538 apex_subdir = os.path.join(partition.upper(), 'apex')
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000539 if os.path.isdir(input_file):
540 tmp_dir = input_file
541 else:
Daniel Normane9af70a2021-04-15 16:39:22 -0700542 tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')])
543 target_dir = os.path.join(tmp_dir, apex_subdir)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000544
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800545 # Partial target-files packages for vendor-only builds may not contain
546 # a system apex directory.
547 if not os.path.exists(target_dir):
Daniel Normane9af70a2021-04-15 16:39:22 -0700548 logger.info('No APEX directory at path: %s', target_dir)
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800549 return []
550
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000551 apex_infos = []
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500552
553 debugfs_path = "debugfs"
554 if OPTIONS.search_path:
555 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
556 deapexer = 'deapexer'
557 if OPTIONS.search_path:
Kelvin Zhang05a3f682021-01-29 14:38:24 -0500558 deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer")
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500559 if os.path.isfile(deapexer_path):
560 deapexer = deapexer_path
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000561 for apex_filename in os.listdir(target_dir):
562 apex_filepath = os.path.join(target_dir, apex_filename)
563 if not os.path.isfile(apex_filepath) or \
Kelvin Zhang7cab7502021-08-02 19:58:14 -0400564 not zipfile.is_zipfile(apex_filepath):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000565 logger.info("Skipping %s because it's not a zipfile", apex_filepath)
566 continue
567 apex_info = ota_metadata_pb2.ApexInfo()
568 # Open the apex file to retrieve information
569 manifest = apex_manifest.fromApex(apex_filepath)
570 apex_info.package_name = manifest.name
571 apex_info.version = manifest.version
572 # Check if the file is compressed or not
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000573 apex_type = RunAndCheckOutput([
574 deapexer, "--debugfs_path", debugfs_path,
575 'info', '--print-type', apex_filepath]).rstrip()
576 if apex_type == 'COMPRESSED':
577 apex_info.is_compressed = True
578 elif apex_type == 'UNCOMPRESSED':
579 apex_info.is_compressed = False
580 else:
581 raise RuntimeError('Not an APEX file: ' + apex_type)
582
583 # Decompress compressed APEX to determine its size
584 if apex_info.is_compressed:
585 decompressed_file_path = MakeTempFile(prefix="decompressed-",
586 suffix=".apex")
587 # Decompression target path should not exist
588 os.remove(decompressed_file_path)
589 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
590 '--output', decompressed_file_path])
591 apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
592
Daniel Normane9af70a2021-04-15 16:39:22 -0700593 if not compressed_only or apex_info.is_compressed:
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500594 apex_infos.append(apex_info)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000595
596 return apex_infos