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 | |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 24 | import apex_manifest |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 25 | import common |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 26 | from common import UnzipTemp, RunAndCheckOutput, MakeTempFile, OPTIONS |
| 27 | |
| 28 | import ota_metadata_pb2 |
| 29 | |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 30 | |
| 31 | logger = logging.getLogger(__name__) |
| 32 | |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 33 | OPTIONS = common.OPTIONS |
| 34 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 35 | APEX_PAYLOAD_IMAGE = 'apex_payload.img' |
| 36 | |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 37 | APEX_PUBKEY = 'apex_pubkey' |
| 38 | |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 39 | |
| 40 | class ApexInfoError(Exception): |
| 41 | """An Exception raised during Apex Information command.""" |
| 42 | |
| 43 | def __init__(self, message): |
| 44 | Exception.__init__(self, message) |
| 45 | |
| 46 | |
| 47 | class ApexSigningError(Exception): |
| 48 | """An Exception raised during Apex Payload signing.""" |
| 49 | |
| 50 | def __init__(self, message): |
| 51 | Exception.__init__(self, message) |
| 52 | |
| 53 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 54 | class ApexApkSigner(object): |
| 55 | """Class to sign the apk files in a apex payload image and repack the apex""" |
| 56 | |
| 57 | def __init__(self, apex_path, key_passwords, codename_to_api_level_map): |
| 58 | self.apex_path = apex_path |
Oleh Cherpak | e555ab1 | 2020-10-05 17:04:59 +0300 | [diff] [blame] | 59 | if not key_passwords: |
| 60 | self.key_passwords = dict() |
| 61 | else: |
| 62 | self.key_passwords = key_passwords |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 63 | self.codename_to_api_level_map = codename_to_api_level_map |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 64 | self.debugfs_path = os.path.join( |
| 65 | OPTIONS.search_path, "bin", "debugfs_static") |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 66 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 67 | def ProcessApexFile(self, apk_keys, payload_key, signing_args=None): |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 68 | """Scans and signs the apk files and repack the apex |
| 69 | |
| 70 | Args: |
| 71 | apk_keys: A dict that holds the signing keys for apk files. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 72 | |
| 73 | Returns: |
| 74 | The repacked apex file containing the signed apk files. |
| 75 | """ |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 76 | if not os.path.exists(self.debugfs_path): |
Kelvin Zhang | d6b799a | 2020-08-19 14:54:42 -0400 | [diff] [blame] | 77 | raise ApexSigningError( |
| 78 | "Couldn't find location of debugfs_static: " + |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 79 | "Path {} does not exist. ".format(self.debugfs_path) + |
Kelvin Zhang | d6b799a | 2020-08-19 14:54:42 -0400 | [diff] [blame] | 80 | "Make sure bin/debugfs_static can be found in -p <path>") |
| 81 | list_cmd = ['deapexer', '--debugfs_path', |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 82 | self.debugfs_path, 'list', self.apex_path] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 83 | entries_names = common.RunAndCheckOutput(list_cmd).split() |
| 84 | apk_entries = [name for name in entries_names if name.endswith('.apk')] |
| 85 | |
| 86 | # No need to sign and repack, return the original apex path. |
| 87 | if not apk_entries: |
| 88 | logger.info('No apk file to sign in %s', self.apex_path) |
| 89 | return self.apex_path |
| 90 | |
| 91 | for entry in apk_entries: |
| 92 | apk_name = os.path.basename(entry) |
| 93 | if apk_name not in apk_keys: |
| 94 | raise ApexSigningError('Failed to find signing keys for apk file {} in' |
| 95 | ' apex {}. Use "-e <apkname>=" to specify a key' |
| 96 | .format(entry, self.apex_path)) |
| 97 | if not any(dirname in entry for dirname in ['app/', 'priv-app/', |
| 98 | 'overlay/']): |
| 99 | logger.warning('Apk path does not contain the intended directory name:' |
| 100 | ' %s', entry) |
| 101 | |
| 102 | payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks( |
| 103 | apk_entries, apk_keys) |
| 104 | if not has_signed_apk: |
| 105 | logger.info('No apk file has been signed in %s', self.apex_path) |
| 106 | return self.apex_path |
| 107 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 108 | return self.RepackApexPayload(payload_dir, payload_key, signing_args) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 109 | |
| 110 | def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys): |
| 111 | """Extracts the payload image and signs the containing apk files.""" |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 112 | if not os.path.exists(self.debugfs_path): |
| 113 | raise ApexSigningError( |
| 114 | "Couldn't find location of debugfs_static: " + |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 115 | "Path {} does not exist. ".format(self.debugfs_path) + |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 116 | "Make sure bin/debugfs_static can be found in -p <path>") |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 117 | payload_dir = common.MakeTempDir() |
Kelvin Zhang | dd833dc | 2020-08-21 14:13:13 -0400 | [diff] [blame] | 118 | extract_cmd = ['deapexer', '--debugfs_path', |
| 119 | self.debugfs_path, 'extract', self.apex_path, payload_dir] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 120 | common.RunAndCheckOutput(extract_cmd) |
| 121 | |
| 122 | has_signed_apk = False |
| 123 | for entry in apk_entries: |
| 124 | apk_path = os.path.join(payload_dir, entry) |
| 125 | assert os.path.exists(self.apex_path) |
| 126 | |
| 127 | key_name = apk_keys.get(os.path.basename(entry)) |
| 128 | if key_name in common.SPECIAL_CERT_STRINGS: |
| 129 | logger.info('Not signing: %s due to special cert string', apk_path) |
| 130 | continue |
| 131 | |
| 132 | logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path) |
| 133 | # Rename the unsigned apk and overwrite the original apk path with the |
| 134 | # signed apk file. |
| 135 | unsigned_apk = common.MakeTempFile() |
| 136 | os.rename(apk_path, unsigned_apk) |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 137 | common.SignFile( |
| 138 | unsigned_apk, apk_path, key_name, self.key_passwords.get(key_name), |
| 139 | codename_to_api_level_map=self.codename_to_api_level_map) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 140 | has_signed_apk = True |
| 141 | return payload_dir, has_signed_apk |
| 142 | |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 143 | def RepackApexPayload(self, payload_dir, payload_key, signing_args=None): |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 144 | """Rebuilds the apex file with the updated payload directory.""" |
| 145 | apex_dir = common.MakeTempDir() |
| 146 | # Extract the apex file and reuse its meta files as repack parameters. |
| 147 | common.UnzipToDir(self.apex_path, apex_dir) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 148 | arguments_dict = { |
| 149 | 'manifest': os.path.join(apex_dir, 'apex_manifest.pb'), |
| 150 | 'build_info': os.path.join(apex_dir, 'apex_build_info.pb'), |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 151 | 'key': payload_key, |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 152 | } |
| 153 | for filename in arguments_dict.values(): |
| 154 | assert os.path.exists(filename), 'file {} not found'.format(filename) |
| 155 | |
| 156 | # The repack process will add back these files later in the payload image. |
| 157 | for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']: |
| 158 | path = os.path.join(payload_dir, name) |
| 159 | if os.path.isfile(path): |
| 160 | os.remove(path) |
| 161 | elif os.path.isdir(path): |
| 162 | shutil.rmtree(path) |
| 163 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 164 | # TODO(xunchang) the signing process can be improved by using |
| 165 | # '--unsigned_payload_only'. But we need to parse the vbmeta earlier for |
| 166 | # the signing arguments, e.g. algorithm, salt, etc. |
| 167 | payload_img = os.path.join(apex_dir, APEX_PAYLOAD_IMAGE) |
| 168 | generate_image_cmd = ['apexer', '--force', '--payload_only', |
| 169 | '--do_not_check_keyname', '--apexer_tool_path', |
| 170 | os.getenv('PATH')] |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 171 | for key, val in arguments_dict.items(): |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 172 | generate_image_cmd.extend(['--' + key, val]) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 173 | |
| 174 | # Add quote to the signing_args as we will pass |
| 175 | # --signing_args "--signing_helper_with_files=%path" to apexer |
| 176 | if signing_args: |
Kelvin Zhang | d6b799a | 2020-08-19 14:54:42 -0400 | [diff] [blame] | 177 | generate_image_cmd.extend( |
| 178 | ['--signing_args', '"{}"'.format(signing_args)]) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 179 | |
Tianjie Xu | 83bd55c | 2020-01-29 11:37:43 -0800 | [diff] [blame] | 180 | # optional arguments for apex repacking |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 181 | manifest_json = os.path.join(apex_dir, 'apex_manifest.json') |
| 182 | if os.path.exists(manifest_json): |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 183 | generate_image_cmd.extend(['--manifest_json', manifest_json]) |
| 184 | generate_image_cmd.extend([payload_dir, payload_img]) |
Tianjie Xu | cea6ad1 | 2020-01-30 17:12:05 -0800 | [diff] [blame] | 185 | if OPTIONS.verbose: |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 186 | generate_image_cmd.append('-v') |
| 187 | common.RunAndCheckOutput(generate_image_cmd) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 188 | |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 189 | # Add the payload image back to the apex file. |
| 190 | common.ZipDelete(self.apex_path, APEX_PAYLOAD_IMAGE) |
Kelvin Zhang | 928c234 | 2020-09-22 16:15:57 -0400 | [diff] [blame] | 191 | with zipfile.ZipFile(self.apex_path, 'a', allowZip64=True) as output_apex: |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 192 | common.ZipWrite(output_apex, payload_img, APEX_PAYLOAD_IMAGE, |
| 193 | compress_type=zipfile.ZIP_STORED) |
| 194 | return self.apex_path |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 195 | |
| 196 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 197 | def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name, |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 198 | algorithm, salt, hash_algorithm, no_hashtree, signing_args=None): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 199 | """Signs a given payload_file with the payload key.""" |
| 200 | # 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] | 201 | cmd = [avbtool, 'add_hashtree_footer', |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 202 | '--do_not_generate_fec', |
| 203 | '--algorithm', algorithm, |
| 204 | '--key', payload_key_path, |
| 205 | '--prop', 'apex.key:{}'.format(payload_key_name), |
| 206 | '--image', payload_file, |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 207 | '--salt', salt, |
| 208 | '--hash_algorithm', hash_algorithm] |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 209 | if no_hashtree: |
| 210 | cmd.append('--no_hashtree') |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 211 | if signing_args: |
| 212 | cmd.extend(shlex.split(signing_args)) |
| 213 | |
| 214 | try: |
| 215 | common.RunAndCheckOutput(cmd) |
| 216 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 217 | raise ApexSigningError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 218 | 'Failed to sign APEX payload {} with {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 219 | payload_file, payload_key_path, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 220 | |
| 221 | # Verify the signed payload image with specified public key. |
| 222 | logger.info('Verifying %s', payload_file) |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 223 | VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 224 | |
| 225 | |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 226 | def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 227 | """Verifies the APEX payload signature with the given key.""" |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 228 | cmd = [avbtool, 'verify_image', '--image', payload_file, |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 229 | '--key', payload_key] |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 230 | if no_hashtree: |
| 231 | cmd.append('--accept_zeroed_hashtree') |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 232 | try: |
| 233 | common.RunAndCheckOutput(cmd) |
| 234 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 235 | raise ApexSigningError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 236 | 'Failed to validate payload signing for {} with {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 237 | payload_file, payload_key, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 238 | |
| 239 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 240 | def ParseApexPayloadInfo(avbtool, payload_path): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 241 | """Parses the APEX payload info. |
| 242 | |
| 243 | Args: |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 244 | avbtool: The AVB tool to use. |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 245 | payload_path: The path to the payload image. |
| 246 | |
| 247 | Raises: |
| 248 | ApexInfoError on parsing errors. |
| 249 | |
| 250 | Returns: |
| 251 | 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] | 252 | contain Algorithm, Salt, Tree Size and apex.key. |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 253 | """ |
| 254 | if not os.path.exists(payload_path): |
| 255 | raise ApexInfoError('Failed to find image: {}'.format(payload_path)) |
| 256 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 257 | cmd = [avbtool, 'info_image', '--image', payload_path] |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 258 | try: |
| 259 | output = common.RunAndCheckOutput(cmd) |
| 260 | except common.ExternalError as e: |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 261 | raise ApexInfoError( |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 262 | 'Failed to get APEX payload info for {}:\n{}'.format( |
Tao Bao | 86b529a | 2019-06-19 17:03:37 -0700 | [diff] [blame] | 263 | payload_path, e)) |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 264 | |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 265 | # Extract the Algorithm / Hash Algorithm / Salt / Prop info / Tree size from |
| 266 | # payload (i.e. an image signed with avbtool). For example, |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 267 | # Algorithm: SHA256_RSA4096 |
| 268 | PAYLOAD_INFO_PATTERN = ( |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 269 | 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] | 270 | payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN) |
| 271 | |
| 272 | payload_info = {} |
| 273 | for line in output.split('\n'): |
| 274 | line_info = payload_info_matcher.match(line) |
| 275 | if not line_info: |
| 276 | continue |
| 277 | |
| 278 | key, value = line_info.group('key'), line_info.group('value') |
| 279 | |
| 280 | if key == 'Prop': |
| 281 | # Further extract the property key-value pair, from a 'Prop:' line. For |
| 282 | # example, |
| 283 | # Prop: apex.key -> 'com.android.runtime' |
| 284 | # Note that avbtool writes single or double quotes around values. |
| 285 | PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$' |
| 286 | |
| 287 | prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN) |
| 288 | prop = prop_matcher.match(value) |
| 289 | if not prop: |
| 290 | raise ApexInfoError( |
| 291 | 'Failed to parse prop string {}'.format(value)) |
| 292 | |
| 293 | prop_key, prop_value = prop.group('key'), prop.group('value') |
| 294 | if prop_key == 'apex.key': |
| 295 | # avbtool dumps the prop value with repr(), which contains single / |
| 296 | # double quotes that we don't want. |
| 297 | payload_info[prop_key] = prop_value.strip('\"\'') |
| 298 | |
| 299 | else: |
| 300 | payload_info[key] = value |
| 301 | |
Ivan Lozano | b021b2a | 2020-07-28 09:31:06 -0400 | [diff] [blame] | 302 | # Validation check. |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 303 | for key in ('Algorithm', 'Salt', 'apex.key', 'Hash Algorithm'): |
Tao Bao | 1cd59f2 | 2019-03-15 15:13:01 -0700 | [diff] [blame] | 304 | if key not in payload_info: |
| 305 | raise ApexInfoError( |
| 306 | 'Failed to find {} prop in {}'.format(key, payload_path)) |
| 307 | |
| 308 | return payload_info |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 309 | |
| 310 | |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 311 | def SignUncompressedApex(avbtool, apex_file, payload_key, container_key, |
Nikita Ioffe | 6068e8d | 2021-01-12 00:03:02 +0000 | [diff] [blame] | 312 | container_pw, apk_keys, codename_to_api_level_map, |
| 313 | no_hashtree, signing_args=None): |
| 314 | """Signs the current uncompressed APEX with the given payload/container keys. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 315 | |
| 316 | Args: |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 317 | apex_file: Uncompressed APEX file. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 318 | payload_key: The path to payload signing key (w/ extension). |
| 319 | container_key: The path to container signing key (w/o extension). |
| 320 | container_pw: The matching password of the container_key, or None. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 321 | apk_keys: A dict that holds the signing keys for apk files. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 322 | 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] | 323 | no_hashtree: Don't include hashtree in the signed APEX. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 324 | signing_args: Additional args to be passed to the payload signer. |
| 325 | |
| 326 | Returns: |
| 327 | The path to the signed APEX file. |
| 328 | """ |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 329 | # 1. Extract the apex payload image and sign the containing apk files. Repack |
| 330 | # the apex file after signing. |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 331 | apk_signer = ApexApkSigner(apex_file, container_pw, |
| 332 | codename_to_api_level_map) |
Baligh Uddin | 639b3b7 | 2020-03-25 20:50:23 -0700 | [diff] [blame] | 333 | apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key, signing_args) |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 334 | |
| 335 | # 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 336 | # payload_key. |
| 337 | payload_dir = common.MakeTempDir(prefix='apex-payload-') |
| 338 | with zipfile.ZipFile(apex_file) as apex_fd: |
| 339 | payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir) |
Baligh Uddin | 1588128 | 2019-08-25 12:01:44 -0700 | [diff] [blame] | 340 | zip_items = apex_fd.namelist() |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 341 | |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 342 | payload_info = ParseApexPayloadInfo(avbtool, payload_file) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 343 | SignApexPayload( |
Tao Bao | 1ac886e | 2019-06-26 11:58:22 -0700 | [diff] [blame] | 344 | avbtool, |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 345 | payload_file, |
| 346 | payload_key, |
| 347 | payload_info['apex.key'], |
| 348 | payload_info['Algorithm'], |
| 349 | payload_info['Salt'], |
Jiyong Park | a1887f3 | 2020-05-19 23:18:03 +0900 | [diff] [blame] | 350 | payload_info['Hash Algorithm'], |
Tao Bao | 448004a | 2019-09-19 07:55:02 -0700 | [diff] [blame] | 351 | no_hashtree, |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 352 | signing_args) |
| 353 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 354 | # 2b. Update the embedded payload public key. |
Tianjie | c180a5d | 2020-03-23 18:14:09 -0700 | [diff] [blame] | 355 | payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 356 | common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE) |
Baligh Uddin | 1588128 | 2019-08-25 12:01:44 -0700 | [diff] [blame] | 357 | if APEX_PUBKEY in zip_items: |
| 358 | common.ZipDelete(apex_file, APEX_PUBKEY) |
Kelvin Zhang | 928c234 | 2020-09-22 16:15:57 -0400 | [diff] [blame] | 359 | apex_zip = zipfile.ZipFile(apex_file, 'a', allowZip64=True) |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 360 | common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE) |
| 361 | common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY) |
| 362 | common.ZipClose(apex_zip) |
| 363 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 364 | # 3. Align the files at page boundary (same as in apexer). |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 365 | aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex') |
| 366 | common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex]) |
| 367 | |
Tianjie Xu | 88a759d | 2020-01-23 10:47:54 -0800 | [diff] [blame] | 368 | # 4. Sign the APEX container with container_key. |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 369 | signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex') |
| 370 | |
| 371 | # Specify the 4K alignment when calling SignApk. |
| 372 | extra_signapk_args = OPTIONS.extra_signapk_args[:] |
| 373 | extra_signapk_args.extend(['-a', '4096']) |
| 374 | |
Nikita Ioffe | c3fdfed | 2021-01-11 23:50:31 +0000 | [diff] [blame] | 375 | password = container_pw.get(container_key) if container_pw else None |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 376 | common.SignFile( |
| 377 | aligned_apex, |
| 378 | signed_apex, |
| 379 | container_key, |
Nikita Ioffe | c3fdfed | 2021-01-11 23:50:31 +0000 | [diff] [blame] | 380 | password, |
Tao Bao | e7354ba | 2019-05-09 16:54:15 -0700 | [diff] [blame] | 381 | codename_to_api_level_map=codename_to_api_level_map, |
| 382 | extra_signapk_args=extra_signapk_args) |
| 383 | |
| 384 | return signed_apex |
Nikita Ioffe | 6068e8d | 2021-01-12 00:03:02 +0000 | [diff] [blame] | 385 | |
| 386 | |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 387 | def SignCompressedApex(avbtool, apex_file, payload_key, container_key, |
| 388 | container_pw, apk_keys, codename_to_api_level_map, |
| 389 | no_hashtree, signing_args=None): |
| 390 | """Signs the current compressed APEX with the given payload/container keys. |
| 391 | |
| 392 | Args: |
| 393 | apex_file: Raw uncompressed APEX data. |
| 394 | payload_key: The path to payload signing key (w/ extension). |
| 395 | container_key: The path to container signing key (w/o extension). |
| 396 | container_pw: The matching password of the container_key, or None. |
| 397 | apk_keys: A dict that holds the signing keys for apk files. |
| 398 | codename_to_api_level_map: A dict that maps from codename to API level. |
| 399 | no_hashtree: Don't include hashtree in the signed APEX. |
| 400 | signing_args: Additional args to be passed to the payload signer. |
| 401 | |
| 402 | Returns: |
| 403 | The path to the signed APEX file. |
| 404 | """ |
| 405 | debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static') |
| 406 | |
| 407 | # 1. Decompress original_apex inside compressed apex. |
| 408 | original_apex_file = common.MakeTempFile(prefix='original-apex-', |
| 409 | suffix='.apex') |
| 410 | # Decompression target path should not exist |
| 411 | os.remove(original_apex_file) |
| 412 | common.RunAndCheckOutput(['deapexer', '--debugfs_path', debugfs_path, |
| 413 | 'decompress', '--input', apex_file, |
| 414 | '--output', original_apex_file]) |
| 415 | |
| 416 | # 2. Sign original_apex |
| 417 | signed_original_apex_file = SignUncompressedApex( |
| 418 | avbtool, |
| 419 | original_apex_file, |
| 420 | payload_key, |
| 421 | container_key, |
| 422 | container_pw, |
| 423 | apk_keys, |
| 424 | codename_to_api_level_map, |
| 425 | no_hashtree, |
| 426 | signing_args) |
| 427 | |
| 428 | # 3. Compress signed original apex. |
| 429 | compressed_apex_file = common.MakeTempFile(prefix='apex-container-', |
| 430 | suffix='.capex') |
| 431 | common.RunAndCheckOutput(['apex_compression_tool', |
| 432 | 'compress', |
| 433 | '--apex_compression_tool_path', os.getenv('PATH'), |
| 434 | '--input', signed_original_apex_file, |
| 435 | '--output', compressed_apex_file]) |
| 436 | |
| 437 | # 4. Align apex |
| 438 | aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex') |
| 439 | common.RunAndCheckOutput(['zipalign', '-f', '4096', compressed_apex_file, |
| 440 | aligned_apex]) |
| 441 | |
| 442 | # 5. Sign the APEX container with container_key. |
| 443 | signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.capex') |
| 444 | |
| 445 | # Specify the 4K alignment when calling SignApk. |
| 446 | extra_signapk_args = OPTIONS.extra_signapk_args[:] |
| 447 | extra_signapk_args.extend(['-a', '4096']) |
| 448 | |
| 449 | password = container_pw.get(container_key) if container_pw else None |
| 450 | common.SignFile( |
| 451 | aligned_apex, |
| 452 | signed_apex, |
| 453 | container_key, |
| 454 | password, |
| 455 | codename_to_api_level_map=codename_to_api_level_map, |
| 456 | extra_signapk_args=extra_signapk_args) |
| 457 | |
| 458 | return signed_apex |
| 459 | |
| 460 | |
Nikita Ioffe | 6068e8d | 2021-01-12 00:03:02 +0000 | [diff] [blame] | 461 | def SignApex(avbtool, apex_data, payload_key, container_key, container_pw, |
| 462 | apk_keys, codename_to_api_level_map, |
| 463 | no_hashtree, signing_args=None): |
| 464 | """Signs the current APEX with the given payload/container keys. |
| 465 | |
| 466 | Args: |
| 467 | apex_file: Path to apex file path. |
| 468 | payload_key: The path to payload signing key (w/ extension). |
| 469 | container_key: The path to container signing key (w/o extension). |
| 470 | container_pw: The matching password of the container_key, or None. |
| 471 | apk_keys: A dict that holds the signing keys for apk files. |
| 472 | codename_to_api_level_map: A dict that maps from codename to API level. |
| 473 | no_hashtree: Don't include hashtree in the signed APEX. |
| 474 | signing_args: Additional args to be passed to the payload signer. |
| 475 | |
| 476 | Returns: |
| 477 | The path to the signed APEX file. |
| 478 | """ |
| 479 | apex_file = common.MakeTempFile(prefix='apex-container-', suffix='.apex') |
| 480 | with open(apex_file, 'wb') as output_fp: |
| 481 | output_fp.write(apex_data) |
| 482 | |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 483 | debugfs_path = os.path.join(OPTIONS.search_path, 'bin', 'debugfs_static') |
Nikita Ioffe | 6068e8d | 2021-01-12 00:03:02 +0000 | [diff] [blame] | 484 | cmd = ['deapexer', '--debugfs_path', debugfs_path, |
| 485 | 'info', '--print-type', apex_file] |
| 486 | |
| 487 | try: |
| 488 | apex_type = common.RunAndCheckOutput(cmd).strip() |
| 489 | if apex_type == 'UNCOMPRESSED': |
| 490 | return SignUncompressedApex( |
| 491 | avbtool, |
Nikita Ioffe | 3608148 | 2021-01-20 01:32:28 +0000 | [diff] [blame] | 492 | apex_file, |
| 493 | payload_key=payload_key, |
| 494 | container_key=container_key, |
| 495 | container_pw=None, |
| 496 | codename_to_api_level_map=codename_to_api_level_map, |
| 497 | no_hashtree=no_hashtree, |
| 498 | apk_keys=apk_keys, |
| 499 | signing_args=signing_args) |
| 500 | elif apex_type == 'COMPRESSED': |
| 501 | return SignCompressedApex( |
| 502 | avbtool, |
| 503 | apex_file, |
Nikita Ioffe | 6068e8d | 2021-01-12 00:03:02 +0000 | [diff] [blame] | 504 | payload_key=payload_key, |
| 505 | container_key=container_key, |
| 506 | container_pw=None, |
| 507 | codename_to_api_level_map=codename_to_api_level_map, |
| 508 | no_hashtree=no_hashtree, |
| 509 | apk_keys=apk_keys, |
| 510 | signing_args=signing_args) |
| 511 | else: |
| 512 | # TODO(b/172912232): support signing compressed apex |
| 513 | raise ApexInfoError('Unsupported apex type {}'.format(apex_type)) |
| 514 | |
| 515 | except common.ExternalError as e: |
| 516 | raise ApexInfoError( |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 517 | 'Failed to get type for {}:\n{}'.format(apex_file, e)) |
| 518 | |
Daniel Norman | e9af70a | 2021-04-15 16:39:22 -0700 | [diff] [blame^] | 519 | def GetApexInfoFromTargetFiles(input_file, partition, compressed_only=True): |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 520 | """ |
| 521 | Get information about system APEX stored in the input_file zip |
| 522 | |
| 523 | Args: |
| 524 | input_file: The filename of the target build target-files zip or directory. |
| 525 | |
| 526 | Return: |
| 527 | A list of ota_metadata_pb2.ApexInfo() populated using the APEX stored in |
| 528 | /system partition of the input_file |
| 529 | """ |
| 530 | |
| 531 | # Extract the apex files so that we can run checks on them |
| 532 | if not isinstance(input_file, str): |
| 533 | raise RuntimeError("must pass filepath to target-files zip or directory") |
| 534 | |
Daniel Norman | e9af70a | 2021-04-15 16:39:22 -0700 | [diff] [blame^] | 535 | apex_subdir = os.path.join(partition.upper(), 'apex') |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 536 | if os.path.isdir(input_file): |
| 537 | tmp_dir = input_file |
| 538 | else: |
Daniel Norman | e9af70a | 2021-04-15 16:39:22 -0700 | [diff] [blame^] | 539 | tmp_dir = UnzipTemp(input_file, [os.path.join(apex_subdir, '*')]) |
| 540 | target_dir = os.path.join(tmp_dir, apex_subdir) |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 541 | |
Daniel Norman | b4b07ab | 2021-02-17 13:22:21 -0800 | [diff] [blame] | 542 | # Partial target-files packages for vendor-only builds may not contain |
| 543 | # a system apex directory. |
| 544 | if not os.path.exists(target_dir): |
Daniel Norman | e9af70a | 2021-04-15 16:39:22 -0700 | [diff] [blame^] | 545 | logger.info('No APEX directory at path: %s', target_dir) |
Daniel Norman | b4b07ab | 2021-02-17 13:22:21 -0800 | [diff] [blame] | 546 | return [] |
| 547 | |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 548 | apex_infos = [] |
Kelvin Zhang | c72718c | 2021-01-27 14:17:14 -0500 | [diff] [blame] | 549 | |
| 550 | debugfs_path = "debugfs" |
| 551 | if OPTIONS.search_path: |
| 552 | debugfs_path = os.path.join(OPTIONS.search_path, "bin", "debugfs_static") |
| 553 | deapexer = 'deapexer' |
| 554 | if OPTIONS.search_path: |
Kelvin Zhang | 05a3f68 | 2021-01-29 14:38:24 -0500 | [diff] [blame] | 555 | deapexer_path = os.path.join(OPTIONS.search_path, "bin", "deapexer") |
Kelvin Zhang | c72718c | 2021-01-27 14:17:14 -0500 | [diff] [blame] | 556 | if os.path.isfile(deapexer_path): |
| 557 | deapexer = deapexer_path |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 558 | for apex_filename in os.listdir(target_dir): |
| 559 | apex_filepath = os.path.join(target_dir, apex_filename) |
| 560 | if not os.path.isfile(apex_filepath) or \ |
| 561 | not zipfile.is_zipfile(apex_filepath): |
| 562 | logger.info("Skipping %s because it's not a zipfile", apex_filepath) |
| 563 | continue |
| 564 | apex_info = ota_metadata_pb2.ApexInfo() |
| 565 | # Open the apex file to retrieve information |
| 566 | manifest = apex_manifest.fromApex(apex_filepath) |
| 567 | apex_info.package_name = manifest.name |
| 568 | apex_info.version = manifest.version |
| 569 | # Check if the file is compressed or not |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 570 | apex_type = RunAndCheckOutput([ |
| 571 | deapexer, "--debugfs_path", debugfs_path, |
| 572 | 'info', '--print-type', apex_filepath]).rstrip() |
| 573 | if apex_type == 'COMPRESSED': |
| 574 | apex_info.is_compressed = True |
| 575 | elif apex_type == 'UNCOMPRESSED': |
| 576 | apex_info.is_compressed = False |
| 577 | else: |
| 578 | raise RuntimeError('Not an APEX file: ' + apex_type) |
| 579 | |
| 580 | # Decompress compressed APEX to determine its size |
| 581 | if apex_info.is_compressed: |
| 582 | decompressed_file_path = MakeTempFile(prefix="decompressed-", |
| 583 | suffix=".apex") |
| 584 | # Decompression target path should not exist |
| 585 | os.remove(decompressed_file_path) |
| 586 | RunAndCheckOutput([deapexer, 'decompress', '--input', apex_filepath, |
| 587 | '--output', decompressed_file_path]) |
| 588 | apex_info.decompressed_size = os.path.getsize(decompressed_file_path) |
| 589 | |
Daniel Norman | e9af70a | 2021-04-15 16:39:22 -0700 | [diff] [blame^] | 590 | if not compressed_only or apex_info.is_compressed: |
Kelvin Zhang | c72718c | 2021-01-27 14:17:14 -0500 | [diff] [blame] | 591 | apex_infos.append(apex_info) |
Mohammad Samiul Islam | 9fd5886 | 2021-01-06 13:33:25 +0000 | [diff] [blame] | 592 | |
| 593 | return apex_infos |