blob: bd86acf69ae80d4a71a64d0cdc6b830a83ee950d [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):
55 """Class to sign the apk files in a apex payload image and repack the apex"""
56
57 def __init__(self, apex_path, key_passwords, codename_to_api_level_map):
58 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")
Tianjie Xu88a759d2020-01-23 10:47:54 -080066
Baligh Uddin639b3b72020-03-25 20:50:23 -070067 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080068 """Scans and signs the apk files and repack the apex
69
70 Args:
71 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080072
73 Returns:
74 The repacked apex file containing the signed apk files.
75 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040076 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040077 raise ApexSigningError(
78 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000079 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040080 "Make sure bin/debugfs_static can be found in -p <path>")
81 list_cmd = ['deapexer', '--debugfs_path',
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040082 self.debugfs_path, 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080083 entries_names = common.RunAndCheckOutput(list_cmd).split()
84 apk_entries = [name for name in entries_names if name.endswith('.apk')]
85
86 # No need to sign and repack, return the original apex path.
87 if not apk_entries:
88 logger.info('No apk file to sign in %s', self.apex_path)
89 return self.apex_path
90
91 for entry in apk_entries:
92 apk_name = os.path.basename(entry)
93 if apk_name not in apk_keys:
94 raise ApexSigningError('Failed to find signing keys for apk file {} in'
95 ' apex {}. Use "-e <apkname>=" to specify a key'
96 .format(entry, self.apex_path))
97 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
98 'overlay/']):
99 logger.warning('Apk path does not contain the intended directory name:'
100 ' %s', entry)
101
102 payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
103 apk_entries, apk_keys)
104 if not has_signed_apk:
105 logger.info('No apk file has been signed in %s', self.apex_path)
106 return self.apex_path
107
Baligh Uddin639b3b72020-03-25 20:50:23 -0700108 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800109
110 def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
111 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400112 if not os.path.exists(self.debugfs_path):
113 raise ApexSigningError(
114 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000115 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400116 "Make sure bin/debugfs_static can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800117 payload_dir = common.MakeTempDir()
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400118 extract_cmd = ['deapexer', '--debugfs_path',
119 self.debugfs_path, 'extract', self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800120 common.RunAndCheckOutput(extract_cmd)
121
122 has_signed_apk = False
123 for entry in apk_entries:
124 apk_path = os.path.join(payload_dir, entry)
125 assert os.path.exists(self.apex_path)
126
127 key_name = apk_keys.get(os.path.basename(entry))
128 if key_name in common.SPECIAL_CERT_STRINGS:
129 logger.info('Not signing: %s due to special cert string', apk_path)
130 continue
131
132 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
133 # Rename the unsigned apk and overwrite the original apk path with the
134 # signed apk file.
135 unsigned_apk = common.MakeTempFile()
136 os.rename(apk_path, unsigned_apk)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000137 common.SignFile(
138 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
139 codename_to_api_level_map=self.codename_to_api_level_map)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800140 has_signed_apk = True
141 return payload_dir, has_signed_apk
142
Baligh Uddin639b3b72020-03-25 20:50:23 -0700143 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800144 """Rebuilds the apex file with the updated payload directory."""
145 apex_dir = common.MakeTempDir()
146 # Extract the apex file and reuse its meta files as repack parameters.
147 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800148 arguments_dict = {
149 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
150 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800151 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800152 }
153 for filename in arguments_dict.values():
154 assert os.path.exists(filename), 'file {} not found'.format(filename)
155
156 # The repack process will add back these files later in the payload image.
157 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
158 path = os.path.join(payload_dir, name)
159 if os.path.isfile(path):
160 os.remove(path)
161 elif os.path.isdir(path):
162 shutil.rmtree(path)
163
Tianjiec180a5d2020-03-23 18:14:09 -0700164 # TODO(xunchang) the signing process can be improved by using
165 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
166 # the signing arguments, e.g. algorithm, salt, etc.
167 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
168 generate_image_cmd = ['apexer', '--force', '--payload_only',
169 '--do_not_check_keyname', '--apexer_tool_path',
170 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800171 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700172 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700173
174 # Add quote to the signing_args as we will pass
175 # --signing_args "--signing_helper_with_files=%path" to apexer
176 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400177 generate_image_cmd.extend(
178 ['--signing_args', '"{}"'.format(signing_args)])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700179
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800180 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800181 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
182 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700183 generate_image_cmd.extend(['--manifest_json', manifest_json])
184 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800185 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700186 generate_image_cmd.append('-v')
187 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800188
Tianjiec180a5d2020-03-23 18:14:09 -0700189 # Add the payload image back to the apex file.
190 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400191 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700192 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
193 compress_type=zipfile.ZIP_STORED)
194 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800195
196
Tao Bao1ac886e2019-06-26 11:58:22 -0700197def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900198 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700199 """Signs a given payload_file with the payload key."""
200 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700201 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700202 '--do_not_generate_fec',
203 '--algorithm', algorithm,
204 '--key', payload_key_path,
205 '--prop', 'apex.key:{}'.format(payload_key_name),
206 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900207 '--salt', salt,
208 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700209 if no_hashtree:
210 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700211 if signing_args:
212 cmd.extend(shlex.split(signing_args))
213
214 try:
215 common.RunAndCheckOutput(cmd)
216 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700217 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700218 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700219 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700220
221 # Verify the signed payload image with specified public key.
222 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700223 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700224
225
Tao Bao448004a2019-09-19 07:55:02 -0700226def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700227 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700228 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700229 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700230 if no_hashtree:
231 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700232 try:
233 common.RunAndCheckOutput(cmd)
234 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700235 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700236 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700237 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700238
239
Tao Bao1ac886e2019-06-26 11:58:22 -0700240def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700241 """Parses the APEX payload info.
242
243 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700244 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700245 payload_path: The path to the payload image.
246
247 Raises:
248 ApexInfoError on parsing errors.
249
250 Returns:
251 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700252 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700253 """
254 if not os.path.exists(payload_path):
255 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
256
Tao Bao1ac886e2019-06-26 11:58:22 -0700257 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700258 try:
259 output = common.RunAndCheckOutput(cmd)
260 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700261 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700262 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700263 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700264
Jiyong Parka1887f32020-05-19 23:18:03 +0900265 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
266 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700267 # Algorithm: SHA256_RSA4096
268 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900269 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700270 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
271
272 payload_info = {}
273 for line in output.split('\n'):
274 line_info = payload_info_matcher.match(line)
275 if not line_info:
276 continue
277
278 key, value = line_info.group('key'), line_info.group('value')
279
280 if key == 'Prop':
281 # Further extract the property key-value pair, from a 'Prop:' line. For
282 # example,
283 # Prop: apex.key -> 'com.android.runtime'
284 # Note that avbtool writes single or double quotes around values.
285 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
286
287 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
288 prop = prop_matcher.match(value)
289 if not prop:
290 raise ApexInfoError(
291 'Failed to parse prop string {}'.format(value))
292
293 prop_key, prop_value = prop.group('key'), prop.group('value')
294 if prop_key == 'apex.key':
295 # avbtool dumps the prop value with repr(), which contains single /
296 # double quotes that we don't want.
297 payload_info[prop_key] = prop_value.strip('\"\'')
298
299 else:
300 payload_info[key] = value
301
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400302 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900303 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700304 if key not in payload_info:
305 raise ApexInfoError(
306 'Failed to find {} prop in {}'.format(key, payload_path))
307
308 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700309
310
Nikita Ioffe36081482021-01-20 01:32:28 +0000311def SignUncompressedApex(avbtool, apex_file, payload_key, container_key,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000312 container_pw, apk_keys, codename_to_api_level_map,
313 no_hashtree, signing_args=None):
314 """Signs the current uncompressed APEX with the given payload/container keys.
Tao Baoe7354ba2019-05-09 16:54:15 -0700315
316 Args:
Nikita Ioffe36081482021-01-20 01:32:28 +0000317 apex_file: Uncompressed APEX file.
Tao Baoe7354ba2019-05-09 16:54:15 -0700318 payload_key: The path to payload signing key (w/ extension).
319 container_key: The path to container signing key (w/o extension).
320 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800321 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700322 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700323 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700324 signing_args: Additional args to be passed to the payload signer.
325
326 Returns:
327 The path to the signed APEX file.
328 """
Tianjie Xu88a759d2020-01-23 10:47:54 -0800329 # 1. Extract the apex payload image and sign the containing apk files. Repack
330 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800331 apk_signer = ApexApkSigner(apex_file, container_pw,
332 codename_to_api_level_map)
Baligh Uddin639b3b72020-03-25 20:50:23 -0700333 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800334
335 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700336 # payload_key.
337 payload_dir = common.MakeTempDir(prefix='apex-payload-')
338 with zipfile.ZipFile(apex_file) as apex_fd:
339 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700340 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700341
Tao Bao1ac886e2019-06-26 11:58:22 -0700342 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700343 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700344 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700345 payload_file,
346 payload_key,
347 payload_info['apex.key'],
348 payload_info['Algorithm'],
349 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900350 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700351 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700352 signing_args)
353
Tianjie Xu88a759d2020-01-23 10:47:54 -0800354 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700355 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700356 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700357 if APEX_PUBKEY in zip_items:
358 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400359 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700360 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
361 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
362 common.ZipClose(apex_zip)
363
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900364 # 3. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700365 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
366
367 # Specify the 4K alignment when calling SignApk.
368 extra_signapk_args = OPTIONS.extra_signapk_args[:]
Jooyung Hanebe9afe2021-07-12 13:23:52 +0900369 extra_signapk_args.extend(['-a', '4096', '--align-file-size'])
Tao Baoe7354ba2019-05-09 16:54:15 -0700370
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000371 password = container_pw.get(container_key) if container_pw else None
Tao Baoe7354ba2019-05-09 16:54:15 -0700372 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900373 apex_file,
Tao Baoe7354ba2019-05-09 16:54:15 -0700374 signed_apex,
375 container_key,
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000376 password,
Tao Baoe7354ba2019-05-09 16:54:15 -0700377 codename_to_api_level_map=codename_to_api_level_map,
378 extra_signapk_args=extra_signapk_args)
379
380 return signed_apex
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000381
382
Nikita Ioffe36081482021-01-20 01:32:28 +0000383def SignCompressedApex(avbtool, apex_file, payload_key, container_key,
384 container_pw, apk_keys, codename_to_api_level_map,
385 no_hashtree, signing_args=None):
386 """Signs the current compressed APEX with the given payload/container keys.
387
388 Args:
389 apex_file: Raw uncompressed APEX data.
390 payload_key: The path to payload signing key (w/ extension).
391 container_key: The path to container signing key (w/o extension).
392 container_pw: The matching password of the container_key, or None.
393 apk_keys: A dict that holds the signing keys for apk files.
394 codename_to_api_level_map: A dict that maps from codename to API level.
395 no_hashtree: Don't include hashtree in the signed APEX.
396 signing_args: Additional args to be passed to the payload signer.
397
398 Returns:
399 The path to the signed APEX file.
400 """
401 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
402
403 # 1. Decompress original_apex inside compressed apex.
404 original_apex_file = common.MakeTempFile(prefix='original-apex-',
405 suffix='.apex')
406 # Decompression target path should not exist
407 os.remove(original_apex_file)
408 common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path,
409 'decompress', '--input', apex_file,
410 '--output', original_apex_file])
411
412 # 2. Sign original_apex
413 signed_original_apex_file = SignUncompressedApex(
414 avbtool,
415 original_apex_file,
416 payload_key,
417 container_key,
418 container_pw,
419 apk_keys,
420 codename_to_api_level_map,
421 no_hashtree,
422 signing_args)
423
424 # 3. Compress signed original apex.
425 compressed_apex_file = common.MakeTempFile(prefix='apex-container-',
426 suffix='.capex')
427 common.RunAndCheckOutput(['apex_compression_tool',
428 'compress',
429 '--apex_compression_tool_path', os.getenv('PATH'),
430 '--input', signed_original_apex_file,
431 '--output', compressed_apex_file])
432
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900433 # 4. Sign the APEX container with container_key.
Nikita Ioffe36081482021-01-20 01:32:28 +0000434 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex')
435
Nikita Ioffe36081482021-01-20 01:32:28 +0000436 password = container_pw.get(container_key) if container_pw else None
437 common.SignFile(
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900438 compressed_apex_file,
Nikita Ioffe36081482021-01-20 01:32:28 +0000439 signed_apex,
440 container_key,
441 password,
442 codename_to_api_level_map=codename_to_api_level_map,
Jooyung Hanf9be5ee2021-07-22 18:21:25 +0900443 extra_signapk_args=OPTIONS.extra_signapk_args)
Nikita Ioffe36081482021-01-20 01:32:28 +0000444
445 return signed_apex
446
447
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000448def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
449 apk_keys, codename_to_api_level_map,
450 no_hashtree, signing_args=None):
451 """Signs the current APEX with the given payload/container keys.
452
453 Args:
454 apex_file: Path to apex file path.
455 payload_key: The path to payload signing key (w/ extension).
456 container_key: The path to container signing key (w/o extension).
457 container_pw: The matching password of the container_key, or None.
458 apk_keys: A dict that holds the signing keys for apk files.
459 codename_to_api_level_map: A dict that maps from codename to API level.
460 no_hashtree: Don't include hashtree in the signed APEX.
461 signing_args: Additional args to be passed to the payload signer.
462
463 Returns:
464 The path to the signed APEX file.
465 """
466 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
467 with open(apex_file, 'wb') as output_fp:
468 output_fp.write(apex_data)
469
Nikita Ioffe36081482021-01-20 01:32:28 +0000470 debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static')
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000471 cmd = ['deapexer', '--debugfs_path', debugfs_path,
472 'info', '--print-type', apex_file]
473
474 try:
475 apex_type = common.RunAndCheckOutput(cmd).strip()
476 if apex_type == 'UNCOMPRESSED':
477 return SignUncompressedApex(
478 avbtool,
Nikita Ioffe36081482021-01-20 01:32:28 +0000479 apex_file,
480 payload_key=payload_key,
481 container_key=container_key,
482 container_pw=None,
483 codename_to_api_level_map=codename_to_api_level_map,
484 no_hashtree=no_hashtree,
485 apk_keys=apk_keys,
486 signing_args=signing_args)
487 elif apex_type == 'COMPRESSED':
488 return SignCompressedApex(
489 avbtool,
490 apex_file,
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000491 payload_key=payload_key,
492 container_key=container_key,
493 container_pw=None,
494 codename_to_api_level_map=codename_to_api_level_map,
495 no_hashtree=no_hashtree,
496 apk_keys=apk_keys,
497 signing_args=signing_args)
498 else:
499 # TODO(b/172912232): support signing compressed apex
500 raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
501
502 except common.ExternalError as e:
503 raise ApexInfoError(
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000504 'Failed to get type for {}:\n{}'.format(apex_file, e))
505
Daniel Normane9af70a2021-04-15 16:39:22 -0700506def GetApexInfoFromTargetFiles(input_file, partition, compressed_only=True):
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000507 """
508 Get information about system APEX stored in the input_file zip
509
510 Args:
511 input_file: The filename of the target build target-files zip or directory.
512
513 Return:
514 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
515 /system partition of the input_file
516 """
517
518 # Extract the apex files so that we can run checks on them
519 if not isinstance(input_file, str):
520 raise RuntimeError("must pass filepath to target-files zip or directory")
521
Daniel Normane9af70a2021-04-15 16:39:22 -0700522 apex_subdir = os.path.join(partition.upper(), 'apex')
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000523 if os.path.isdir(input_file):
524 tmp_dir = input_file
525 else:
Daniel Normane9af70a2021-04-15 16:39:22 -0700526 tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')])
527 target_dir = os.path.join(tmp_dir, apex_subdir)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000528
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800529 # Partial target-files packages for vendor-only builds may not contain
530 # a system apex directory.
531 if not os.path.exists(target_dir):
Daniel Normane9af70a2021-04-15 16:39:22 -0700532 logger.info('No APEX directory at path: %s', target_dir)
Daniel Normanb4b07ab2021-02-17 13:22:21 -0800533 return []
534
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000535 apex_infos = []
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500536
537 debugfs_path = "debugfs"
538 if OPTIONS.search_path:
539 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
540 deapexer = 'deapexer'
541 if OPTIONS.search_path:
Kelvin Zhang05a3f682021-01-29 14:38:24 -0500542 deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer")
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500543 if os.path.isfile(deapexer_path):
544 deapexer = deapexer_path
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000545 for apex_filename in os.listdir(target_dir):
546 apex_filepath = os.path.join(target_dir, apex_filename)
547 if not os.path.isfile(apex_filepath) or \
548 not zipfile.is_zipfile(apex_filepath):
549 logger.info("Skipping %s because it's not a zipfile", apex_filepath)
550 continue
551 apex_info = ota_metadata_pb2.ApexInfo()
552 # Open the apex file to retrieve information
553 manifest = apex_manifest.fromApex(apex_filepath)
554 apex_info.package_name = manifest.name
555 apex_info.version = manifest.version
556 # Check if the file is compressed or not
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000557 apex_type = RunAndCheckOutput([
558 deapexer, "--debugfs_path", debugfs_path,
559 'info', '--print-type', apex_filepath]).rstrip()
560 if apex_type == 'COMPRESSED':
561 apex_info.is_compressed = True
562 elif apex_type == 'UNCOMPRESSED':
563 apex_info.is_compressed = False
564 else:
565 raise RuntimeError('Not an APEX file: ' + apex_type)
566
567 # Decompress compressed APEX to determine its size
568 if apex_info.is_compressed:
569 decompressed_file_path = MakeTempFile(prefix="decompressed-",
570 suffix=".apex")
571 # Decompression target path should not exist
572 os.remove(decompressed_file_path)
573 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
574 '--output', decompressed_file_path])
575 apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
576
Daniel Normane9af70a2021-04-15 16:39:22 -0700577 if not compressed_only or apex_info.is_compressed:
Kelvin Zhangc72718c2021-01-27 14:17:14 -0500578 apex_infos.append(apex_info)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000579
580 return apex_infos