blob: dc6e3ca82f6eea8efcbcfc6d9e532c497bb6b7fc [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
Tianjiec180a5d2020-03-23 18:14:09 -070030APEX_PAYLOAD_IMAGE = 'apex_payload.img'
31
Tao Bao1cd59f22019-03-15 15:13:01 -070032
33class ApexInfoError(Exception):
34 """An Exception raised during Apex Information command."""
35
36 def __init__(self, message):
37 Exception.__init__(self, message)
38
39
40class ApexSigningError(Exception):
41 """An Exception raised during Apex Payload signing."""
42
43 def __init__(self, message):
44 Exception.__init__(self, message)
45
46
Tianjie Xu88a759d2020-01-23 10:47:54 -080047class ApexApkSigner(object):
48 """Class to sign the apk files in a apex payload image and repack the apex"""
49
50 def __init__(self, apex_path, key_passwords, codename_to_api_level_map):
51 self.apex_path = apex_path
Oleh Cherpake555ab12020-10-05 17:04:59 +030052 if not key_passwords:
53 self.key_passwords = dict()
54 else:
55 self.key_passwords = key_passwords
Tianjie Xu88a759d2020-01-23 10:47:54 -080056 self.codename_to_api_level_map = codename_to_api_level_map
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040057 self.debugfs_path = os.path.join(
58 OPTIONS.search_path, "bin", "debugfs_static")
Tianjie Xu88a759d2020-01-23 10:47:54 -080059
Baligh Uddin639b3b72020-03-25 20:50:23 -070060 def ProcessApexFile(self, apk_keys, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -080061 """Scans and signs the apk files and repack the apex
62
63 Args:
64 apk_keys: A dict that holds the signing keys for apk files.
Tianjie Xu88a759d2020-01-23 10:47:54 -080065
66 Returns:
67 The repacked apex file containing the signed apk files.
68 """
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040069 if not os.path.exists(self.debugfs_path):
Kelvin Zhangd6b799a2020-08-19 14:54:42 -040070 raise ApexSigningError(
71 "Couldn't find location of debugfs_static: " +
72 "Path {} does not exist. ".format(debugfs_path) +
73 "Make sure bin/debugfs_static can be found in -p <path>")
74 list_cmd = ['deapexer', '--debugfs_path',
Kelvin Zhangdd833dc2020-08-21 14:13:13 -040075 self.debugfs_path, 'list', self.apex_path]
Tianjie Xu88a759d2020-01-23 10:47:54 -080076 entries_names = common.RunAndCheckOutput(list_cmd).split()
77 apk_entries = [name for name in entries_names if name.endswith('.apk')]
78
79 # No need to sign and repack, return the original apex path.
80 if not apk_entries:
81 logger.info('No apk file to sign in %s', self.apex_path)
82 return self.apex_path
83
84 for entry in apk_entries:
85 apk_name = os.path.basename(entry)
86 if apk_name not in apk_keys:
87 raise ApexSigningError('Failed to find signing keys for apk file {} in'
88 ' apex {}. Use "-e <apkname>=" to specify a key'
89 .format(entry, self.apex_path))
90 if not any(dirname in entry for dirname in ['app/', 'priv-app/',
91 'overlay/']):
92 logger.warning('Apk path does not contain the intended directory name:'
93 ' %s', entry)
94
95 payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
96 apk_entries, apk_keys)
97 if not has_signed_apk:
98 logger.info('No apk file has been signed in %s', self.apex_path)
99 return self.apex_path
100
Baligh Uddin639b3b72020-03-25 20:50:23 -0700101 return self.RepackApexPayload(payload_dir, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800102
103 def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
104 """Extracts the payload image and signs the containing apk files."""
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400105 if not os.path.exists(self.debugfs_path):
106 raise ApexSigningError(
107 "Couldn't find location of debugfs_static: " +
108 "Path {} does not exist. ".format(debugfs_path) +
109 "Make sure bin/debugfs_static can be found in -p <path>")
Tianjie Xu88a759d2020-01-23 10:47:54 -0800110 payload_dir = common.MakeTempDir()
Kelvin Zhangdd833dc2020-08-21 14:13:13 -0400111 extract_cmd = ['deapexer', '--debugfs_path',
112 self.debugfs_path, 'extract', self.apex_path, payload_dir]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800113 common.RunAndCheckOutput(extract_cmd)
114
115 has_signed_apk = False
116 for entry in apk_entries:
117 apk_path = os.path.join(payload_dir, entry)
118 assert os.path.exists(self.apex_path)
119
120 key_name = apk_keys.get(os.path.basename(entry))
121 if key_name in common.SPECIAL_CERT_STRINGS:
122 logger.info('Not signing: %s due to special cert string', apk_path)
123 continue
124
125 logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
126 # Rename the unsigned apk and overwrite the original apk path with the
127 # signed apk file.
128 unsigned_apk = common.MakeTempFile()
129 os.rename(apk_path, unsigned_apk)
Oleh Cherpake555ab12020-10-05 17:04:59 +0300130 common.SignFile(unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800131 codename_to_api_level_map=self.codename_to_api_level_map)
132 has_signed_apk = True
133 return payload_dir, has_signed_apk
134
Baligh Uddin639b3b72020-03-25 20:50:23 -0700135 def RepackApexPayload(self, payload_dir, payload_key, signing_args=None):
Tianjie Xu88a759d2020-01-23 10:47:54 -0800136 """Rebuilds the apex file with the updated payload directory."""
137 apex_dir = common.MakeTempDir()
138 # Extract the apex file and reuse its meta files as repack parameters.
139 common.UnzipToDir(self.apex_path, apex_dir)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800140 arguments_dict = {
141 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
142 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
Tianjie Xu88a759d2020-01-23 10:47:54 -0800143 'key': payload_key,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800144 }
145 for filename in arguments_dict.values():
146 assert os.path.exists(filename), 'file {} not found'.format(filename)
147
148 # The repack process will add back these files later in the payload image.
149 for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
150 path = os.path.join(payload_dir, name)
151 if os.path.isfile(path):
152 os.remove(path)
153 elif os.path.isdir(path):
154 shutil.rmtree(path)
155
Tianjiec180a5d2020-03-23 18:14:09 -0700156 # TODO(xunchang) the signing process can be improved by using
157 # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for
158 # the signing arguments, e.g. algorithm, salt, etc.
159 payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE)
160 generate_image_cmd = ['apexer', '--force', '--payload_only',
161 '--do_not_check_keyname', '--apexer_tool_path',
162 os.getenv('PATH')]
Tianjie Xu88a759d2020-01-23 10:47:54 -0800163 for key, val in arguments_dict.items():
Tianjiec180a5d2020-03-23 18:14:09 -0700164 generate_image_cmd.extend(['--' + key, val])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700165
166 # Add quote to the signing_args as we will pass
167 # --signing_args "--signing_helper_with_files=%path" to apexer
168 if signing_args:
Kelvin Zhangd6b799a2020-08-19 14:54:42 -0400169 generate_image_cmd.extend(
170 ['--signing_args', '"{}"'.format(signing_args)])
Baligh Uddin639b3b72020-03-25 20:50:23 -0700171
Tianjie Xu83bd55c2020-01-29 11:37:43 -0800172 # optional arguments for apex repacking
Tianjie Xu88a759d2020-01-23 10:47:54 -0800173 manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
174 if os.path.exists(manifest_json):
Tianjiec180a5d2020-03-23 18:14:09 -0700175 generate_image_cmd.extend(['--manifest_json', manifest_json])
176 generate_image_cmd.extend([payload_dir, payload_img])
Tianjie Xucea6ad12020-01-30 17:12:05 -0800177 if OPTIONS.verbose:
Tianjiec180a5d2020-03-23 18:14:09 -0700178 generate_image_cmd.append('-v')
179 common.RunAndCheckOutput(generate_image_cmd)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800180
Tianjiec180a5d2020-03-23 18:14:09 -0700181 # Add the payload image back to the apex file.
182 common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400183 with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex:
Tianjiec180a5d2020-03-23 18:14:09 -0700184 common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE,
185 compress_type=zipfile.ZIP_STORED)
186 return self.apex_path
Tianjie Xu88a759d2020-01-23 10:47:54 -0800187
188
Tao Bao1ac886e2019-06-26 11:58:22 -0700189def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Jiyong Parka1887f32020-05-19 23:18:03 +0900190 algorithm, salt, hash_algorithm, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -0700191 """Signs a given payload_file with the payload key."""
192 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -0700193 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -0700194 '--do_not_generate_fec',
195 '--algorithm', algorithm,
196 '--key', payload_key_path,
197 '--prop', 'apex.key:{}'.format(payload_key_name),
198 '--image', payload_file,
Jiyong Parka1887f32020-05-19 23:18:03 +0900199 '--salt', salt,
200 '--hash_algorithm', hash_algorithm]
Tao Bao448004a2019-09-19 07:55:02 -0700201 if no_hashtree:
202 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700203 if signing_args:
204 cmd.extend(shlex.split(signing_args))
205
206 try:
207 common.RunAndCheckOutput(cmd)
208 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700209 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700210 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700211 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700212
213 # Verify the signed payload image with specified public key.
214 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -0700215 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -0700216
217
Tao Bao448004a2019-09-19 07:55:02 -0700218def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -0700219 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -0700220 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -0700221 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -0700222 if no_hashtree:
223 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -0700224 try:
225 common.RunAndCheckOutput(cmd)
226 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700227 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700228 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700229 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700230
231
Tao Bao1ac886e2019-06-26 11:58:22 -0700232def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -0700233 """Parses the APEX payload info.
234
235 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -0700236 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -0700237 payload_path: The path to the payload image.
238
239 Raises:
240 ApexInfoError on parsing errors.
241
242 Returns:
243 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -0700244 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -0700245 """
246 if not os.path.exists(payload_path):
247 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
248
Tao Bao1ac886e2019-06-26 11:58:22 -0700249 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700250 try:
251 output = common.RunAndCheckOutput(cmd)
252 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700253 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700254 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700255 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700256
Jiyong Parka1887f32020-05-19 23:18:03 +0900257 # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from
258 # payload (i.e. an image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700259 # Algorithm: SHA256_RSA4096
260 PAYLOAD_INFO_PATTERN = (
Jiyong Parka1887f32020-05-19 23:18:03 +0900261 r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700262 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
263
264 payload_info = {}
265 for line in output.split('\n'):
266 line_info = payload_info_matcher.match(line)
267 if not line_info:
268 continue
269
270 key, value = line_info.group('key'), line_info.group('value')
271
272 if key == 'Prop':
273 # Further extract the property key-value pair, from a 'Prop:' line. For
274 # example,
275 # Prop: apex.key -> 'com.android.runtime'
276 # Note that avbtool writes single or double quotes around values.
277 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
278
279 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
280 prop = prop_matcher.match(value)
281 if not prop:
282 raise ApexInfoError(
283 'Failed to parse prop string {}'.format(value))
284
285 prop_key, prop_value = prop.group('key'), prop.group('value')
286 if prop_key == 'apex.key':
287 # avbtool dumps the prop value with repr(), which contains single /
288 # double quotes that we don't want.
289 payload_info[prop_key] = prop_value.strip('\"\'')
290
291 else:
292 payload_info[key] = value
293
Ivan Lozanob021b2a2020-07-28 09:31:06 -0400294 # Validation check.
Jiyong Parka1887f32020-05-19 23:18:03 +0900295 for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'):
Tao Bao1cd59f22019-03-15 15:13:01 -0700296 if key not in payload_info:
297 raise ApexInfoError(
298 'Failed to find {} prop in {}'.format(key, payload_path))
299
300 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700301
302
Tao Bao1ac886e2019-06-26 11:58:22 -0700303def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Tianjie Xu88a759d2020-01-23 10:47:54 -0800304 apk_keys, codename_to_api_level_map,
305 no_hashtree, signing_args=None):
Tao Baoe7354ba2019-05-09 16:54:15 -0700306 """Signs the current APEX with the given payload/container keys.
307
308 Args:
309 apex_data: Raw APEX data.
310 payload_key: The path to payload signing key (w/ extension).
311 container_key: The path to container signing key (w/o extension).
312 container_pw: The matching password of the container_key, or None.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800313 apk_keys: A dict that holds the signing keys for apk files.
Tao Baoe7354ba2019-05-09 16:54:15 -0700314 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700315 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700316 signing_args: Additional args to be passed to the payload signer.
317
318 Returns:
319 The path to the signed APEX file.
320 """
321 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
322 with open(apex_file, 'wb') as apex_fp:
323 apex_fp.write(apex_data)
324
Tao Baoe7354ba2019-05-09 16:54:15 -0700325 APEX_PUBKEY = 'apex_pubkey'
326
Tianjie Xu88a759d2020-01-23 10:47:54 -0800327 # 1. Extract the apex payload image and sign the containing apk files. Repack
328 # the apex file after signing.
Tianjie Xu88a759d2020-01-23 10:47:54 -0800329 apk_signer = ApexApkSigner(apex_file, container_pw,
330 codename_to_api_level_map)
Baligh Uddin639b3b72020-03-25 20:50:23 -0700331 apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args)
Tianjie Xu88a759d2020-01-23 10:47:54 -0800332
333 # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
Tao Baoe7354ba2019-05-09 16:54:15 -0700334 # payload_key.
335 payload_dir = common.MakeTempDir(prefix='apex-payload-')
336 with zipfile.ZipFile(apex_file) as apex_fd:
337 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700338 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700339
Tao Bao1ac886e2019-06-26 11:58:22 -0700340 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700341 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700342 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700343 payload_file,
344 payload_key,
345 payload_info['apex.key'],
346 payload_info['Algorithm'],
347 payload_info['Salt'],
Jiyong Parka1887f32020-05-19 23:18:03 +0900348 payload_info['Hash Algorithm'],
Tao Bao448004a2019-09-19 07:55:02 -0700349 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700350 signing_args)
351
Tianjie Xu88a759d2020-01-23 10:47:54 -0800352 # 2b. Update the embedded payload public key.
Tianjiec180a5d2020-03-23 18:14:09 -0700353 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700354 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700355 if APEX_PUBKEY in zip_items:
356 common.ZipDelete(apex_file, APEX_PUBKEY)
Kelvin Zhang928c2342020-09-22 16:15:57 -0400357 apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True)
Tao Baoe7354ba2019-05-09 16:54:15 -0700358 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
359 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
360 common.ZipClose(apex_zip)
361
Tianjie Xu88a759d2020-01-23 10:47:54 -0800362 # 3. Align the files at page boundary (same as in apexer).
Tao Baoe7354ba2019-05-09 16:54:15 -0700363 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
364 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
365
Tianjie Xu88a759d2020-01-23 10:47:54 -0800366 # 4. Sign the APEX container with container_key.
Tao Baoe7354ba2019-05-09 16:54:15 -0700367 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
368
369 # Specify the 4K alignment when calling SignApk.
370 extra_signapk_args = OPTIONS.extra_signapk_args[:]
371 extra_signapk_args.extend(['-a', '4096'])
372
373 common.SignFile(
374 aligned_apex,
375 signed_apex,
376 container_key,
Oleh Cherpake555ab12020-10-05 17:04:59 +0300377 container_pw.get(container_key),
Tao Baoe7354ba2019-05-09 16:54:15 -0700378 codename_to_api_level_map=codename_to_api_level_map,
379 extra_signapk_args=extra_signapk_args)
380
381 return signed_apex