Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 1 | #!/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 | |
| 17 | import logging |
| 18 | import os.path |
| 19 | import re |
| 20 | import shlex |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 21 | import shutil |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 22 | import zipfile |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 23 | |
| 24 | import common |
| 25 | |
| 26 | logger = logging.getLogger(__name__) |
| 27 | |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 28 | OPTIONS = common.OPTIONS |
| 29 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 30 | APEX_PAYLOAD_IMAGE = 'apex_payload.img' |
| 31 | |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 32 | |
| 33 | class ApexInfoError(Exception): |
| 34 | """An Exception raised during Apex Information command.""" |
| 35 | |
| 36 | def __init__(self, message): |
| 37 | Exception.__init__(self, message) |
| 38 | |
| 39 | |
| 40 | class ApexSigningError(Exception): |
| 41 | """An Exception raised during Apex Payload signing.""" |
| 42 | |
| 43 | def __init__(self, message): |
| 44 | Exception.__init__(self, message) |
| 45 | |
| 46 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 47 | class 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 |
| 52 | self.key_passwords = key_passwords |
| 53 | self.codename_to_api_level_map = codename_to_api_level_map |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 54 | self.debugfs_path = os.path.join( |
| 55 | OPTIONS.search_path, "bin", "debugfs_static") |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 56 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 57 | def ProcessApexFile(self, apk_keys, payload_key, signing_args=None): |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 58 | """Scans and signs the apk files and repack the apex |
| 59 | |
| 60 | Args: |
| 61 | apk_keys: A dict that holds the signing keys for apk files. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 62 | |
| 63 | Returns: |
| 64 | The repacked apex file containing the signed apk files. |
| 65 | """ |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 66 | if not os.path.exists(self.debugfs_path): |
Kelvin Zhang | d6b799a | 2020-08-19 14:54:42 -0400 | [diff] [blame] | 67 | raise ApexSigningError( |
| 68 | "Couldn't find location of debugfs_static: " + |
| 69 | "Path {} does not exist. ".format(debugfs_path) + |
| 70 | "Make sure bin/debugfs_static can be found in -p <path>") |
| 71 | list_cmd = ['deapexer', '--debugfs_path', |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 72 | self.debugfs_path, 'list', self.apex_path] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 73 | entries_names = common.RunAndCheckOutput(list_cmd).split() |
| 74 | apk_entries = [name for name in entries_names if name.endswith('.apk')] |
| 75 | |
| 76 | # No need to sign and repack, return the original apex path. |
| 77 | if not apk_entries: |
| 78 | logger.info('No apk file to sign in %s', self.apex_path) |
| 79 | return self.apex_path |
| 80 | |
| 81 | for entry in apk_entries: |
| 82 | apk_name = os.path.basename(entry) |
| 83 | if apk_name not in apk_keys: |
| 84 | raise ApexSigningError('Failed to find signing keys for apk file {} in' |
| 85 | ' apex {}. Use "-e <apkname>=" to specify a key' |
| 86 | .format(entry, self.apex_path)) |
| 87 | if not any(dirname in entry for dirname in ['app/', 'priv-app/', |
| 88 | 'overlay/']): |
| 89 | logger.warning('Apk path does not contain the intended directory name:' |
| 90 | ' %s', entry) |
| 91 | |
| 92 | payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks( |
| 93 | apk_entries, apk_keys) |
| 94 | if not has_signed_apk: |
| 95 | logger.info('No apk file has been signed in %s', self.apex_path) |
| 96 | return self.apex_path |
| 97 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 98 | return self.RepackApexPayload(payload_dir, payload_key, signing_args) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 99 | |
| 100 | def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys): |
| 101 | """Extracts the payload image and signs the containing apk files.""" |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 102 | if not os.path.exists(self.debugfs_path): |
| 103 | raise ApexSigningError( |
| 104 | "Couldn't find location of debugfs_static: " + |
| 105 | "Path {} does not exist. ".format(debugfs_path) + |
| 106 | "Make sure bin/debugfs_static can be found in -p <path>") |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 107 | payload_dir = common.MakeTempDir() |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 108 | extract_cmd = ['deapexer', '--debugfs_path', |
| 109 | self.debugfs_path, 'extract', self.apex_path, payload_dir] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 110 | common.RunAndCheckOutput(extract_cmd) |
| 111 | |
| 112 | has_signed_apk = False |
| 113 | for entry in apk_entries: |
| 114 | apk_path = os.path.join(payload_dir, entry) |
| 115 | assert os.path.exists(self.apex_path) |
| 116 | |
| 117 | key_name = apk_keys.get(os.path.basename(entry)) |
| 118 | if key_name in common.SPECIAL_CERT_STRINGS: |
| 119 | logger.info('Not signing: %s due to special cert string', apk_path) |
| 120 | continue |
| 121 | |
| 122 | logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path) |
| 123 | # Rename the unsigned apk and overwrite the original apk path with the |
| 124 | # signed apk file. |
| 125 | unsigned_apk = common.MakeTempFile() |
| 126 | os.rename(apk_path, unsigned_apk) |
| 127 | common.SignFile(unsigned_apk, apk_path, key_name, self.key_passwords, |
| 128 | codename_to_api_level_map=self.codename_to_api_level_map) |
| 129 | has_signed_apk = True |
| 130 | return payload_dir, has_signed_apk |
| 131 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 132 | def RepackApexPayload(self, payload_dir, payload_key, signing_args=None): |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 133 | """Rebuilds the apex file with the updated payload directory.""" |
| 134 | apex_dir = common.MakeTempDir() |
| 135 | # Extract the apex file and reuse its meta files as repack parameters. |
| 136 | common.UnzipToDir(self.apex_path, apex_dir) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 137 | arguments_dict = { |
| 138 | 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'), |
| 139 | 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'), |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 140 | 'key': payload_key, |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 141 | } |
| 142 | for filename in arguments_dict.values(): |
| 143 | assert os.path.exists(filename), 'file {} not found'.format(filename) |
| 144 | |
| 145 | # The repack process will add back these files later in the payload image. |
| 146 | for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']: |
| 147 | path = os.path.join(payload_dir, name) |
| 148 | if os.path.isfile(path): |
| 149 | os.remove(path) |
| 150 | elif os.path.isdir(path): |
| 151 | shutil.rmtree(path) |
| 152 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 153 | # TODO(xunchang) the signing process can be improved by using |
| 154 | # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for |
| 155 | # the signing arguments, e.g. algorithm, salt, etc. |
| 156 | payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE) |
| 157 | generate_image_cmd = ['apexer', '--force', '--payload_only', |
| 158 | '--do_not_check_keyname', '--apexer_tool_path', |
| 159 | os.getenv('PATH')] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 160 | for key, val in arguments_dict.items(): |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 161 | generate_image_cmd.extend(['--' + key, val]) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 162 | |
| 163 | # Add quote to the signing_args as we will pass |
| 164 | # --signing_args "--signing_helper_with_files=%path" to apexer |
| 165 | if signing_args: |
Kelvin Zhang | d6b799a | 2020-08-19 14:54:42 -0400 | [diff] [blame] | 166 | generate_image_cmd.extend( |
| 167 | ['--signing_args', '"{}"'.format(signing_args)]) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 168 | |
Tianjie Xu | 83bd55c | 2020-01-29 11:37:43 -0800 | [diff] [blame] | 169 | # optional arguments for apex repacking |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 170 | manifest_json = os.path.join(apex_dir, 'apex_manifest.json') |
| 171 | if os.path.exists(manifest_json): |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 172 | generate_image_cmd.extend(['--manifest_json', manifest_json]) |
| 173 | generate_image_cmd.extend([payload_dir, payload_img]) |
Tianjie Xu | cea6ad1 | 2020-01-30 17:12:05 -0800 | [diff] [blame] | 174 | if OPTIONS.verbose: |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 175 | generate_image_cmd.append('-v') |
| 176 | common.RunAndCheckOutput(generate_image_cmd) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 177 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 178 | # Add the payload image back to the apex file. |
| 179 | common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE) |
Kelvin Zhang | 928c234 | 2020-09-22 16:15:57 -0400 | [diff] [blame^] | 180 | with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex: |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 181 | common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE, |
| 182 | compress_type=zipfile.ZIP_STORED) |
| 183 | return self.apex_path |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 184 | |
| 185 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 186 | def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name, |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 187 | algorithm, salt, hash_algorithm, no_hashtree, signing_args=None): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 188 | """Signs a given payload_file with the payload key.""" |
| 189 | # Add the new footer. Old footer, if any, will be replaced by avbtool. |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 190 | cmd = [avbtool, 'add_hashtree_footer', |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 191 | '--do_not_generate_fec', |
| 192 | '--algorithm', algorithm, |
| 193 | '--key', payload_key_path, |
| 194 | '--prop', 'apex.key:{}'.format(payload_key_name), |
| 195 | '--image', payload_file, |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 196 | '--salt', salt, |
| 197 | '--hash_algorithm', hash_algorithm] |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 198 | if no_hashtree: |
| 199 | cmd.append('--no_hashtree') |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 200 | if signing_args: |
| 201 | cmd.extend(shlex.split(signing_args)) |
| 202 | |
| 203 | try: |
| 204 | common.RunAndCheckOutput(cmd) |
| 205 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 206 | raise ApexSigningError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 207 | 'Failed to sign APEX payload {} with {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 208 | payload_file, payload_key_path, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 209 | |
| 210 | # Verify the signed payload image with specified public key. |
| 211 | logger.info('Verifying %s', payload_file) |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 212 | VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 213 | |
| 214 | |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 215 | def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 216 | """Verifies the APEX payload signature with the given key.""" |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 217 | cmd = [avbtool, 'verify_image', '--image', payload_file, |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 218 | '--key', payload_key] |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 219 | if no_hashtree: |
| 220 | cmd.append('--accept_zeroed_hashtree') |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 221 | try: |
| 222 | common.RunAndCheckOutput(cmd) |
| 223 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 224 | raise ApexSigningError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 225 | 'Failed to validate payload signing for {} with {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 226 | payload_file, payload_key, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 227 | |
| 228 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 229 | def ParseApexPayloadInfo(avbtool, payload_path): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 230 | """Parses the APEX payload info. |
| 231 | |
| 232 | Args: |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 233 | avbtool: The AVB tool to use. |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 234 | payload_path: The path to the payload image. |
| 235 | |
| 236 | Raises: |
| 237 | ApexInfoError on parsing errors. |
| 238 | |
| 239 | Returns: |
| 240 | A dict that contains payload property-value pairs. The dict should at least |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 241 | contain Algorithm, Salt, Tree Size and apex.key. |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 242 | """ |
| 243 | if not os.path.exists(payload_path): |
| 244 | raise ApexInfoError('Failed to find image: {}'.format(payload_path)) |
| 245 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 246 | cmd = [avbtool, 'info_image', '--image', payload_path] |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 247 | try: |
| 248 | output = common.RunAndCheckOutput(cmd) |
| 249 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 250 | raise ApexInfoError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 251 | 'Failed to get APEX payload info for {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 252 | payload_path, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 253 | |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 254 | # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from |
| 255 | # payload (i.e. an image signed with avbtool). For example, |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 256 | # Algorithm: SHA256_RSA4096 |
| 257 | PAYLOAD_INFO_PATTERN = ( |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 258 | r'^\s*(?P<key>Algorithm|Hash Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$') |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 259 | payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN) |
| 260 | |
| 261 | payload_info = {} |
| 262 | for line in output.split('\n'): |
| 263 | line_info = payload_info_matcher.match(line) |
| 264 | if not line_info: |
| 265 | continue |
| 266 | |
| 267 | key, value = line_info.group('key'), line_info.group('value') |
| 268 | |
| 269 | if key == 'Prop': |
| 270 | # Further extract the property key-value pair, from a 'Prop:' line. For |
| 271 | # example, |
| 272 | # Prop: apex.key -> 'com.android.runtime' |
| 273 | # Note that avbtool writes single or double quotes around values. |
| 274 | PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$' |
| 275 | |
| 276 | prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN) |
| 277 | prop = prop_matcher.match(value) |
| 278 | if not prop: |
| 279 | raise ApexInfoError( |
| 280 | 'Failed to parse prop string {}'.format(value)) |
| 281 | |
| 282 | prop_key, prop_value = prop.group('key'), prop.group('value') |
| 283 | if prop_key == 'apex.key': |
| 284 | # avbtool dumps the prop value with repr(), which contains single / |
| 285 | # double quotes that we don't want. |
| 286 | payload_info[prop_key] = prop_value.strip('\"\'') |
| 287 | |
| 288 | else: |
| 289 | payload_info[key] = value |
| 290 | |
Ivan Lozano | b021b2a | 2020-07-28 09:31:06 -0400 | [diff] [blame] | 291 | # Validation check. |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 292 | for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 293 | if key not in payload_info: |
| 294 | raise ApexInfoError( |
| 295 | 'Failed to find {} prop in {}'.format(key, payload_path)) |
| 296 | |
| 297 | return payload_info |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 298 | |
| 299 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 300 | def SignApex(avbtool, apex_data, payload_key, container_key, container_pw, |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 301 | apk_keys, codename_to_api_level_map, |
| 302 | no_hashtree, signing_args=None): |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 303 | """Signs the current APEX with the given payload/container keys. |
| 304 | |
| 305 | Args: |
| 306 | apex_data: Raw APEX data. |
| 307 | payload_key: The path to payload signing key (w/ extension). |
| 308 | container_key: The path to container signing key (w/o extension). |
| 309 | container_pw: The matching password of the container_key, or None. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 310 | apk_keys: A dict that holds the signing keys for apk files. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 311 | codename_to_api_level_map: A dict that maps from codename to API level. |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 312 | no_hashtree: Don't include hashtree in the signed APEX. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 313 | signing_args: Additional args to be passed to the payload signer. |
| 314 | |
| 315 | Returns: |
| 316 | The path to the signed APEX file. |
| 317 | """ |
| 318 | apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex') |
| 319 | with open(apex_file, 'wb') as apex_fp: |
| 320 | apex_fp.write(apex_data) |
| 321 | |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 322 | APEX_PUBKEY = 'apex_pubkey' |
| 323 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 324 | # 1. Extract the apex payload image and sign the containing apk files. Repack |
| 325 | # the apex file after signing. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 326 | apk_signer = ApexApkSigner(apex_file, container_pw, |
| 327 | codename_to_api_level_map) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 328 | apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 329 | |
| 330 | # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 331 | # payload_key. |
| 332 | payload_dir = common.MakeTempDir(prefix='apex-payload-') |
| 333 | with zipfile.ZipFile(apex_file) as apex_fd: |
| 334 | payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir) |
Baligh Uddin | 1588128 | 2019-08-25 12:01:44 -0700 | [diff] [blame] | 335 | zip_items = apex_fd.namelist() |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 336 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 337 | payload_info = ParseApexPayloadInfo(avbtool, payload_file) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 338 | SignApexPayload( |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 339 | avbtool, |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 340 | payload_file, |
| 341 | payload_key, |
| 342 | payload_info['apex.key'], |
| 343 | payload_info['Algorithm'], |
| 344 | payload_info['Salt'], |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 345 | payload_info['Hash Algorithm'], |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 346 | no_hashtree, |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 347 | signing_args) |
| 348 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 349 | # 2b. Update the embedded payload public key. |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 350 | payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 351 | common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE) |
Baligh Uddin | 1588128 | 2019-08-25 12:01:44 -0700 | [diff] [blame] | 352 | if APEX_PUBKEY in zip_items: |
| 353 | common.ZipDelete(apex_file, APEX_PUBKEY) |
Kelvin Zhang | 928c234 | 2020-09-22 16:15:57 -0400 | [diff] [blame^] | 354 | apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 355 | common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE) |
| 356 | common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY) |
| 357 | common.ZipClose(apex_zip) |
| 358 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 359 | # 3. Align the files at page boundary (same as in apexer). |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 360 | aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex') |
| 361 | common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex]) |
| 362 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 363 | # 4. Sign the APEX container with container_key. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 364 | signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex') |
| 365 | |
| 366 | # Specify the 4K alignment when calling SignApk. |
| 367 | extra_signapk_args = OPTIONS.extra_signapk_args[:] |
| 368 | extra_signapk_args.extend(['-a', '4096']) |
| 369 | |
| 370 | common.SignFile( |
| 371 | aligned_apex, |
| 372 | signed_apex, |
| 373 | container_key, |
| 374 | container_pw, |
| 375 | codename_to_api_level_map=codename_to_api_level_map, |
| 376 | extra_signapk_args=extra_signapk_args) |
| 377 | |
| 378 | return signed_apex |