blob: 7ccc95cb91ba573f4ee6f209a4212c8c32b2953c [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
Tao Bao1cd59f22019-03-15 15:13:01 -070037
38class ApexInfoError(Exception):
39 """An Exception raised during Apex Information command."""
40
41 def __init__(self, message):
42 Exception.__init__(self, message)
43
44
45class ApexSigningError(Exception):
46 """An Exception raised during Apex Payload signing."""
47
48 def __init__(self, message):
49 Exception.__init__(self, message)
50
51
Tianjie Xu88a759d2020-01-23 10:47:54 -080052class ApexApkSigner(object):
53 """Class to sign the apk files in a apex payload image and repack the apex"""
54
55 def __init__(self, apex_path, key_passwords, codename_to_api_level_map):
56 self.apex_path = apex_path
Oleh Cherpake555ab12020-10-05 17:04:59 +030057 if not key_passwords:
58 self.key_passwords = dict()
59 else:
60 self.key_passwords = key_passwords
Tianjie Xu88a759d2020-01-23 10:47:54 -080061 self.codename_to_api_level_map = codename_to_api_level_map
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040062 self.debugfs_path = os.path.join(
63 OPTIONS.search_path, "bin", "debugfs_static")
Tianjie Xu88a759d2020-01-23 10:47:54 -080064
Baligh Uddin639b3b72020-03-25 20:50:23 -070065 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080066 """Scans and signs the apk files and repack the apex
67
68 Args:
69 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080070
71 Returns:
72 The repacked apex file containing the signed apk files.
73 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040074 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040075 raise ApexSigningError(
76 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +000077 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040078 "Make sure bin/debugfs_static can be found in -p <path>")
79 list_cmd = ['deapexer', '--debugfs_path',
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040080 self.debugfs_path, 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080081 entries_names = common.RunAndCheckOutput(list_cmd).split()
82 apk_entries = [name for name in entries_names if name.endswith('.apk')]
83
84 # No need to sign and repack, return the original apex path.
85 if not apk_entries:
86 logger.info('No apk file to sign in %s', self.apex_path)
87 return self.apex_path
88
89 for entry in apk_entries:
90 apk_name = os.path.basename(entry)
91 if apk_name not in apk_keys:
92 raise ApexSigningError('Failed to find signing keys for apk file {} in'
93 ' apex {}. Use "-e <apkname>=" to specify a key'
94 .format(entry, self.apex_path))
95 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
96 'overlay/']):
97 logger.warning('Apk path does not contain the intended directory name:'
98 ' %s', entry)
99
100 payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
101 apk_entries, apk_keys)
102 if not has_signed_apk:
103 logger.info('No apk file has been signed in %s', self.apex_path)
104 return self.apex_path
105
Baligh Uddin639b3b72020-03-25 20:50:23 -0700106 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800107
108 def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
109 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400110 if not os.path.exists(self.debugfs_path):
111 raise ApexSigningError(
112 "Couldn't find location of debugfs_static: " +
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000113 "Path {} does not exist. ".format(self.debugfs_path) +
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400114 "Make sure bin/debugfs_static can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800115 payload_dir = common.MakeTempDir()
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400116 extract_cmd = ['deapexer', '--debugfs_path',
117 self.debugfs_path, 'extract', self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800118 common.RunAndCheckOutput(extract_cmd)
119
120 has_signed_apk = False
121 for entry in apk_entries:
122 apk_path = os.path.join(payload_dir, entry)
123 assert os.path.exists(self.apex_path)
124
125 key_name = apk_keys.get(os.path.basename(entry))
126 if key_name in common.SPECIAL_CERT_STRINGS:
127 logger.info('Not signing: %s due to special cert string', apk_path)
128 continue
129
130 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
131 # Rename the unsigned apk and overwrite the original apk path with the
132 # signed apk file.
133 unsigned_apk = common.MakeTempFile()
134 os.rename(apk_path, unsigned_apk)
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000135 common.SignFile(
136 unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
137 codename_to_api_level_map=self.codename_to_api_level_map)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800138 has_signed_apk = True
139 return payload_dir, has_signed_apk
140
Baligh Uddin639b3b72020-03-25 20:50:23 -0700141 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800142 """Rebuilds the apex file with the updated payload directory."""
143 apex_dir = common.MakeTempDir()
144 # Extract the apex file and reuse its meta files as repack parameters.
145 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800146 arguments_dict = {
147 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
148 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800149 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800150 }
151 for filename in arguments_dict.values():
152 assert os.path.exists(filename), 'file {} not found'.format(filename)
153
154 # The repack process will add back these files later in the payload image.
155 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
156 path = os.path.join(payload_dir, name)
157 if os.path.isfile(path):
158 os.remove(path)
159 elif os.path.isdir(path):
160 shutil.rmtree(path)
161
Tianjiec180a5d2020-03-23 18:14:09 -0700162 # TODO(xunchang) the signing process can be improved by using
163 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
164 # the signing arguments, e.g. algorithm, salt, etc.
165 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
166 generate_image_cmd = ['apexer', '--force', '--payload_only',
167 '--do_not_check_keyname', '--apexer_tool_path',
168 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800169 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700170 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700171
172 # Add quote to the signing_args as we will pass
173 # --signing_args "--signing_helper_with_files=%path" to apexer
174 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400175 generate_image_cmd.extend(
176 ['--signing_args', '"{}"'.format(signing_args)])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700177
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800178 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800179 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
180 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700181 generate_image_cmd.extend(['--manifest_json', manifest_json])
182 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800183 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700184 generate_image_cmd.append('-v')
185 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800186
Tianjiec180a5d2020-03-23 18:14:09 -0700187 # Add the payload image back to the apex file.
188 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400189 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700190 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
191 compress_type=zipfile.ZIP_STORED)
192 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800193
194
Tao Bao1ac886e2019-06-26 11:58:22 -0700195def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900196 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700197 """Signs a given payload_file with the payload key."""
198 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700199 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700200 '--do_not_generate_fec',
201 '--algorithm', algorithm,
202 '--key', payload_key_path,
203 '--prop', 'apex.key:{}'.format(payload_key_name),
204 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900205 '--salt', salt,
206 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700207 if no_hashtree:
208 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700209 if signing_args:
210 cmd.extend(shlex.split(signing_args))
211
212 try:
213 common.RunAndCheckOutput(cmd)
214 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700215 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700216 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700217 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700218
219 # Verify the signed payload image with specified public key.
220 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700221 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700222
223
Tao Bao448004a2019-09-19 07:55:02 -0700224def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700225 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700226 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700227 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700228 if no_hashtree:
229 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700230 try:
231 common.RunAndCheckOutput(cmd)
232 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700233 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700234 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700235 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700236
237
Tao Bao1ac886e2019-06-26 11:58:22 -0700238def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700239 """Parses the APEX payload info.
240
241 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700242 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700243 payload_path: The path to the payload image.
244
245 Raises:
246 ApexInfoError on parsing errors.
247
248 Returns:
249 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700250 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700251 """
252 if not os.path.exists(payload_path):
253 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
254
Tao Bao1ac886e2019-06-26 11:58:22 -0700255 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700256 try:
257 output = common.RunAndCheckOutput(cmd)
258 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700259 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700260 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700261 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700262
Jiyong Parka1887f32020-05-19 23:18:03 +0900263 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
264 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700265 # Algorithm: SHA256_RSA4096
266 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900267 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700268 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
269
270 payload_info = {}
271 for line in output.split('\n'):
272 line_info = payload_info_matcher.match(line)
273 if not line_info:
274 continue
275
276 key, value = line_info.group('key'), line_info.group('value')
277
278 if key == 'Prop':
279 # Further extract the property key-value pair, from a 'Prop:' line. For
280 # example,
281 # Prop: apex.key -> 'com.android.runtime'
282 # Note that avbtool writes single or double quotes around values.
283 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
284
285 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
286 prop = prop_matcher.match(value)
287 if not prop:
288 raise ApexInfoError(
289 'Failed to parse prop string {}'.format(value))
290
291 prop_key, prop_value = prop.group('key'), prop.group('value')
292 if prop_key == 'apex.key':
293 # avbtool dumps the prop value with repr(), which contains single /
294 # double quotes that we don't want.
295 payload_info[prop_key] = prop_value.strip('\"\'')
296
297 else:
298 payload_info[key] = value
299
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400300 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900301 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700302 if key not in payload_info:
303 raise ApexInfoError(
304 'Failed to find {} prop in {}'.format(key, payload_path))
305
306 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700307
308
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000309def SignUncompressedApex(avbtool, apex_data, payload_key, container_key,
310 container_pw, apk_keys, codename_to_api_level_map,
311 no_hashtree, signing_args=None):
312 """Signs the current uncompressed APEX with the given payload/container keys.
Tao Baoe7354ba2019-05-09 16:54:15 -0700313
314 Args:
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000315 apex_data: Raw uncompressed APEX data.
Tao Baoe7354ba2019-05-09 16:54:15 -0700316 payload_key: The path to payload signing key (w/ extension).
317 container_key: The path to container signing key (w/o extension).
318 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800319 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700320 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700321 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700322 signing_args: Additional args to be passed to the payload signer.
323
324 Returns:
325 The path to the signed APEX file.
326 """
327 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
328 with open(apex_file, 'wb') as apex_fp:
329 apex_fp.write(apex_data)
330
Tao Baoe7354ba2019-05-09 16:54:15 -0700331 APEX_PUBKEY = 'apex_pubkey'
332
Tianjie Xu88a759d2020-01-23 10:47:54 -0800333 # 1. Extract the apex payload image and sign the containing apk files. Repack
334 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800335 apk_signer = ApexApkSigner(apex_file, container_pw,
336 codename_to_api_level_map)
Baligh Uddin639b3b72020-03-25 20:50:23 -0700337 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800338
339 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700340 # payload_key.
341 payload_dir = common.MakeTempDir(prefix='apex-payload-')
342 with zipfile.ZipFile(apex_file) as apex_fd:
343 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700344 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700345
Tao Bao1ac886e2019-06-26 11:58:22 -0700346 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700347 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700348 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700349 payload_file,
350 payload_key,
351 payload_info['apex.key'],
352 payload_info['Algorithm'],
353 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900354 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700355 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700356 signing_args)
357
Tianjie Xu88a759d2020-01-23 10:47:54 -0800358 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700359 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700360 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700361 if APEX_PUBKEY in zip_items:
362 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400363 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700364 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
365 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
366 common.ZipClose(apex_zip)
367
Tianjie Xu88a759d2020-01-23 10:47:54 -0800368 # 3. Align the files at page boundary (same as in apexer).
Tao Baoe7354ba2019-05-09 16:54:15 -0700369 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
370 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
371
Tianjie Xu88a759d2020-01-23 10:47:54 -0800372 # 4. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700373 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
374
375 # Specify the 4K alignment when calling SignApk.
376 extra_signapk_args = OPTIONS.extra_signapk_args[:]
377 extra_signapk_args.extend(['-a', '4096'])
378
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000379 password = container_pw.get(container_key) if container_pw else None
Tao Baoe7354ba2019-05-09 16:54:15 -0700380 common.SignFile(
381 aligned_apex,
382 signed_apex,
383 container_key,
Nikita Ioffec3fdfed2021-01-11 23:50:31 +0000384 password,
Tao Baoe7354ba2019-05-09 16:54:15 -0700385 codename_to_api_level_map=codename_to_api_level_map,
386 extra_signapk_args=extra_signapk_args)
387
388 return signed_apex
Nikita Ioffe6068e8d2021-01-12 00:03:02 +0000389
390
391def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
392 apk_keys, codename_to_api_level_map,
393 no_hashtree, signing_args=None):
394 """Signs the current APEX with the given payload/container keys.
395
396 Args:
397 apex_file: Path to apex file path.
398 payload_key: The path to payload signing key (w/ extension).
399 container_key: The path to container signing key (w/o extension).
400 container_pw: The matching password of the container_key, or None.
401 apk_keys: A dict that holds the signing keys for apk files.
402 codename_to_api_level_map: A dict that maps from codename to API level.
403 no_hashtree: Don't include hashtree in the signed APEX.
404 signing_args: Additional args to be passed to the payload signer.
405
406 Returns:
407 The path to the signed APEX file.
408 """
409 apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
410 with open(apex_file, 'wb') as output_fp:
411 output_fp.write(apex_data)
412
413 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
414 cmd = ['deapexer', '--debugfs_path', debugfs_path,
415 'info', '--print-type', apex_file]
416
417 try:
418 apex_type = common.RunAndCheckOutput(cmd).strip()
419 if apex_type == 'UNCOMPRESSED':
420 return SignUncompressedApex(
421 avbtool,
422 apex_data,
423 payload_key=payload_key,
424 container_key=container_key,
425 container_pw=None,
426 codename_to_api_level_map=codename_to_api_level_map,
427 no_hashtree=no_hashtree,
428 apk_keys=apk_keys,
429 signing_args=signing_args)
430 else:
431 # TODO(b/172912232): support signing compressed apex
432 raise ApexInfoError('Unsupported apex type {}'.format(apex_type))
433
434 except common.ExternalError as e:
435 raise ApexInfoError(
Mohammad Samiul Islam9fd58862021-01-06 13:33:25 +0000436 'Failed to get type for {}:\n{}'.format(apex_file, e))
437
438def GetApexInfoFromTargetFiles(input_file):
439 """
440 Get information about system APEX stored in the input_file zip
441
442 Args:
443 input_file: The filename of the target build target-files zip or directory.
444
445 Return:
446 A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in
447 /system partition of the input_file
448 """
449
450 # Extract the apex files so that we can run checks on them
451 if not isinstance(input_file, str):
452 raise RuntimeError("must pass filepath to target-files zip or directory")
453
454 if os.path.isdir(input_file):
455 tmp_dir = input_file
456 else:
457 tmp_dir = UnzipTemp(input_file, ["SYSTEM/apex/*"])
458 target_dir = os.path.join(tmp_dir, "SYSTEM/apex/")
459
460 apex_infos = []
461 for apex_filename in os.listdir(target_dir):
462 apex_filepath = os.path.join(target_dir, apex_filename)
463 if not os.path.isfile(apex_filepath) or \
464 not zipfile.is_zipfile(apex_filepath):
465 logger.info("Skipping %s because it's not a zipfile", apex_filepath)
466 continue
467 apex_info = ota_metadata_pb2.ApexInfo()
468 # Open the apex file to retrieve information
469 manifest = apex_manifest.fromApex(apex_filepath)
470 apex_info.package_name = manifest.name
471 apex_info.version = manifest.version
472 # Check if the file is compressed or not
473 debugfs_path = "debugfs"
474 if OPTIONS.search_path:
475 debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static")
476 deapexer = 'deapexer'
477 if OPTIONS.search_path:
478 deapexer_path = os.path.join(OPTIONS.search_path, "deapexer")
479 if os.path.isfile(deapexer_path):
480 deapexer = deapexer_path
481 apex_type = RunAndCheckOutput([
482 deapexer, "--debugfs_path", debugfs_path,
483 'info', '--print-type', apex_filepath]).rstrip()
484 if apex_type == 'COMPRESSED':
485 apex_info.is_compressed = True
486 elif apex_type == 'UNCOMPRESSED':
487 apex_info.is_compressed = False
488 else:
489 raise RuntimeError('Not an APEX file: ' + apex_type)
490
491 # Decompress compressed APEX to determine its size
492 if apex_info.is_compressed:
493 decompressed_file_path = MakeTempFile(prefix="decompressed-",
494 suffix=".apex")
495 # Decompression target path should not exist
496 os.remove(decompressed_file_path)
497 RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath,
498 '--output', decompressed_file_path])
499 apex_info.decompressed_size = os.path.getsize(decompressed_file_path)
500
501 apex_infos.append(apex_info)
502
503 return apex_infos