2019-03-15 23:13:01 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Copyright (C) 2019 The Android Open Source Project
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import os.path
|
|
|
|
import re
|
|
|
|
import shlex
|
2020-01-23 19:47:54 +01:00
|
|
|
import shutil
|
2019-05-10 01:54:15 +02:00
|
|
|
import zipfile
|
2019-03-15 23:13:01 +01:00
|
|
|
|
|
|
|
import common
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2019-05-10 01:54:15 +02:00
|
|
|
OPTIONS = common.OPTIONS
|
|
|
|
|
2019-03-15 23:13:01 +01:00
|
|
|
|
|
|
|
class ApexInfoError(Exception):
|
|
|
|
"""An Exception raised during Apex Information command."""
|
|
|
|
|
|
|
|
def __init__(self, message):
|
|
|
|
Exception.__init__(self, message)
|
|
|
|
|
|
|
|
|
|
|
|
class ApexSigningError(Exception):
|
|
|
|
"""An Exception raised during Apex Payload signing."""
|
|
|
|
|
|
|
|
def __init__(self, message):
|
|
|
|
Exception.__init__(self, message)
|
|
|
|
|
|
|
|
|
2020-01-23 19:47:54 +01:00
|
|
|
class ApexApkSigner(object):
|
|
|
|
"""Class to sign the apk files in a apex payload image and repack the apex"""
|
|
|
|
|
|
|
|
def __init__(self, apex_path, key_passwords, codename_to_api_level_map):
|
|
|
|
self.apex_path = apex_path
|
|
|
|
self.key_passwords = key_passwords
|
|
|
|
self.codename_to_api_level_map = codename_to_api_level_map
|
|
|
|
|
2020-01-31 02:12:05 +01:00
|
|
|
def ProcessApexFile(self, apk_keys, payload_key, payload_public_key,
|
|
|
|
signing_args=None):
|
2020-01-23 19:47:54 +01:00
|
|
|
"""Scans and signs the apk files and repack the apex
|
|
|
|
|
|
|
|
Args:
|
|
|
|
apk_keys: A dict that holds the signing keys for apk files.
|
|
|
|
payload_key: The path to the apex payload signing key.
|
|
|
|
payload_public_key: The path to the public key corresponding to the
|
|
|
|
payload signing key.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The repacked apex file containing the signed apk files.
|
|
|
|
"""
|
|
|
|
list_cmd = ['deapexer', 'list', self.apex_path]
|
|
|
|
entries_names = common.RunAndCheckOutput(list_cmd).split()
|
|
|
|
apk_entries = [name for name in entries_names if name.endswith('.apk')]
|
|
|
|
|
|
|
|
# No need to sign and repack, return the original apex path.
|
|
|
|
if not apk_entries:
|
|
|
|
logger.info('No apk file to sign in %s', self.apex_path)
|
|
|
|
return self.apex_path
|
|
|
|
|
|
|
|
for entry in apk_entries:
|
|
|
|
apk_name = os.path.basename(entry)
|
|
|
|
if apk_name not in apk_keys:
|
|
|
|
raise ApexSigningError('Failed to find signing keys for apk file {} in'
|
|
|
|
' apex {}. Use "-e <apkname>=" to specify a key'
|
|
|
|
.format(entry, self.apex_path))
|
|
|
|
if not any(dirname in entry for dirname in ['app/', 'priv-app/',
|
|
|
|
'overlay/']):
|
|
|
|
logger.warning('Apk path does not contain the intended directory name:'
|
|
|
|
' %s', entry)
|
|
|
|
|
|
|
|
payload_dir, has_signed_apk = self.ExtractApexPayloadAndSignApks(
|
|
|
|
apk_entries, apk_keys)
|
|
|
|
if not has_signed_apk:
|
|
|
|
logger.info('No apk file has been signed in %s', self.apex_path)
|
|
|
|
return self.apex_path
|
|
|
|
|
2020-01-31 02:12:05 +01:00
|
|
|
return self.RepackApexPayload(payload_dir, payload_key, payload_public_key,
|
|
|
|
signing_args)
|
2020-01-23 19:47:54 +01:00
|
|
|
|
|
|
|
def ExtractApexPayloadAndSignApks(self, apk_entries, apk_keys):
|
|
|
|
"""Extracts the payload image and signs the containing apk files."""
|
|
|
|
payload_dir = common.MakeTempDir()
|
|
|
|
extract_cmd = ['deapexer', 'extract', self.apex_path, payload_dir]
|
|
|
|
common.RunAndCheckOutput(extract_cmd)
|
|
|
|
|
|
|
|
has_signed_apk = False
|
|
|
|
for entry in apk_entries:
|
|
|
|
apk_path = os.path.join(payload_dir, entry)
|
|
|
|
assert os.path.exists(self.apex_path)
|
|
|
|
|
|
|
|
key_name = apk_keys.get(os.path.basename(entry))
|
|
|
|
if key_name in common.SPECIAL_CERT_STRINGS:
|
|
|
|
logger.info('Not signing: %s due to special cert string', apk_path)
|
|
|
|
continue
|
|
|
|
|
|
|
|
logger.info('Signing apk file %s in apex %s', apk_path, self.apex_path)
|
|
|
|
# Rename the unsigned apk and overwrite the original apk path with the
|
|
|
|
# signed apk file.
|
|
|
|
unsigned_apk = common.MakeTempFile()
|
|
|
|
os.rename(apk_path, unsigned_apk)
|
|
|
|
common.SignFile(unsigned_apk, apk_path, key_name, self.key_passwords,
|
|
|
|
codename_to_api_level_map=self.codename_to_api_level_map)
|
|
|
|
has_signed_apk = True
|
|
|
|
return payload_dir, has_signed_apk
|
|
|
|
|
2020-01-31 02:12:05 +01:00
|
|
|
def RepackApexPayload(self, payload_dir, payload_key, payload_public_key,
|
|
|
|
signing_args=None):
|
2020-01-23 19:47:54 +01:00
|
|
|
"""Rebuilds the apex file with the updated payload directory."""
|
|
|
|
apex_dir = common.MakeTempDir()
|
|
|
|
# Extract the apex file and reuse its meta files as repack parameters.
|
|
|
|
common.UnzipToDir(self.apex_path, apex_dir)
|
|
|
|
|
|
|
|
android_jar_path = common.OPTIONS.android_jar_path
|
|
|
|
if not android_jar_path:
|
2020-01-28 19:54:50 +01:00
|
|
|
android_jar_path = os.path.join(os.environ.get('ANDROID_BUILD_TOP', ''),
|
|
|
|
'prebuilts', 'sdk', 'current', 'public',
|
|
|
|
'android.jar')
|
2020-01-23 19:47:54 +01:00
|
|
|
logger.warning('android_jar_path not found in options, falling back to'
|
|
|
|
' use %s', android_jar_path)
|
|
|
|
|
|
|
|
arguments_dict = {
|
|
|
|
'manifest': os.path.join(apex_dir, 'apex_manifest.pb'),
|
|
|
|
'build_info': os.path.join(apex_dir, 'apex_build_info.pb'),
|
|
|
|
'android_jar_path': android_jar_path,
|
|
|
|
'key': payload_key,
|
|
|
|
'pubkey': payload_public_key,
|
|
|
|
}
|
|
|
|
for filename in arguments_dict.values():
|
|
|
|
assert os.path.exists(filename), 'file {} not found'.format(filename)
|
|
|
|
|
|
|
|
# The repack process will add back these files later in the payload image.
|
|
|
|
for name in ['apex_manifest.pb', 'apex_manifest.json', 'lost+found']:
|
|
|
|
path = os.path.join(payload_dir, name)
|
|
|
|
if os.path.isfile(path):
|
|
|
|
os.remove(path)
|
|
|
|
elif os.path.isdir(path):
|
|
|
|
shutil.rmtree(path)
|
|
|
|
|
|
|
|
repacked_apex = common.MakeTempFile(suffix='.apex')
|
|
|
|
repack_cmd = ['apexer', '--force', '--include_build_info',
|
|
|
|
'--do_not_check_keyname', '--apexer_tool_path',
|
|
|
|
os.getenv('PATH')]
|
|
|
|
for key, val in arguments_dict.items():
|
2020-01-31 02:12:05 +01:00
|
|
|
repack_cmd.extend(['--' + key, val])
|
2020-01-31 21:11:12 +01:00
|
|
|
# Add quote to the signing_args as we will pass
|
|
|
|
# --signing_args "--signing_helper_with_files=%path" to apexer
|
2020-01-31 02:12:05 +01:00
|
|
|
if signing_args:
|
2020-01-31 21:11:12 +01:00
|
|
|
repack_cmd.extend(['--signing_args', '"{}"'.format(signing_args)])
|
2020-01-29 20:37:43 +01:00
|
|
|
# optional arguments for apex repacking
|
2020-01-23 19:47:54 +01:00
|
|
|
manifest_json = os.path.join(apex_dir, 'apex_manifest.json')
|
|
|
|
if os.path.exists(manifest_json):
|
2020-01-31 02:12:05 +01:00
|
|
|
repack_cmd.extend(['--manifest_json', manifest_json])
|
2020-01-29 20:37:43 +01:00
|
|
|
assets_dir = os.path.join(apex_dir, 'assets')
|
|
|
|
if os.path.isdir(assets_dir):
|
2020-01-31 02:12:05 +01:00
|
|
|
repack_cmd.extend(['--assets_dir', assets_dir])
|
|
|
|
repack_cmd.extend([payload_dir, repacked_apex])
|
|
|
|
if OPTIONS.verbose:
|
|
|
|
repack_cmd.append('-v')
|
2020-01-23 19:47:54 +01:00
|
|
|
common.RunAndCheckOutput(repack_cmd)
|
|
|
|
|
|
|
|
return repacked_apex
|
|
|
|
|
|
|
|
|
2019-06-26 20:58:22 +02:00
|
|
|
def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
|
2019-09-19 16:55:02 +02:00
|
|
|
algorithm, salt, no_hashtree, signing_args=None):
|
2019-03-15 23:13:01 +01:00
|
|
|
"""Signs a given payload_file with the payload key."""
|
|
|
|
# Add the new footer. Old footer, if any, will be replaced by avbtool.
|
2019-06-26 20:58:22 +02:00
|
|
|
cmd = [avbtool, 'add_hashtree_footer',
|
2019-03-15 23:13:01 +01:00
|
|
|
'--do_not_generate_fec',
|
|
|
|
'--algorithm', algorithm,
|
|
|
|
'--key', payload_key_path,
|
|
|
|
'--prop', 'apex.key:{}'.format(payload_key_name),
|
|
|
|
'--image', payload_file,
|
|
|
|
'--salt', salt]
|
2019-09-19 16:55:02 +02:00
|
|
|
if no_hashtree:
|
|
|
|
cmd.append('--no_hashtree')
|
2019-03-15 23:13:01 +01:00
|
|
|
if signing_args:
|
|
|
|
cmd.extend(shlex.split(signing_args))
|
|
|
|
|
|
|
|
try:
|
|
|
|
common.RunAndCheckOutput(cmd)
|
|
|
|
except common.ExternalError as e:
|
2019-06-20 02:03:37 +02:00
|
|
|
raise ApexSigningError(
|
2019-03-15 23:13:01 +01:00
|
|
|
'Failed to sign APEX payload {} with {}:\n{}'.format(
|
2019-06-20 02:03:37 +02:00
|
|
|
payload_file, payload_key_path, e))
|
2019-03-15 23:13:01 +01:00
|
|
|
|
|
|
|
# Verify the signed payload image with specified public key.
|
|
|
|
logger.info('Verifying %s', payload_file)
|
2019-09-19 16:55:02 +02:00
|
|
|
VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
|
2019-03-15 23:13:01 +01:00
|
|
|
|
|
|
|
|
2019-09-19 16:55:02 +02:00
|
|
|
def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
|
2019-03-15 23:13:01 +01:00
|
|
|
"""Verifies the APEX payload signature with the given key."""
|
2019-06-26 20:58:22 +02:00
|
|
|
cmd = [avbtool, 'verify_image', '--image', payload_file,
|
2019-03-15 23:13:01 +01:00
|
|
|
'--key', payload_key]
|
2019-09-19 16:55:02 +02:00
|
|
|
if no_hashtree:
|
|
|
|
cmd.append('--accept_zeroed_hashtree')
|
2019-03-15 23:13:01 +01:00
|
|
|
try:
|
|
|
|
common.RunAndCheckOutput(cmd)
|
|
|
|
except common.ExternalError as e:
|
2019-06-20 02:03:37 +02:00
|
|
|
raise ApexSigningError(
|
2019-03-15 23:13:01 +01:00
|
|
|
'Failed to validate payload signing for {} with {}:\n{}'.format(
|
2019-06-20 02:03:37 +02:00
|
|
|
payload_file, payload_key, e))
|
2019-03-15 23:13:01 +01:00
|
|
|
|
|
|
|
|
2019-06-26 20:58:22 +02:00
|
|
|
def ParseApexPayloadInfo(avbtool, payload_path):
|
2019-03-15 23:13:01 +01:00
|
|
|
"""Parses the APEX payload info.
|
|
|
|
|
|
|
|
Args:
|
2019-06-26 20:58:22 +02:00
|
|
|
avbtool: The AVB tool to use.
|
2019-03-15 23:13:01 +01:00
|
|
|
payload_path: The path to the payload image.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ApexInfoError on parsing errors.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A dict that contains payload property-value pairs. The dict should at least
|
2019-09-19 16:55:02 +02:00
|
|
|
contain Algorithm, Salt, Tree Size and apex.key.
|
2019-03-15 23:13:01 +01:00
|
|
|
"""
|
|
|
|
if not os.path.exists(payload_path):
|
|
|
|
raise ApexInfoError('Failed to find image: {}'.format(payload_path))
|
|
|
|
|
2019-06-26 20:58:22 +02:00
|
|
|
cmd = [avbtool, 'info_image', '--image', payload_path]
|
2019-03-15 23:13:01 +01:00
|
|
|
try:
|
|
|
|
output = common.RunAndCheckOutput(cmd)
|
|
|
|
except common.ExternalError as e:
|
2019-06-20 02:03:37 +02:00
|
|
|
raise ApexInfoError(
|
2019-03-15 23:13:01 +01:00
|
|
|
'Failed to get APEX payload info for {}:\n{}'.format(
|
2019-06-20 02:03:37 +02:00
|
|
|
payload_path, e))
|
2019-03-15 23:13:01 +01:00
|
|
|
|
2019-09-19 16:55:02 +02:00
|
|
|
# Extract the Algorithm / Salt / Prop info / Tree size from payload (i.e. an
|
|
|
|
# image signed with avbtool). For example,
|
2019-03-15 23:13:01 +01:00
|
|
|
# Algorithm: SHA256_RSA4096
|
|
|
|
PAYLOAD_INFO_PATTERN = (
|
2019-09-19 16:55:02 +02:00
|
|
|
r'^\s*(?P<key>Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
|
2019-03-15 23:13:01 +01:00
|
|
|
payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
|
|
|
|
|
|
|
|
payload_info = {}
|
|
|
|
for line in output.split('\n'):
|
|
|
|
line_info = payload_info_matcher.match(line)
|
|
|
|
if not line_info:
|
|
|
|
continue
|
|
|
|
|
|
|
|
key, value = line_info.group('key'), line_info.group('value')
|
|
|
|
|
|
|
|
if key == 'Prop':
|
|
|
|
# Further extract the property key-value pair, from a 'Prop:' line. For
|
|
|
|
# example,
|
|
|
|
# Prop: apex.key -> 'com.android.runtime'
|
|
|
|
# Note that avbtool writes single or double quotes around values.
|
|
|
|
PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
|
|
|
|
|
|
|
|
prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
|
|
|
|
prop = prop_matcher.match(value)
|
|
|
|
if not prop:
|
|
|
|
raise ApexInfoError(
|
|
|
|
'Failed to parse prop string {}'.format(value))
|
|
|
|
|
|
|
|
prop_key, prop_value = prop.group('key'), prop.group('value')
|
|
|
|
if prop_key == 'apex.key':
|
|
|
|
# avbtool dumps the prop value with repr(), which contains single /
|
|
|
|
# double quotes that we don't want.
|
|
|
|
payload_info[prop_key] = prop_value.strip('\"\'')
|
|
|
|
|
|
|
|
else:
|
|
|
|
payload_info[key] = value
|
|
|
|
|
|
|
|
# Sanity check.
|
|
|
|
for key in ('Algorithm', 'Salt', 'apex.key'):
|
|
|
|
if key not in payload_info:
|
|
|
|
raise ApexInfoError(
|
|
|
|
'Failed to find {} prop in {}'.format(key, payload_path))
|
|
|
|
|
|
|
|
return payload_info
|
2019-05-10 01:54:15 +02:00
|
|
|
|
|
|
|
|
2019-06-26 20:58:22 +02:00
|
|
|
def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
|
2020-01-23 19:47:54 +01:00
|
|
|
apk_keys, codename_to_api_level_map,
|
|
|
|
no_hashtree, signing_args=None):
|
2019-05-10 01:54:15 +02:00
|
|
|
"""Signs the current APEX with the given payload/container keys.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
apex_data: Raw APEX data.
|
|
|
|
payload_key: The path to payload signing key (w/ extension).
|
|
|
|
container_key: The path to container signing key (w/o extension).
|
|
|
|
container_pw: The matching password of the container_key, or None.
|
2020-01-23 19:47:54 +01:00
|
|
|
apk_keys: A dict that holds the signing keys for apk files.
|
2019-05-10 01:54:15 +02:00
|
|
|
codename_to_api_level_map: A dict that maps from codename to API level.
|
2019-09-19 16:55:02 +02:00
|
|
|
no_hashtree: Don't include hashtree in the signed APEX.
|
2019-05-10 01:54:15 +02:00
|
|
|
signing_args: Additional args to be passed to the payload signer.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The path to the signed APEX file.
|
|
|
|
"""
|
|
|
|
apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
|
|
|
|
with open(apex_file, 'wb') as apex_fp:
|
|
|
|
apex_fp.write(apex_data)
|
|
|
|
|
|
|
|
APEX_PAYLOAD_IMAGE = 'apex_payload.img'
|
|
|
|
APEX_PUBKEY = 'apex_pubkey'
|
|
|
|
|
2020-01-23 19:47:54 +01:00
|
|
|
# 1. Extract the apex payload image and sign the containing apk files. Repack
|
|
|
|
# the apex file after signing.
|
|
|
|
payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
|
|
|
|
apk_signer = ApexApkSigner(apex_file, container_pw,
|
|
|
|
codename_to_api_level_map)
|
|
|
|
apex_file = apk_signer.ProcessApexFile(apk_keys, payload_key,
|
2020-01-31 02:12:05 +01:00
|
|
|
payload_public_key, signing_args)
|
2020-01-23 19:47:54 +01:00
|
|
|
|
|
|
|
# 2a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
|
2019-05-10 01:54:15 +02:00
|
|
|
# payload_key.
|
|
|
|
payload_dir = common.MakeTempDir(prefix='apex-payload-')
|
|
|
|
with zipfile.ZipFile(apex_file) as apex_fd:
|
|
|
|
payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
|
2019-08-25 21:01:44 +02:00
|
|
|
zip_items = apex_fd.namelist()
|
2019-05-10 01:54:15 +02:00
|
|
|
|
2019-06-26 20:58:22 +02:00
|
|
|
payload_info = ParseApexPayloadInfo(avbtool, payload_file)
|
2019-05-10 01:54:15 +02:00
|
|
|
SignApexPayload(
|
2019-06-26 20:58:22 +02:00
|
|
|
avbtool,
|
2019-05-10 01:54:15 +02:00
|
|
|
payload_file,
|
|
|
|
payload_key,
|
|
|
|
payload_info['apex.key'],
|
|
|
|
payload_info['Algorithm'],
|
|
|
|
payload_info['Salt'],
|
2019-09-19 16:55:02 +02:00
|
|
|
no_hashtree,
|
2019-05-10 01:54:15 +02:00
|
|
|
signing_args)
|
|
|
|
|
2020-01-23 19:47:54 +01:00
|
|
|
# 2b. Update the embedded payload public key.
|
2019-05-10 01:54:15 +02:00
|
|
|
|
|
|
|
common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
|
2019-08-25 21:01:44 +02:00
|
|
|
if APEX_PUBKEY in zip_items:
|
|
|
|
common.ZipDelete(apex_file, APEX_PUBKEY)
|
2019-05-10 01:54:15 +02:00
|
|
|
apex_zip = zipfile.ZipFile(apex_file, 'a')
|
|
|
|
common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
|
|
|
|
common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
|
|
|
|
common.ZipClose(apex_zip)
|
|
|
|
|
2020-01-23 19:47:54 +01:00
|
|
|
# 3. Align the files at page boundary (same as in apexer).
|
2019-05-10 01:54:15 +02:00
|
|
|
aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
|
|
|
|
common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
|
|
|
|
|
2020-01-23 19:47:54 +01:00
|
|
|
# 4. Sign the APEX container with container_key.
|
2019-05-10 01:54:15 +02:00
|
|
|
signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
|
|
|
|
|
|
|
|
# Specify the 4K alignment when calling SignApk.
|
|
|
|
extra_signapk_args = OPTIONS.extra_signapk_args[:]
|
|
|
|
extra_signapk_args.extend(['-a', '4096'])
|
|
|
|
|
|
|
|
common.SignFile(
|
|
|
|
aligned_apex,
|
|
|
|
signed_apex,
|
|
|
|
container_key,
|
|
|
|
container_pw,
|
|
|
|
codename_to_api_level_map=codename_to_api_level_map,
|
|
|
|
extra_signapk_args=extra_signapk_args)
|
|
|
|
|
|
|
|
return signed_apex
|