blob: 4ca091700c5d60948b2225ab190cb4eb89363166 [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
Tianjie Xucea6ad12020-01-30 17:12:05 -080053 def ProcessApexFile(self, apk_keys, payload_key, payload_public_key,
54 signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080055 """Scans and signs the apk files and repack the apex
56
57 Args:
58 apk_keys: A dict that holds the signing keys for apk files.
59 payload_key: The path to the apex payload signing key.
60 payload_public_key: The path to the public key corresponding to the
61 payload signing key.
62
63 Returns:
64 The repacked apex file containing the signed apk files.
65 """
66 list_cmd = ['deapexer', 'list', self.apex_path]
67 entries_names = common.RunAndCheckOutput(list_cmd).split()
68 apk_entries = [name for name in entries_names if name.endswith('.apk')]
69
70 # No need to sign and repack, return the original apex path.
71 if not apk_entries:
72 logger.info('No apk file to sign in %s', self.apex_path)
73 return self.apex_path
74
75 for entry in apk_entries:
76 apk_name = os.path.basename(entry)
77 if apk_name not in apk_keys:
78 raise ApexSigningError('Failed to find signing keys for apk file {} in'
79 ' apex {}. Use "-e <apkname>=" to specify a key'
80 .format(entry, self.apex_path))
81 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
82 'overlay/']):
83 logger.warning('Apk path does not contain the intended directory name:'
84 ' %s', entry)
85
86 payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
87 apk_entries, apk_keys)
88 if not has_signed_apk:
89 logger.info('No apk file has been signed in %s', self.apex_path)
90 return self.apex_path
91
Tianjie Xucea6ad12020-01-30 17:12:05 -080092 return self.RepackApexPayload(payload_dir, payload_key, payload_public_key,
93 signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -080094
95 def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
96 """Extracts the payload image and signs the containing apk files."""
97 payload_dir = common.MakeTempDir()
98 extract_cmd = ['deapexer', 'extract', self.apex_path, payload_dir]
99 common.RunAndCheckOutput(extract_cmd)
100
101 has_signed_apk = False
102 for entry in apk_entries:
103 apk_path = os.path.join(payload_dir, entry)
104 assert os.path.exists(self.apex_path)
105
106 key_name = apk_keys.get(os.path.basename(entry))
107 if key_name in common.SPECIAL_CERT_STRINGS:
108 logger.info('Not signing: %s due to special cert string', apk_path)
109 continue
110
111 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
112 # Rename the unsigned apk and overwrite the original apk path with the
113 # signed apk file.
114 unsigned_apk = common.MakeTempFile()
115 os.rename(apk_path, unsigned_apk)
116 common.SignFile(unsigned_apk, apk_path, key_name, self.key_passwords,
117 codename_to_api_level_map=self.codename_to_api_level_map)
118 has_signed_apk = True
119 return payload_dir, has_signed_apk
120
Tianjie Xucea6ad12020-01-30 17:12:05 -0800121 def RepackApexPayload(self, payload_dir, payload_key, payload_public_key,
122 signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800123 """Rebuilds the apex file with the updated payload directory."""
124 apex_dir = common.MakeTempDir()
125 # Extract the apex file and reuse its meta files as repack parameters.
126 common.UnzipToDir(self.apex_path, apex_dir)
127
128 android_jar_path = common.OPTIONS.android_jar_path
129 if not android_jar_path:
Tianjie Xu61a792f2020-01-28 10:54:50 -0800130 android_jar_path = os.path.join(os.environ.get('ANDROID_BUILD_TOP', ''),
131 'prebuilts', 'sdk', 'current', 'public',
132 'android.jar')
Tianjie Xu88a759d2020-01-23 10:47:54 -0800133 logger.warning('android_jar_path not found in options, falling back to'
134 ' use %s', android_jar_path)
135
136 arguments_dict = {
137 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
138 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800139 'android_jar_path': android_jar_path,
140 'key': payload_key,
141 'pubkey': payload_public_key,
142 }
143 for filename in arguments_dict.values():
144 assert os.path.exists(filename), 'file {} not found'.format(filename)
145
146 # The repack process will add back these files later in the payload image.
147 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
148 path = os.path.join(payload_dir, name)
149 if os.path.isfile(path):
150 os.remove(path)
151 elif os.path.isdir(path):
152 shutil.rmtree(path)
153
154 repacked_apex = common.MakeTempFile(suffix='.apex')
155 repack_cmd = ['apexer', '--force', '--include_build_info',
156 '--do_not_check_keyname', '--apexer_tool_path',
157 os.getenv('PATH')]
158 for key, val in arguments_dict.items():
Tianjie Xucea6ad12020-01-30 17:12:05 -0800159 repack_cmd.extend(['--' + key, val])
160 if signing_args:
161 repack_cmd.extend(['--signing_args', signing_args])
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800162 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800163 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
164 if os.path.exists(manifest_json):
Tianjie Xucea6ad12020-01-30 17:12:05 -0800165 repack_cmd.extend(['--manifest_json', manifest_json])
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800166 assets_dir = os.path.join(apex_dir, 'assets')
167 if os.path.isdir(assets_dir):
Tianjie Xucea6ad12020-01-30 17:12:05 -0800168 repack_cmd.extend(['--assets_dir', assets_dir])
169 repack_cmd.extend([payload_dir, repacked_apex])
170 if OPTIONS.verbose:
171 repack_cmd.append('-v')
Tianjie Xu88a759d2020-01-23 10:47:54 -0800172 common.RunAndCheckOutput(repack_cmd)
173
174 return repacked_apex
175
176
Tao Bao1ac886e2019-06-26 11:58:22 -0700177def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Tao Bao448004a2019-09-19 07:55:02 -0700178 algorithm, salt, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700179 """Signs a given payload_file with the payload key."""
180 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700181 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700182 '--do_not_generate_fec',
183 '--algorithm', algorithm,
184 '--key', payload_key_path,
185 '--prop', 'apex.key:{}'.format(payload_key_name),
186 '--image', payload_file,
187 '--salt', salt]
Tao Bao448004a2019-09-19 07:55:02 -0700188 if no_hashtree:
189 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700190 if signing_args:
191 cmd.extend(shlex.split(signing_args))
192
193 try:
194 common.RunAndCheckOutput(cmd)
195 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700196 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700197 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700198 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700199
200 # Verify the signed payload image with specified public key.
201 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700202 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700203
204
Tao Bao448004a2019-09-19 07:55:02 -0700205def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700206 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700207 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700208 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700209 if no_hashtree:
210 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700211 try:
212 common.RunAndCheckOutput(cmd)
213 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700214 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700215 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700216 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700217
218
Tao Bao1ac886e2019-06-26 11:58:22 -0700219def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700220 """Parses the APEX payload info.
221
222 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700223 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700224 payload_path: The path to the payload image.
225
226 Raises:
227 ApexInfoError on parsing errors.
228
229 Returns:
230 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700231 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700232 """
233 if not os.path.exists(payload_path):
234 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
235
Tao Bao1ac886e2019-06-26 11:58:22 -0700236 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700237 try:
238 output = common.RunAndCheckOutput(cmd)
239 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700240 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700241 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700242 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700243
Tao Bao448004a2019-09-19 07:55:02 -0700244 # Extract the Algorithm / Salt / Prop info / Tree size from payload (i.e. an
245 # image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700246 # Algorithm: SHA256_RSA4096
247 PAYLOAD_INFO_PATTERN = (
Tao Bao448004a2019-09-19 07:55:02 -0700248 r'^\s*(?P<key>Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700249 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
250
251 payload_info = {}
252 for line in output.split('\n'):
253 line_info = payload_info_matcher.match(line)
254 if not line_info:
255 continue
256
257 key, value = line_info.group('key'), line_info.group('value')
258
259 if key == 'Prop':
260 # Further extract the property key-value pair, from a 'Prop:' line. For
261 # example,
262 # Prop: apex.key -> 'com.android.runtime'
263 # Note that avbtool writes single or double quotes around values.
264 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
265
266 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
267 prop = prop_matcher.match(value)
268 if not prop:
269 raise ApexInfoError(
270 'Failed to parse prop string {}'.format(value))
271
272 prop_key, prop_value = prop.group('key'), prop.group('value')
273 if prop_key == 'apex.key':
274 # avbtool dumps the prop value with repr(), which contains single /
275 # double quotes that we don't want.
276 payload_info[prop_key] = prop_value.strip('\"\'')
277
278 else:
279 payload_info[key] = value
280
281 # Sanity check.
282 for key in ('Algorithm', 'Salt', 'apex.key'):
283 if key not in payload_info:
284 raise ApexInfoError(
285 'Failed to find {} prop in {}'.format(key, payload_path))
286
287 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700288
289
Tao Bao1ac886e2019-06-26 11:58:22 -0700290def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800291 apk_keys, codename_to_api_level_map,
292 no_hashtree, signing_args=None):
Tao Baoe7354ba2019-05-09 16:54:15 -0700293 """Signs the current APEX with the given payload/container keys.
294
295 Args:
296 apex_data: Raw APEX data.
297 payload_key: The path to payload signing key (w/ extension).
298 container_key: The path to container signing key (w/o extension).
299 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800300 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700301 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700302 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700303 signing_args: Additional args to be passed to the payload signer.
304
305 Returns:
306 The path to the signed APEX file.
307 """
308 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
309 with open(apex_file, 'wb') as apex_fp:
310 apex_fp.write(apex_data)
311
312 APEX_PAYLOAD_IMAGE = 'apex_payload.img'
313 APEX_PUBKEY = 'apex_pubkey'
314
Tianjie Xu88a759d2020-01-23 10:47:54 -0800315 # 1. Extract the apex payload image and sign the containing apk files. Repack
316 # the apex file after signing.
317 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
318 apk_signer = ApexApkSigner(apex_file, container_pw,
319 codename_to_api_level_map)
320 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key,
Tianjie Xucea6ad12020-01-30 17:12:05 -0800321 payload_public_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800322
323 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700324 # payload_key.
325 payload_dir = common.MakeTempDir(prefix='apex-payload-')
326 with zipfile.ZipFile(apex_file) as apex_fd:
327 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700328 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700329
Tao Bao1ac886e2019-06-26 11:58:22 -0700330 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700331 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700332 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700333 payload_file,
334 payload_key,
335 payload_info['apex.key'],
336 payload_info['Algorithm'],
337 payload_info['Salt'],
Tao Bao448004a2019-09-19 07:55:02 -0700338 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700339 signing_args)
340
Tianjie Xu88a759d2020-01-23 10:47:54 -0800341 # 2b. Update the embedded payload public key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700342
343 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700344 if APEX_PUBKEY in zip_items:
345 common.ZipDelete(apex_file, APEX_PUBKEY)
Tao Baoe7354ba2019-05-09 16:54:15 -0700346 apex_zip = zipfile.ZipFile(apex_file, 'a')
347 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
348 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
349 common.ZipClose(apex_zip)
350
Tianjie Xu88a759d2020-01-23 10:47:54 -0800351 # 3. Align the files at page boundary (same as in apexer).
Tao Baoe7354ba2019-05-09 16:54:15 -0700352 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
353 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
354
Tianjie Xu88a759d2020-01-23 10:47:54 -0800355 # 4. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700356 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
357
358 # Specify the 4K alignment when calling SignApk.
359 extra_signapk_args = OPTIONS.extra_signapk_args[:]
360 extra_signapk_args.extend(['-a', '4096'])
361
362 common.SignFile(
363 aligned_apex,
364 signed_apex,
365 container_key,
366 container_pw,
367 codename_to_api_level_map=codename_to_api_level_map,
368 extra_signapk_args=extra_signapk_args)
369
370 return signed_apex