blob: cf10386ecef012cdd86b0a5a42700402c6165e36 [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
24import common
25
26logger = logging.getLogger(__name__)
27
Tao Baoe7354ba2019-05-09 16:54:15 -070028OPTIONS = common.OPTIONS
29
Tao Bao1cd59f22019-03-15 15:13:01 -070030
31class ApexInfoError(Exception):
32 """An Exception raised during Apex Information command."""
33
34 def __init__(self, message):
35 Exception.__init__(self, message)
36
37
38class ApexSigningError(Exception):
39 """An Exception raised during Apex Payload signing."""
40
41 def __init__(self, message):
42 Exception.__init__(self, message)
43
44
Tianjie Xu88a759d2020-01-23 10:47:54 -080045class ApexApkSigner(object):
46 """Class to sign the apk files in a apex payload image and repack the apex"""
47
48 def __init__(self, apex_path, key_passwords, codename_to_api_level_map):
49 self.apex_path = apex_path
50 self.key_passwords = key_passwords
51 self.codename_to_api_level_map = codename_to_api_level_map
52
53 def ProcessApexFile(self, apk_keys, payload_key, payload_public_key):
54 """Scans and signs the apk files and repack the apex
55
56 Args:
57 apk_keys: A dict that holds the signing keys for apk files.
58 payload_key: The path to the apex payload signing key.
59 payload_public_key: The path to the public key corresponding to the
60 payload signing key.
61
62 Returns:
63 The repacked apex file containing the signed apk files.
64 """
65 list_cmd = ['deapexer', 'list', self.apex_path]
66 entries_names = common.RunAndCheckOutput(list_cmd).split()
67 apk_entries = [name for name in entries_names if name.endswith('.apk')]
68
69 # No need to sign and repack, return the original apex path.
70 if not apk_entries:
71 logger.info('No apk file to sign in %s', self.apex_path)
72 return self.apex_path
73
74 for entry in apk_entries:
75 apk_name = os.path.basename(entry)
76 if apk_name not in apk_keys:
77 raise ApexSigningError('Failed to find signing keys for apk file {} in'
78 ' apex {}. Use "-e <apkname>=" to specify a key'
79 .format(entry, self.apex_path))
80 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
81 'overlay/']):
82 logger.warning('Apk path does not contain the intended directory name:'
83 ' %s', entry)
84
85 payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
86 apk_entries, apk_keys)
87 if not has_signed_apk:
88 logger.info('No apk file has been signed in %s', self.apex_path)
89 return self.apex_path
90
91 return self.RepackApexPayload(payload_dir, payload_key, payload_public_key)
92
93 def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
94 """Extracts the payload image and signs the containing apk files."""
95 payload_dir = common.MakeTempDir()
96 extract_cmd = ['deapexer', 'extract', self.apex_path, payload_dir]
97 common.RunAndCheckOutput(extract_cmd)
98
99 has_signed_apk = False
100 for entry in apk_entries:
101 apk_path = os.path.join(payload_dir, entry)
102 assert os.path.exists(self.apex_path)
103
104 key_name = apk_keys.get(os.path.basename(entry))
105 if key_name in common.SPECIAL_CERT_STRINGS:
106 logger.info('Not signing: %s due to special cert string', apk_path)
107 continue
108
109 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
110 # Rename the unsigned apk and overwrite the original apk path with the
111 # signed apk file.
112 unsigned_apk = common.MakeTempFile()
113 os.rename(apk_path, unsigned_apk)
114 common.SignFile(unsigned_apk, apk_path, key_name, self.key_passwords,
115 codename_to_api_level_map=self.codename_to_api_level_map)
116 has_signed_apk = True
117 return payload_dir, has_signed_apk
118
119 def RepackApexPayload(self, payload_dir, payload_key, payload_public_key):
120 """Rebuilds the apex file with the updated payload directory."""
121 apex_dir = common.MakeTempDir()
122 # Extract the apex file and reuse its meta files as repack parameters.
123 common.UnzipToDir(self.apex_path, apex_dir)
124
125 android_jar_path = common.OPTIONS.android_jar_path
126 if not android_jar_path:
Tianjie Xu61a792f2020-01-28 10:54:50 -0800127 android_jar_path = os.path.join(os.environ.get('ANDROID_BUILD_TOP', ''),
128 'prebuilts', 'sdk', 'current', 'public',
129 'android.jar')
Tianjie Xu88a759d2020-01-23 10:47:54 -0800130 logger.warning('android_jar_path not found in options, falling back to'
131 ' use %s', android_jar_path)
132
133 arguments_dict = {
134 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
135 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800136 'android_jar_path': android_jar_path,
137 'key': payload_key,
138 'pubkey': payload_public_key,
139 }
140 for filename in arguments_dict.values():
141 assert os.path.exists(filename), 'file {} not found'.format(filename)
142
143 # The repack process will add back these files later in the payload image.
144 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
145 path = os.path.join(payload_dir, name)
146 if os.path.isfile(path):
147 os.remove(path)
148 elif os.path.isdir(path):
149 shutil.rmtree(path)
150
151 repacked_apex = common.MakeTempFile(suffix='.apex')
152 repack_cmd = ['apexer', '--force', '--include_build_info',
153 '--do_not_check_keyname', '--apexer_tool_path',
154 os.getenv('PATH')]
155 for key, val in arguments_dict.items():
156 repack_cmd.append('--' + key)
157 repack_cmd.append(val)
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800158 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800159 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
160 if os.path.exists(manifest_json):
161 repack_cmd.append('--manifest_json')
162 repack_cmd.append(manifest_json)
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800163 assets_dir = os.path.join(apex_dir, 'assets')
164 if os.path.isdir(assets_dir):
165 repack_cmd.append('--assets_dir')
166 repack_cmd.append(assets_dir)
167
Tianjie Xu88a759d2020-01-23 10:47:54 -0800168 repack_cmd.append(payload_dir)
169 repack_cmd.append(repacked_apex)
170 common.RunAndCheckOutput(repack_cmd)
171
172 return repacked_apex
173
174
Tao Bao1ac886e2019-06-26 11:58:22 -0700175def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Tao Bao448004a2019-09-19 07:55:02 -0700176 algorithm, salt, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700177 """Signs a given payload_file with the payload key."""
178 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700179 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700180 '--do_not_generate_fec',
181 '--algorithm', algorithm,
182 '--key', payload_key_path,
183 '--prop', 'apex.key:{}'.format(payload_key_name),
184 '--image', payload_file,
185 '--salt', salt]
Tao Bao448004a2019-09-19 07:55:02 -0700186 if no_hashtree:
187 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700188 if signing_args:
189 cmd.extend(shlex.split(signing_args))
190
191 try:
192 common.RunAndCheckOutput(cmd)
193 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700194 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700195 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700196 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700197
198 # Verify the signed payload image with specified public key.
199 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700200 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700201
202
Tao Bao448004a2019-09-19 07:55:02 -0700203def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700204 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700205 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700206 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700207 if no_hashtree:
208 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700209 try:
210 common.RunAndCheckOutput(cmd)
211 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700212 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700213 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700214 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700215
216
Tao Bao1ac886e2019-06-26 11:58:22 -0700217def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700218 """Parses the APEX payload info.
219
220 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700221 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700222 payload_path: The path to the payload image.
223
224 Raises:
225 ApexInfoError on parsing errors.
226
227 Returns:
228 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700229 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700230 """
231 if not os.path.exists(payload_path):
232 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
233
Tao Bao1ac886e2019-06-26 11:58:22 -0700234 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700235 try:
236 output = common.RunAndCheckOutput(cmd)
237 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700238 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700239 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700240 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700241
Tao Bao448004a2019-09-19 07:55:02 -0700242 # Extract the Algorithm / Salt / Prop info / Tree size from payload (i.e. an
243 # image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700244 # Algorithm: SHA256_RSA4096
245 PAYLOAD_INFO_PATTERN = (
Tao Bao448004a2019-09-19 07:55:02 -0700246 r'^\s*(?P<key>Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700247 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
248
249 payload_info = {}
250 for line in output.split('\n'):
251 line_info = payload_info_matcher.match(line)
252 if not line_info:
253 continue
254
255 key, value = line_info.group('key'), line_info.group('value')
256
257 if key == 'Prop':
258 # Further extract the property key-value pair, from a 'Prop:' line. For
259 # example,
260 # Prop: apex.key -> 'com.android.runtime'
261 # Note that avbtool writes single or double quotes around values.
262 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
263
264 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
265 prop = prop_matcher.match(value)
266 if not prop:
267 raise ApexInfoError(
268 'Failed to parse prop string {}'.format(value))
269
270 prop_key, prop_value = prop.group('key'), prop.group('value')
271 if prop_key == 'apex.key':
272 # avbtool dumps the prop value with repr(), which contains single /
273 # double quotes that we don't want.
274 payload_info[prop_key] = prop_value.strip('\"\'')
275
276 else:
277 payload_info[key] = value
278
279 # Sanity check.
280 for key in ('Algorithm', 'Salt', 'apex.key'):
281 if key not in payload_info:
282 raise ApexInfoError(
283 'Failed to find {} prop in {}'.format(key, payload_path))
284
285 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700286
287
Tao Bao1ac886e2019-06-26 11:58:22 -0700288def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800289 apk_keys, codename_to_api_level_map,
290 no_hashtree, signing_args=None):
Tao Baoe7354ba2019-05-09 16:54:15 -0700291 """Signs the current APEX with the given payload/container keys.
292
293 Args:
294 apex_data: Raw APEX data.
295 payload_key: The path to payload signing key (w/ extension).
296 container_key: The path to container signing key (w/o extension).
297 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800298 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700299 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700300 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700301 signing_args: Additional args to be passed to the payload signer.
302
303 Returns:
304 The path to the signed APEX file.
305 """
306 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
307 with open(apex_file, 'wb') as apex_fp:
308 apex_fp.write(apex_data)
309
310 APEX_PAYLOAD_IMAGE = 'apex_payload.img'
311 APEX_PUBKEY = 'apex_pubkey'
312
Tianjie Xu88a759d2020-01-23 10:47:54 -0800313 # 1. Extract the apex payload image and sign the containing apk files. Repack
314 # the apex file after signing.
315 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
316 apk_signer = ApexApkSigner(apex_file, container_pw,
317 codename_to_api_level_map)
318 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key,
319 payload_public_key)
320
321 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700322 # payload_key.
323 payload_dir = common.MakeTempDir(prefix='apex-payload-')
324 with zipfile.ZipFile(apex_file) as apex_fd:
325 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700326 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700327
Tao Bao1ac886e2019-06-26 11:58:22 -0700328 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700329 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700330 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700331 payload_file,
332 payload_key,
333 payload_info['apex.key'],
334 payload_info['Algorithm'],
335 payload_info['Salt'],
Tao Bao448004a2019-09-19 07:55:02 -0700336 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700337 signing_args)
338
Tianjie Xu88a759d2020-01-23 10:47:54 -0800339 # 2b. Update the embedded payload public key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700340
341 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700342 if APEX_PUBKEY in zip_items:
343 common.ZipDelete(apex_file, APEX_PUBKEY)
Tao Baoe7354ba2019-05-09 16:54:15 -0700344 apex_zip = zipfile.ZipFile(apex_file, 'a')
345 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
346 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
347 common.ZipClose(apex_zip)
348
Tianjie Xu88a759d2020-01-23 10:47:54 -0800349 # 3. Align the files at page boundary (same as in apexer).
Tao Baoe7354ba2019-05-09 16:54:15 -0700350 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
351 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
352
Tianjie Xu88a759d2020-01-23 10:47:54 -0800353 # 4. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700354 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
355
356 # Specify the 4K alignment when calling SignApk.
357 extra_signapk_args = OPTIONS.extra_signapk_args[:]
358 extra_signapk_args.extend(['-a', '4096'])
359
360 common.SignFile(
361 aligned_apex,
362 signed_apex,
363 container_key,
364 container_pw,
365 codename_to_api_level_map=codename_to_api_level_map,
366 extra_signapk_args=extra_signapk_args)
367
368 return signed_apex