blob: ee3c463650f4c2df02555cb1c0c14139507bc2e3 [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
Tao Baoe7354ba2019-05-09 16:54:15 -070021import zipfile
Tao Bao1cd59f22019-03-15 15:13:01 -070022
23import common
24
25logger = logging.getLogger(__name__)
26
Tao Baoe7354ba2019-05-09 16:54:15 -070027OPTIONS = common.OPTIONS
28
Tao Bao1cd59f22019-03-15 15:13:01 -070029
30class ApexInfoError(Exception):
31 """An Exception raised during Apex Information command."""
32
33 def __init__(self, message):
34 Exception.__init__(self, message)
35
36
37class ApexSigningError(Exception):
38 """An Exception raised during Apex Payload signing."""
39
40 def __init__(self, message):
41 Exception.__init__(self, message)
42
43
Tao Bao1ac886e2019-06-26 11:58:22 -070044def SignApexPayload(avbtool, payload_file, payload_key_path, payload_key_name,
Tao Bao448004a2019-09-19 07:55:02 -070045 algorithm, salt, no_hashtree, signing_args=None):
Tao Bao1cd59f22019-03-15 15:13:01 -070046 """Signs a given payload_file with the payload key."""
47 # Add the new footer. Old footer, if any, will be replaced by avbtool.
Tao Bao1ac886e2019-06-26 11:58:22 -070048 cmd = [avbtool, 'add_hashtree_footer',
Tao Bao1cd59f22019-03-15 15:13:01 -070049 '--do_not_generate_fec',
50 '--algorithm', algorithm,
51 '--key', payload_key_path,
52 '--prop', 'apex.key:{}'.format(payload_key_name),
53 '--image', payload_file,
54 '--salt', salt]
Tao Bao448004a2019-09-19 07:55:02 -070055 if no_hashtree:
56 cmd.append('--no_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -070057 if signing_args:
58 cmd.extend(shlex.split(signing_args))
59
60 try:
61 common.RunAndCheckOutput(cmd)
62 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -070063 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -070064 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -070065 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -070066
67 # Verify the signed payload image with specified public key.
68 logger.info('Verifying %s', payload_file)
Tao Bao448004a2019-09-19 07:55:02 -070069 VerifyApexPayload(avbtool, payload_file, payload_key_path, no_hashtree)
Tao Bao1cd59f22019-03-15 15:13:01 -070070
71
Tao Bao448004a2019-09-19 07:55:02 -070072def VerifyApexPayload(avbtool, payload_file, payload_key, no_hashtree=False):
Tao Bao1cd59f22019-03-15 15:13:01 -070073 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -070074 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -070075 '--key', payload_key]
Tao Bao448004a2019-09-19 07:55:02 -070076 if no_hashtree:
77 cmd.append('--accept_zeroed_hashtree')
Tao Bao1cd59f22019-03-15 15:13:01 -070078 try:
79 common.RunAndCheckOutput(cmd)
80 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -070081 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -070082 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -070083 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -070084
85
Tao Bao1ac886e2019-06-26 11:58:22 -070086def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -070087 """Parses the APEX payload info.
88
89 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -070090 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -070091 payload_path: The path to the payload image.
92
93 Raises:
94 ApexInfoError on parsing errors.
95
96 Returns:
97 A dict that contains payload property-value pairs. The dict should at least
Tao Bao448004a2019-09-19 07:55:02 -070098 contain Algorithm, Salt, Tree Size and apex.key.
Tao Bao1cd59f22019-03-15 15:13:01 -070099 """
100 if not os.path.exists(payload_path):
101 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
102
Tao Bao1ac886e2019-06-26 11:58:22 -0700103 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700104 try:
105 output = common.RunAndCheckOutput(cmd)
106 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700107 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700108 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700109 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700110
Tao Bao448004a2019-09-19 07:55:02 -0700111 # Extract the Algorithm / Salt / Prop info / Tree size from payload (i.e. an
112 # image signed with avbtool). For example,
Tao Bao1cd59f22019-03-15 15:13:01 -0700113 # Algorithm: SHA256_RSA4096
114 PAYLOAD_INFO_PATTERN = (
Tao Bao448004a2019-09-19 07:55:02 -0700115 r'^\s*(?P<key>Algorithm|Salt|Prop|Tree Size)\:\s*(?P<value>.*?)$')
Tao Bao1cd59f22019-03-15 15:13:01 -0700116 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
117
118 payload_info = {}
119 for line in output.split('\n'):
120 line_info = payload_info_matcher.match(line)
121 if not line_info:
122 continue
123
124 key, value = line_info.group('key'), line_info.group('value')
125
126 if key == 'Prop':
127 # Further extract the property key-value pair, from a 'Prop:' line. For
128 # example,
129 # Prop: apex.key -> 'com.android.runtime'
130 # Note that avbtool writes single or double quotes around values.
131 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
132
133 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
134 prop = prop_matcher.match(value)
135 if not prop:
136 raise ApexInfoError(
137 'Failed to parse prop string {}'.format(value))
138
139 prop_key, prop_value = prop.group('key'), prop.group('value')
140 if prop_key == 'apex.key':
141 # avbtool dumps the prop value with repr(), which contains single /
142 # double quotes that we don't want.
143 payload_info[prop_key] = prop_value.strip('\"\'')
144
145 else:
146 payload_info[key] = value
147
148 # Sanity check.
149 for key in ('Algorithm', 'Salt', 'apex.key'):
150 if key not in payload_info:
151 raise ApexInfoError(
152 'Failed to find {} prop in {}'.format(key, payload_path))
153
154 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700155
156
Tao Bao1ac886e2019-06-26 11:58:22 -0700157def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Tao Bao448004a2019-09-19 07:55:02 -0700158 codename_to_api_level_map, no_hashtree, signing_args=None):
Tao Baoe7354ba2019-05-09 16:54:15 -0700159 """Signs the current APEX with the given payload/container keys.
160
161 Args:
162 apex_data: Raw APEX data.
163 payload_key: The path to payload signing key (w/ extension).
164 container_key: The path to container signing key (w/o extension).
165 container_pw: The matching password of the container_key, or None.
166 codename_to_api_level_map: A dict that maps from codename to API level.
Tao Bao448004a2019-09-19 07:55:02 -0700167 no_hashtree: Don't include hashtree in the signed APEX.
Tao Baoe7354ba2019-05-09 16:54:15 -0700168 signing_args: Additional args to be passed to the payload signer.
169
170 Returns:
171 The path to the signed APEX file.
172 """
173 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
174 with open(apex_file, 'wb') as apex_fp:
175 apex_fp.write(apex_data)
176
177 APEX_PAYLOAD_IMAGE = 'apex_payload.img'
178 APEX_PUBKEY = 'apex_pubkey'
179
180 # 1a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
181 # payload_key.
182 payload_dir = common.MakeTempDir(prefix='apex-payload-')
183 with zipfile.ZipFile(apex_file) as apex_fd:
184 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700185 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700186
Tao Bao1ac886e2019-06-26 11:58:22 -0700187 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700188 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700189 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700190 payload_file,
191 payload_key,
192 payload_info['apex.key'],
193 payload_info['Algorithm'],
194 payload_info['Salt'],
Tao Bao448004a2019-09-19 07:55:02 -0700195 no_hashtree,
Tao Baoe7354ba2019-05-09 16:54:15 -0700196 signing_args)
197
198 # 1b. Update the embedded payload public key.
Tao Bao1ac886e2019-06-26 11:58:22 -0700199 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700200
201 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700202 if APEX_PUBKEY in zip_items:
203 common.ZipDelete(apex_file, APEX_PUBKEY)
Tao Baoe7354ba2019-05-09 16:54:15 -0700204 apex_zip = zipfile.ZipFile(apex_file, 'a')
205 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
206 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
207 common.ZipClose(apex_zip)
208
209 # 2. Align the files at page boundary (same as in apexer).
210 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
211 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
212
213 # 3. Sign the APEX container with container_key.
214 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
215
216 # Specify the 4K alignment when calling SignApk.
217 extra_signapk_args = OPTIONS.extra_signapk_args[:]
218 extra_signapk_args.extend(['-a', '4096'])
219
220 common.SignFile(
221 aligned_apex,
222 signed_apex,
223 container_key,
224 container_pw,
225 codename_to_api_level_map=codename_to_api_level_map,
226 extra_signapk_args=extra_signapk_args)
227
228 return signed_apex