blob: 18ad8cec0df76af8bf7e33635670905ad315b2cd [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,
45 algorithm, salt, 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]
55 if signing_args:
56 cmd.extend(shlex.split(signing_args))
57
58 try:
59 common.RunAndCheckOutput(cmd)
60 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -070061 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -070062 'Failed to sign APEX payload {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -070063 payload_file, payload_key_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -070064
65 # Verify the signed payload image with specified public key.
66 logger.info('Verifying %s', payload_file)
Tao Bao1ac886e2019-06-26 11:58:22 -070067 VerifyApexPayload(avbtool, payload_file, payload_key_path)
Tao Bao1cd59f22019-03-15 15:13:01 -070068
69
Tao Bao1ac886e2019-06-26 11:58:22 -070070def VerifyApexPayload(avbtool, payload_file, payload_key):
Tao Bao1cd59f22019-03-15 15:13:01 -070071 """Verifies the APEX payload signature with the given key."""
Tao Bao1ac886e2019-06-26 11:58:22 -070072 cmd = [avbtool, 'verify_image', '--image', payload_file,
Tao Bao1cd59f22019-03-15 15:13:01 -070073 '--key', payload_key]
74 try:
75 common.RunAndCheckOutput(cmd)
76 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -070077 raise ApexSigningError(
Tao Bao1cd59f22019-03-15 15:13:01 -070078 'Failed to validate payload signing for {} with {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -070079 payload_file, payload_key, e))
Tao Bao1cd59f22019-03-15 15:13:01 -070080
81
Tao Bao1ac886e2019-06-26 11:58:22 -070082def ParseApexPayloadInfo(avbtool, payload_path):
Tao Bao1cd59f22019-03-15 15:13:01 -070083 """Parses the APEX payload info.
84
85 Args:
Tao Bao1ac886e2019-06-26 11:58:22 -070086 avbtool: The AVB tool to use.
Tao Bao1cd59f22019-03-15 15:13:01 -070087 payload_path: The path to the payload image.
88
89 Raises:
90 ApexInfoError on parsing errors.
91
92 Returns:
93 A dict that contains payload property-value pairs. The dict should at least
94 contain Algorithm, Salt and apex.key.
95 """
96 if not os.path.exists(payload_path):
97 raise ApexInfoError('Failed to find image: {}'.format(payload_path))
98
Tao Bao1ac886e2019-06-26 11:58:22 -070099 cmd = [avbtool, 'info_image', '--image', payload_path]
Tao Bao1cd59f22019-03-15 15:13:01 -0700100 try:
101 output = common.RunAndCheckOutput(cmd)
102 except common.ExternalError as e:
Tao Bao86b529a2019-06-19 17:03:37 -0700103 raise ApexInfoError(
Tao Bao1cd59f22019-03-15 15:13:01 -0700104 'Failed to get APEX payload info for {}:\n{}'.format(
Tao Bao86b529a2019-06-19 17:03:37 -0700105 payload_path, e))
Tao Bao1cd59f22019-03-15 15:13:01 -0700106
107 # Extract the Algorithm / Salt / Prop info from payload (i.e. an image signed
108 # with avbtool). For example,
109 # Algorithm: SHA256_RSA4096
110 PAYLOAD_INFO_PATTERN = (
111 r'^\s*(?P<key>Algorithm|Salt|Prop)\:\s*(?P<value>.*?)$')
112 payload_info_matcher = re.compile(PAYLOAD_INFO_PATTERN)
113
114 payload_info = {}
115 for line in output.split('\n'):
116 line_info = payload_info_matcher.match(line)
117 if not line_info:
118 continue
119
120 key, value = line_info.group('key'), line_info.group('value')
121
122 if key == 'Prop':
123 # Further extract the property key-value pair, from a 'Prop:' line. For
124 # example,
125 # Prop: apex.key -> 'com.android.runtime'
126 # Note that avbtool writes single or double quotes around values.
127 PROPERTY_DESCRIPTOR_PATTERN = r'^\s*(?P<key>.*?)\s->\s*(?P<value>.*?)$'
128
129 prop_matcher = re.compile(PROPERTY_DESCRIPTOR_PATTERN)
130 prop = prop_matcher.match(value)
131 if not prop:
132 raise ApexInfoError(
133 'Failed to parse prop string {}'.format(value))
134
135 prop_key, prop_value = prop.group('key'), prop.group('value')
136 if prop_key == 'apex.key':
137 # avbtool dumps the prop value with repr(), which contains single /
138 # double quotes that we don't want.
139 payload_info[prop_key] = prop_value.strip('\"\'')
140
141 else:
142 payload_info[key] = value
143
144 # Sanity check.
145 for key in ('Algorithm', 'Salt', 'apex.key'):
146 if key not in payload_info:
147 raise ApexInfoError(
148 'Failed to find {} prop in {}'.format(key, payload_path))
149
150 return payload_info
Tao Baoe7354ba2019-05-09 16:54:15 -0700151
152
Tao Bao1ac886e2019-06-26 11:58:22 -0700153def SignApex(avbtool, apex_data, payload_key, container_key, container_pw,
Tao Baoe7354ba2019-05-09 16:54:15 -0700154 codename_to_api_level_map, signing_args=None):
155 """Signs the current APEX with the given payload/container keys.
156
157 Args:
158 apex_data: Raw APEX data.
159 payload_key: The path to payload signing key (w/ extension).
160 container_key: The path to container signing key (w/o extension).
161 container_pw: The matching password of the container_key, or None.
162 codename_to_api_level_map: A dict that maps from codename to API level.
163 signing_args: Additional args to be passed to the payload signer.
164
165 Returns:
166 The path to the signed APEX file.
167 """
168 apex_file = common.MakeTempFile(prefix='apex-', suffix='.apex')
169 with open(apex_file, 'wb') as apex_fp:
170 apex_fp.write(apex_data)
171
172 APEX_PAYLOAD_IMAGE = 'apex_payload.img'
173 APEX_PUBKEY = 'apex_pubkey'
174
175 # 1a. Extract and sign the APEX_PAYLOAD_IMAGE entry with the given
176 # payload_key.
177 payload_dir = common.MakeTempDir(prefix='apex-payload-')
178 with zipfile.ZipFile(apex_file) as apex_fd:
179 payload_file = apex_fd.extract(APEX_PAYLOAD_IMAGE, payload_dir)
Baligh Uddin15881282019-08-25 12:01:44 -0700180 zip_items = apex_fd.namelist()
Tao Baoe7354ba2019-05-09 16:54:15 -0700181
Tao Bao1ac886e2019-06-26 11:58:22 -0700182 payload_info = ParseApexPayloadInfo(avbtool, payload_file)
Tao Baoe7354ba2019-05-09 16:54:15 -0700183 SignApexPayload(
Tao Bao1ac886e2019-06-26 11:58:22 -0700184 avbtool,
Tao Baoe7354ba2019-05-09 16:54:15 -0700185 payload_file,
186 payload_key,
187 payload_info['apex.key'],
188 payload_info['Algorithm'],
189 payload_info['Salt'],
190 signing_args)
191
192 # 1b. Update the embedded payload public key.
Tao Bao1ac886e2019-06-26 11:58:22 -0700193 payload_public_key = common.ExtractAvbPublicKey(avbtool, payload_key)
Tao Baoe7354ba2019-05-09 16:54:15 -0700194
195 common.ZipDelete(apex_file, APEX_PAYLOAD_IMAGE)
Baligh Uddin15881282019-08-25 12:01:44 -0700196 if APEX_PUBKEY in zip_items:
197 common.ZipDelete(apex_file, APEX_PUBKEY)
Tao Baoe7354ba2019-05-09 16:54:15 -0700198 apex_zip = zipfile.ZipFile(apex_file, 'a')
199 common.ZipWrite(apex_zip, payload_file, arcname=APEX_PAYLOAD_IMAGE)
200 common.ZipWrite(apex_zip, payload_public_key, arcname=APEX_PUBKEY)
201 common.ZipClose(apex_zip)
202
203 # 2. Align the files at page boundary (same as in apexer).
204 aligned_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
205 common.RunAndCheckOutput(['zipalign', '-f', '4096', apex_file, aligned_apex])
206
207 # 3. Sign the APEX container with container_key.
208 signed_apex = common.MakeTempFile(prefix='apex-container-', suffix='.apex')
209
210 # Specify the 4K alignment when calling SignApk.
211 extra_signapk_args = OPTIONS.extra_signapk_args[:]
212 extra_signapk_args.extend(['-a', '4096'])
213
214 common.SignFile(
215 aligned_apex,
216 signed_apex,
217 container_key,
218 container_pw,
219 codename_to_api_level_map=codename_to_api_level_map,
220 extra_signapk_args=extra_signapk_args)
221
222 return signed_apex