blob: fa62c8f63cf0ce577059866e485e54101d5954ec [file] [log] [blame]
Doug Zongkereef39442009-04-02 12:14:19 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2008 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"""
18Signs all the APK files in a target-files zipfile, producing a new
19target-files zip.
20
21Usage: sign_target_files_apks [flags] input_target_files output_target_files
22
Doug Zongkereef39442009-04-02 12:14:19 -070023 -e (--extra_apks) <name,name,...=key>
24 Add extra APK name/key pairs as though they appeared in
Doug Zongkerad88c7c2009-04-14 12:34:27 -070025 apkcerts.txt (so mappings specified by -k and -d are applied).
26 Keys specified in -e override any value for that app contained
27 in the apkcerts.txt file. Option may be repeated to give
28 multiple extra packages.
Doug Zongkereef39442009-04-02 12:14:19 -070029
30 -k (--key_mapping) <src_key=dest_key>
31 Add a mapping from the key name as specified in apkcerts.txt (the
32 src_key) to the real key you wish to sign the package with
33 (dest_key). Option may be repeated to give multiple key
34 mappings.
35
36 -d (--default_key_mappings) <dir>
37 Set up the following key mappings:
38
Doug Zongker831840e2011-09-22 10:28:04 -070039 $devkey/devkey ==> $dir/releasekey
40 $devkey/testkey ==> $dir/releasekey
41 $devkey/media ==> $dir/media
42 $devkey/shared ==> $dir/shared
43 $devkey/platform ==> $dir/platform
44
45 where $devkey is the directory part of the value of
46 default_system_dev_certificate from the input target-files's
47 META/misc_info.txt. (Defaulting to "build/target/product/security"
48 if the value is not present in misc_info.
Doug Zongkereef39442009-04-02 12:14:19 -070049
50 -d and -k options are added to the set of mappings in the order
51 in which they appear on the command line.
Doug Zongker8e931bf2009-04-06 15:21:45 -070052
53 -o (--replace_ota_keys)
Tao Baoa80ed222016-06-16 14:41:24 -070054 Replace the certificate (public key) used by OTA package verification
55 with the ones specified in the input target_files zip (in the
56 META/otakeys.txt file). Key remapping (-k and -d) is performed on the
57 keys. For A/B devices, the payload verification key will be replaced
58 as well. If there're multiple OTA keys, only the first one will be used
59 for payload verification.
Doug Zongker17aa9442009-04-17 10:15:58 -070060
Doug Zongkerae877012009-04-21 10:04:51 -070061 -t (--tag_changes) <+tag>,<-tag>,...
62 Comma-separated list of changes to make to the set of tags (in
63 the last component of the build fingerprint). Prefix each with
64 '+' or '-' to indicate whether that tag should be added or
65 removed. Changes are processed in the order they appear.
Doug Zongker831840e2011-09-22 10:28:04 -070066 Default value is "-test-keys,-dev-keys,+release-keys".
Doug Zongkerae877012009-04-21 10:04:51 -070067
Tao Bao8adcfd12016-06-17 17:01:22 -070068 --replace_verity_private_key <key>
69 Replace the private key used for verity signing. It expects a filename
70 WITHOUT the extension (e.g. verity_key).
71
72 --replace_verity_public_key <key>
73 Replace the certificate (public key) used for verity verification. The
74 key file replaces the one at BOOT/RAMDISK/verity_key (or ROOT/verity_key
75 for devices using system_root_image). It expects the key filename WITH
76 the extension (e.g. verity_key.pub).
77
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -070078 --replace_verity_keyid <path_to_X509_PEM_cert_file>
79 Replace the veritykeyid in BOOT/cmdline of input_target_file_zip
Tao Bao8adcfd12016-06-17 17:01:22 -070080 with keyid of the cert pointed by <path_to_X509_PEM_cert_file>.
Tao Bao639118f2017-06-19 15:48:02 -070081
82 --avb_{boot,system,vendor,dtbo,vbmeta}_algorithm <algorithm>
83 --avb_{boot,system,vendor,dtbo,vbmeta}_key <key>
84 Use the specified algorithm (e.g. SHA256_RSA4096) and the key to AVB-sign
85 the specified image. Otherwise it uses the existing values in info dict.
86
87 --avb_{boot,system,vendor,dtbo,vbmeta}_extra_args <args>
88 Specify any additional args that are needed to AVB-sign the image
89 (e.g. "--signing_helper /path/to/helper"). The args will be appended to
90 the existing ones in info dict.
Doug Zongkereef39442009-04-02 12:14:19 -070091"""
92
Tao Bao0c28d2d2017-12-24 10:37:38 -080093from __future__ import print_function
Doug Zongkereef39442009-04-02 12:14:19 -070094
Robert Craig817c5742013-04-19 10:59:22 -040095import base64
Doug Zongker8e931bf2009-04-06 15:21:45 -070096import copy
Robert Craig817c5742013-04-19 10:59:22 -040097import errno
Narayan Kamatha07bf042017-08-14 14:49:21 +010098import gzip
Doug Zongkereef39442009-04-02 12:14:19 -070099import os
100import re
Narayan Kamatha07bf042017-08-14 14:49:21 +0100101import shutil
Tao Bao9fdd00f2017-07-12 11:57:05 -0700102import stat
Doug Zongkereef39442009-04-02 12:14:19 -0700103import subprocess
Tao Bao0c28d2d2017-12-24 10:37:38 -0800104import sys
Doug Zongkereef39442009-04-02 12:14:19 -0700105import tempfile
106import zipfile
Tao Bao66472632017-12-04 17:16:36 -0800107from xml.etree import ElementTree
Doug Zongkereef39442009-04-02 12:14:19 -0700108
Doug Zongker3c84f562014-07-31 11:06:30 -0700109import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -0700110import common
111
Tao Bao0c28d2d2017-12-24 10:37:38 -0800112
113if sys.hexversion < 0x02070000:
114 print("Python 2.7 or newer is required.", file=sys.stderr)
115 sys.exit(1)
116
117
Doug Zongkereef39442009-04-02 12:14:19 -0700118OPTIONS = common.OPTIONS
119
120OPTIONS.extra_apks = {}
121OPTIONS.key_map = {}
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700122OPTIONS.rebuild_recovery = False
Doug Zongker8e931bf2009-04-06 15:21:45 -0700123OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -0700124OPTIONS.replace_verity_public_key = False
125OPTIONS.replace_verity_private_key = False
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700126OPTIONS.replace_verity_keyid = False
Doug Zongker831840e2011-09-22 10:28:04 -0700127OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Tao Bao639118f2017-06-19 15:48:02 -0700128OPTIONS.avb_keys = {}
129OPTIONS.avb_algorithms = {}
130OPTIONS.avb_extra_args = {}
Doug Zongkereef39442009-04-02 12:14:19 -0700131
Tao Bao0c28d2d2017-12-24 10:37:38 -0800132
Narayan Kamatha07bf042017-08-14 14:49:21 +0100133def GetApkCerts(certmap):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800134 # apply the key remapping to the contents of the file
135 for apk, cert in certmap.iteritems():
136 certmap[apk] = OPTIONS.key_map.get(cert, cert)
137
138 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700139 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800140 if not cert:
141 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700142 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800143
Doug Zongkereef39442009-04-02 12:14:19 -0700144 return certmap
145
146
Narayan Kamatha07bf042017-08-14 14:49:21 +0100147def CheckAllApksSigned(input_tf_zip, apk_key_map, compressed_extension):
Doug Zongkereb338ef2009-05-20 16:50:49 -0700148 """Check that all the APKs we want to sign have keys specified, and
149 error out if they don't."""
150 unknown_apks = []
Narayan Kamatha07bf042017-08-14 14:49:21 +0100151 compressed_apk_extension = None
152 if compressed_extension:
153 compressed_apk_extension = ".apk" + compressed_extension
Doug Zongkereb338ef2009-05-20 16:50:49 -0700154 for info in input_tf_zip.infolist():
Narayan Kamatha07bf042017-08-14 14:49:21 +0100155 if (info.filename.endswith(".apk") or
Tao Bao0c28d2d2017-12-24 10:37:38 -0800156 (compressed_apk_extension and
157 info.filename.endswith(compressed_apk_extension))):
Doug Zongkereb338ef2009-05-20 16:50:49 -0700158 name = os.path.basename(info.filename)
Narayan Kamatha07bf042017-08-14 14:49:21 +0100159 if compressed_apk_extension and name.endswith(compressed_apk_extension):
160 name = name[:-len(compressed_extension)]
Doug Zongkereb338ef2009-05-20 16:50:49 -0700161 if name not in apk_key_map:
162 unknown_apks.append(name)
163 if unknown_apks:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800164 print("ERROR: no key specified for:\n")
165 print(" " + "\n ".join(unknown_apks))
166 print("\nUse '-e <apkname>=' to specify a key (which may be an empty "
167 "string to not sign this apk).")
Doug Zongkereb338ef2009-05-20 16:50:49 -0700168 sys.exit(1)
169
170
Narayan Kamatha07bf042017-08-14 14:49:21 +0100171def SignApk(data, keyname, pw, platform_api_level, codename_to_api_level_map,
172 is_compressed):
Doug Zongkereef39442009-04-02 12:14:19 -0700173 unsigned = tempfile.NamedTemporaryFile()
174 unsigned.write(data)
175 unsigned.flush()
176
Narayan Kamatha07bf042017-08-14 14:49:21 +0100177 if is_compressed:
178 uncompressed = tempfile.NamedTemporaryFile()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800179 with gzip.open(unsigned.name, "rb") as in_file, \
180 open(uncompressed.name, "wb") as out_file:
Narayan Kamatha07bf042017-08-14 14:49:21 +0100181 shutil.copyfileobj(in_file, out_file)
182
183 # Finally, close the "unsigned" file (which is gzip compressed), and then
184 # replace it with the uncompressed version.
185 #
186 # TODO(narayan): All this nastiness can be avoided if python 3.2 is in use,
187 # we could just gzip / gunzip in-memory buffers instead.
188 unsigned.close()
189 unsigned = uncompressed
190
Doug Zongkereef39442009-04-02 12:14:19 -0700191 signed = tempfile.NamedTemporaryFile()
192
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800193 # For pre-N builds, don't upgrade to SHA-256 JAR signatures based on the APK's
194 # minSdkVersion to avoid increasing incremental OTA update sizes. If an APK
195 # didn't change, we don't want its signature to change due to the switch
196 # from SHA-1 to SHA-256.
197 # By default, APK signer chooses SHA-256 signatures if the APK's minSdkVersion
198 # is 18 or higher. For pre-N builds we disable this mechanism by pretending
199 # that the APK's minSdkVersion is 1.
200 # For N+ builds, we let APK signer rely on the APK's minSdkVersion to
201 # determine whether to use SHA-256.
202 min_api_level = None
203 if platform_api_level > 23:
204 # Let APK signer choose whether to use SHA-1 or SHA-256, based on the APK's
205 # minSdkVersion attribute
206 min_api_level = None
207 else:
208 # Force APK signer to use SHA-1
209 min_api_level = 1
210
211 common.SignFile(unsigned.name, signed.name, keyname, pw,
Tao Bao0c28d2d2017-12-24 10:37:38 -0800212 min_api_level=min_api_level,
213 codename_to_api_level_map=codename_to_api_level_map)
Doug Zongkereef39442009-04-02 12:14:19 -0700214
Tao Bao0c28d2d2017-12-24 10:37:38 -0800215 data = None
Narayan Kamatha07bf042017-08-14 14:49:21 +0100216 if is_compressed:
217 # Recompress the file after it has been signed.
218 compressed = tempfile.NamedTemporaryFile()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800219 with open(signed.name, "rb") as in_file, \
220 gzip.open(compressed.name, "wb") as out_file:
Narayan Kamatha07bf042017-08-14 14:49:21 +0100221 shutil.copyfileobj(in_file, out_file)
222
223 data = compressed.read()
224 compressed.close()
225 else:
226 data = signed.read()
227
Doug Zongkereef39442009-04-02 12:14:19 -0700228 unsigned.close()
229 signed.close()
230
231 return data
232
233
Doug Zongker412c02f2014-02-13 10:58:24 -0800234def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800235 apk_key_map, key_passwords, platform_api_level,
Narayan Kamatha07bf042017-08-14 14:49:21 +0100236 codename_to_api_level_map,
237 compressed_extension):
238
239 compressed_apk_extension = None
240 if compressed_extension:
241 compressed_apk_extension = ".apk" + compressed_extension
Michael Rungedc2661a2014-06-03 14:43:11 -0700242
Tao Bao0c28d2d2017-12-24 10:37:38 -0800243 maxsize = max(
244 [len(os.path.basename(i.filename)) for i in input_tf_zip.infolist()
245 if (i.filename.endswith('.apk') or
246 (compressed_apk_extension and
247 i.filename.endswith(compressed_apk_extension)))])
Tao Baoa80ed222016-06-16 14:41:24 -0700248 system_root_image = misc_info.get("system_root_image") == "true"
Doug Zongker412c02f2014-02-13 10:58:24 -0800249
Doug Zongkereef39442009-04-02 12:14:19 -0700250 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700251 if info.filename.startswith("IMAGES/"):
252 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700253
Doug Zongkereef39442009-04-02 12:14:19 -0700254 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700255 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800256
Tao Baof2cffbd2015-07-22 12:33:18 -0700257 # Sign APKs.
Narayan Kamatha07bf042017-08-14 14:49:21 +0100258 if (info.filename.endswith(".apk") or
Tao Bao0c28d2d2017-12-24 10:37:38 -0800259 (compressed_apk_extension and
260 info.filename.endswith(compressed_apk_extension))):
261 is_compressed = (compressed_extension and
262 info.filename.endswith(compressed_apk_extension))
Doug Zongkereef39442009-04-02 12:14:19 -0700263 name = os.path.basename(info.filename)
Narayan Kamatha07bf042017-08-14 14:49:21 +0100264 if is_compressed:
265 name = name[:-len(compressed_extension)]
266
Doug Zongker43874f82009-04-14 14:05:15 -0700267 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800268 if key not in common.SPECIAL_CERT_STRINGS:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800269 print(" signing: %-*s (%s)" % (maxsize, name, key))
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800270 signed_data = SignApk(data, key, key_passwords[key], platform_api_level,
Tao Bao0c28d2d2017-12-24 10:37:38 -0800271 codename_to_api_level_map, is_compressed)
Tao Bao2ed665a2015-04-01 11:21:55 -0700272 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700273 else:
274 # an APK we're not supposed to sign.
Tao Bao0c28d2d2017-12-24 10:37:38 -0800275 print("NOT signing: %s" % (name,))
Tao Bao2ed665a2015-04-01 11:21:55 -0700276 common.ZipWriteStr(output_tf_zip, out_info, data)
Tao Baoa80ed222016-06-16 14:41:24 -0700277
278 # System properties.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700279 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800280 "VENDOR/build.prop",
Hung-ying Tyan7eb6a922017-05-01 21:56:26 +0800281 "SYSTEM/etc/prop.default",
282 "BOOT/RAMDISK/prop.default",
283 "BOOT/RAMDISK/default.prop", # legacy
284 "ROOT/default.prop", # legacy
285 "RECOVERY/RAMDISK/prop.default",
286 "RECOVERY/RAMDISK/default.prop"): # legacy
Tao Bao0c28d2d2017-12-24 10:37:38 -0800287 print("Rewriting %s:" % (info.filename,))
Hung-ying Tyan7eb6a922017-05-01 21:56:26 +0800288 if stat.S_ISLNK(info.external_attr >> 16):
289 new_data = data
290 else:
Tao Baoa7054ee2017-12-08 14:42:16 -0800291 new_data = RewriteProps(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700292 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700293
Tao Bao66472632017-12-04 17:16:36 -0800294 # Replace the certs in *mac_permissions.xml (there could be multiple, such
295 # as {system,vendor}/etc/selinux/{plat,nonplat}_mac_permissions.xml).
Robert Craig817c5742013-04-19 10:59:22 -0400296 elif info.filename.endswith("mac_permissions.xml"):
Tao Bao0c28d2d2017-12-24 10:37:38 -0800297 print("Rewriting %s with new keys." % (info.filename,))
Robert Craig817c5742013-04-19 10:59:22 -0400298 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700299 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700300
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700301 # Ask add_img_to_target_files to rebuild the recovery patch if needed.
Doug Zongker412c02f2014-02-13 10:58:24 -0800302 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700303 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800304 "SYSTEM/bin/install-recovery.sh"):
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700305 OPTIONS.rebuild_recovery = True
Tao Baoa80ed222016-06-16 14:41:24 -0700306
307 # Don't copy OTA keys if we're replacing them.
Doug Zongker412c02f2014-02-13 10:58:24 -0800308 elif (OPTIONS.replace_ota_keys and
Tao Baoa80ed222016-06-16 14:41:24 -0700309 info.filename in (
310 "BOOT/RAMDISK/res/keys",
Alex Deymob3e8ce62016-08-04 16:06:12 -0700311 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
Tao Baoa80ed222016-06-16 14:41:24 -0700312 "RECOVERY/RAMDISK/res/keys",
313 "SYSTEM/etc/security/otacerts.zip",
314 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800315 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700316
Tao Bao46a59992017-06-05 11:55:16 -0700317 # Skip META/misc_info.txt since we will write back the new values later.
318 elif info.filename == "META/misc_info.txt":
Geremy Condraf19b3652014-07-29 17:54:54 -0700319 pass
Tao Bao8adcfd12016-06-17 17:01:22 -0700320
321 # Skip verity public key if we will replace it.
Michael Runge947894f2014-10-14 20:58:38 -0700322 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700323 info.filename in ("BOOT/RAMDISK/verity_key",
Tao Bao8adcfd12016-06-17 17:01:22 -0700324 "ROOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700325 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700326
Tao Bao8adcfd12016-06-17 17:01:22 -0700327 # Skip verity keyid (for system_root_image use) if we will replace it.
328 elif (OPTIONS.replace_verity_keyid and
329 info.filename == "BOOT/cmdline"):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700330 pass
331
Tianjie Xu4f099002016-08-11 18:04:27 -0700332 # Skip the care_map as we will regenerate the system/vendor images.
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700333 elif info.filename == "META/care_map.txt":
Tianjie Xu4f099002016-08-11 18:04:27 -0700334 pass
335
Tao Baoa80ed222016-06-16 14:41:24 -0700336 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700337 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700338 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700339
Doug Zongker412c02f2014-02-13 10:58:24 -0800340 if OPTIONS.replace_ota_keys:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700341 ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800342
Tao Bao46a59992017-06-05 11:55:16 -0700343 # Replace the keyid string in misc_info dict.
Tao Bao8adcfd12016-06-17 17:01:22 -0700344 if OPTIONS.replace_verity_private_key:
Tao Bao46a59992017-06-05 11:55:16 -0700345 ReplaceVerityPrivateKey(misc_info, OPTIONS.replace_verity_private_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700346
347 if OPTIONS.replace_verity_public_key:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800348 dest = "ROOT/verity_key" if system_root_image else "BOOT/RAMDISK/verity_key"
Tao Bao8adcfd12016-06-17 17:01:22 -0700349 # We are replacing the one in boot image only, since the one under
350 # recovery won't ever be needed.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700351 ReplaceVerityPublicKey(
Tao Bao8adcfd12016-06-17 17:01:22 -0700352 output_tf_zip, dest, OPTIONS.replace_verity_public_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700353
354 # Replace the keyid string in BOOT/cmdline.
355 if OPTIONS.replace_verity_keyid:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700356 ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
357 OPTIONS.replace_verity_keyid[1])
Doug Zongker412c02f2014-02-13 10:58:24 -0800358
Tao Bao639118f2017-06-19 15:48:02 -0700359 # Replace the AVB signing keys, if any.
360 ReplaceAvbSigningKeys(misc_info)
361
Tao Bao46a59992017-06-05 11:55:16 -0700362 # Write back misc_info with the latest values.
363 ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
364
Doug Zongker8e931bf2009-04-06 15:21:45 -0700365
Robert Craig817c5742013-04-19 10:59:22 -0400366def ReplaceCerts(data):
Tao Bao66472632017-12-04 17:16:36 -0800367 """Replaces all the occurences of X.509 certs with the new ones.
Robert Craig817c5742013-04-19 10:59:22 -0400368
Tao Bao66472632017-12-04 17:16:36 -0800369 The mapping info is read from OPTIONS.key_map. Non-existent certificate will
370 be skipped. After the replacement, it additionally checks for duplicate
371 entries, which would otherwise fail the policy loading code in
372 frameworks/base/services/core/java/com/android/server/pm/SELinuxMMAC.java.
373
374 Args:
375 data: Input string that contains a set of X.509 certs.
376
377 Returns:
378 A string after the replacement.
379
380 Raises:
381 AssertionError: On finding duplicate entries.
382 """
383 for old, new in OPTIONS.key_map.iteritems():
384 if OPTIONS.verbose:
385 print(" Replacing %s.x509.pem with %s.x509.pem" % (old, new))
386
387 try:
388 with open(old + ".x509.pem") as old_fp:
389 old_cert16 = base64.b16encode(
390 common.ParseCertificate(old_fp.read())).lower()
391 with open(new + ".x509.pem") as new_fp:
392 new_cert16 = base64.b16encode(
393 common.ParseCertificate(new_fp.read())).lower()
394 except IOError as e:
395 if OPTIONS.verbose or e.errno != errno.ENOENT:
396 print(" Error accessing %s: %s.\nSkip replacing %s.x509.pem with "
397 "%s.x509.pem." % (e.filename, e.strerror, old, new))
398 continue
399
400 # Only match entire certs.
401 pattern = "\\b" + old_cert16 + "\\b"
402 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
403
404 if OPTIONS.verbose:
405 print(" Replaced %d occurence(s) of %s.x509.pem with %s.x509.pem" % (
406 num, old, new))
407
408 # Verify that there're no duplicate entries after the replacement. Note that
409 # it's only checking entries with global seinfo at the moment (i.e. ignoring
410 # the ones with inner packages). (Bug: 69479366)
411 root = ElementTree.fromstring(data)
412 signatures = [signer.attrib['signature'] for signer in root.findall('signer')]
413 assert len(signatures) == len(set(signatures)), \
414 "Found duplicate entries after cert replacement: {}".format(data)
Robert Craig817c5742013-04-19 10:59:22 -0400415
416 return data
417
418
Doug Zongkerc09abc82010-01-11 13:09:15 -0800419def EditTags(tags):
Tao Baoa7054ee2017-12-08 14:42:16 -0800420 """Applies the edits to the tag string as specified in OPTIONS.tag_changes.
421
422 Args:
423 tags: The input string that contains comma-separated tags.
424
425 Returns:
426 The updated tags (comma-separated and sorted).
427 """
Doug Zongkerc09abc82010-01-11 13:09:15 -0800428 tags = set(tags.split(","))
429 for ch in OPTIONS.tag_changes:
430 if ch[0] == "-":
431 tags.discard(ch[1:])
432 elif ch[0] == "+":
433 tags.add(ch[1:])
434 return ",".join(sorted(tags))
435
436
Tao Baoa7054ee2017-12-08 14:42:16 -0800437def RewriteProps(data):
438 """Rewrites the system properties in the given string.
439
440 Each property is expected in 'key=value' format. The properties that contain
441 build tags (i.e. test-keys, dev-keys) will be updated accordingly by calling
442 EditTags().
443
444 Args:
445 data: Input string, separated by newlines.
446
447 Returns:
448 The string with modified properties.
449 """
Doug Zongker17aa9442009-04-17 10:15:58 -0700450 output = []
451 for line in data.split("\n"):
452 line = line.strip()
453 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700454 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700455 key, value = line.split("=", 1)
Tao Baoa7054ee2017-12-08 14:42:16 -0800456 if key in ("ro.build.fingerprint", "ro.build.thumbprint",
457 "ro.vendor.build.fingerprint", "ro.vendor.build.thumbprint"):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800458 pieces = value.split("/")
459 pieces[-1] = EditTags(pieces[-1])
460 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700461 elif key == "ro.bootimage.build.fingerprint":
462 pieces = value.split("/")
463 pieces[-1] = EditTags(pieces[-1])
464 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700465 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800466 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700467 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800468 pieces[-1] = EditTags(pieces[-1])
469 value = " ".join(pieces)
470 elif key == "ro.build.tags":
471 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700472 elif key == "ro.build.display.id":
473 # change, eg, "JWR66N dev-keys" to "JWR66N"
474 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700475 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800476 value.pop()
477 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800478 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700479 if line != original_line:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800480 print(" replace: ", original_line)
481 print(" with: ", line)
Doug Zongker17aa9442009-04-17 10:15:58 -0700482 output.append(line)
483 return "\n".join(output) + "\n"
484
485
Doug Zongker831840e2011-09-22 10:28:04 -0700486def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700487 try:
488 keylist = input_tf_zip.read("META/otakeys.txt").split()
489 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700490 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700491
Tao Baof718f902017-11-09 10:10:10 -0800492 extra_recovery_keys = misc_info.get("extra_recovery_keys")
Doug Zongkere121d6a2011-02-01 14:13:52 -0800493 if extra_recovery_keys:
494 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
495 for k in extra_recovery_keys.split()]
496 if extra_recovery_keys:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800497 print("extra recovery-only key(s): " + ", ".join(extra_recovery_keys))
Doug Zongkere121d6a2011-02-01 14:13:52 -0800498 else:
499 extra_recovery_keys = []
500
Doug Zongker8e931bf2009-04-06 15:21:45 -0700501 mapped_keys = []
502 for k in keylist:
503 m = re.match(r"^(.*)\.x509\.pem$", k)
504 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800505 raise common.ExternalError(
506 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700507 k = m.group(1)
508 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
509
Doug Zongkere05628c2009-08-20 17:38:42 -0700510 if mapped_keys:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800511 print("using:\n ", "\n ".join(mapped_keys))
512 print("for OTA package verification")
Doug Zongkere05628c2009-08-20 17:38:42 -0700513 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700514 devkey = misc_info.get("default_system_dev_certificate",
515 "build/target/product/security/testkey")
Tao Baof718f902017-11-09 10:10:10 -0800516 mapped_devkey = OPTIONS.key_map.get(devkey, devkey)
517 if mapped_devkey != devkey:
518 misc_info["default_system_dev_certificate"] = mapped_devkey
519 mapped_keys.append(mapped_devkey + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700520 print("META/otakeys.txt has no keys; using %s for OTA package"
521 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700522
523 # recovery uses a version of the key that has been slightly
524 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800525 # extra_recovery_keys are used only in recovery.
Tao Baoe95540e2016-11-08 12:08:53 -0800526 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
527 ["-jar",
528 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")] +
529 mapped_keys + extra_recovery_keys)
530 p = common.Run(cmd, stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800531 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700532 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700533 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700534
535 # system_root_image puts the recovery keys at BOOT/RAMDISK.
536 if misc_info.get("system_root_image") == "true":
537 recovery_keys_location = "BOOT/RAMDISK/res/keys"
538 else:
539 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
540 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700541
542 # SystemUpdateActivity uses the x509.pem version of the keys, but
543 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800544 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700545
Tao Bao0c28d2d2017-12-24 10:37:38 -0800546 try:
547 from StringIO import StringIO
548 except ImportError:
549 from io import StringIO
550 temp_file = StringIO()
Dan Albert8b72aef2015-03-23 19:13:21 -0700551 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700552 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700553 common.ZipWrite(certs_zip, k)
554 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700555 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700556 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700557
Tao Baoa80ed222016-06-16 14:41:24 -0700558 # For A/B devices, update the payload verification key.
559 if misc_info.get("ab_update") == "true":
560 # Unlike otacerts.zip that may contain multiple keys, we can only specify
561 # ONE payload verification key.
562 if len(mapped_keys) > 1:
563 print("\n WARNING: Found more than one OTA keys; Using the first one"
564 " as payload verification key.\n\n")
565
Tao Bao0c28d2d2017-12-24 10:37:38 -0800566 print("Using %s for payload verification." % (mapped_keys[0],))
Tao Bao04e1f012018-02-04 12:13:35 -0800567 pubkey = common.ExtractPublicKey(mapped_keys[0])
Tao Bao13b69622016-07-06 15:28:59 -0700568 common.ZipWriteStr(
Tao Baoa80ed222016-06-16 14:41:24 -0700569 output_tf_zip,
Tao Bao13b69622016-07-06 15:28:59 -0700570 "SYSTEM/etc/update_engine/update-payload-key.pub.pem",
571 pubkey)
Alex Deymob3e8ce62016-08-04 16:06:12 -0700572 common.ZipWriteStr(
573 output_tf_zip,
574 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
575 pubkey)
Tao Baoa80ed222016-06-16 14:41:24 -0700576
Doug Zongker412c02f2014-02-13 10:58:24 -0800577 return new_recovery_keys
578
Tao Bao8adcfd12016-06-17 17:01:22 -0700579
Tao Bao0c28d2d2017-12-24 10:37:38 -0800580def ReplaceVerityPublicKey(output_zip, filename, key_path):
581 """Replaces the verity public key at the given path in the given zip.
582
583 Args:
584 output_zip: The output target_files zip.
585 filename: The archive name in the output zip.
586 key_path: The path to the public key.
587 """
588 print("Replacing verity public key with %s" % (key_path,))
589 common.ZipWrite(output_zip, key_path, arcname=filename)
Geremy Condraf19b3652014-07-29 17:54:54 -0700590
Tao Bao8adcfd12016-06-17 17:01:22 -0700591
Tao Bao46a59992017-06-05 11:55:16 -0700592def ReplaceVerityPrivateKey(misc_info, key_path):
Tao Bao0c28d2d2017-12-24 10:37:38 -0800593 """Replaces the verity private key in misc_info dict.
594
595 Args:
596 misc_info: The info dict.
597 key_path: The path to the private key in PKCS#8 format.
598 """
599 print("Replacing verity private key with %s" % (key_path,))
Andrew Boied083f0b2014-09-15 16:01:07 -0700600 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700601
Tao Bao8adcfd12016-06-17 17:01:22 -0700602
Tao Baoe838d142017-12-23 23:44:48 -0800603def ReplaceVerityKeyId(input_zip, output_zip, key_path):
604 """Replaces the veritykeyid parameter in BOOT/cmdline.
605
606 Args:
607 input_zip: The input target_files zip, which should be already open.
608 output_zip: The output target_files zip, which should be already open and
609 writable.
610 key_path: The path to the PEM encoded X.509 certificate.
611 """
612 in_cmdline = input_zip.read("BOOT/cmdline")
613 # Copy in_cmdline to output_zip if veritykeyid is not present.
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700614 if "veritykeyid" not in in_cmdline:
Tao Baoe838d142017-12-23 23:44:48 -0800615 common.ZipWriteStr(output_zip, "BOOT/cmdline", in_cmdline)
616 return
617
Tao Bao0c28d2d2017-12-24 10:37:38 -0800618 out_buffer = []
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700619 for param in in_cmdline.split():
Tao Baoe838d142017-12-23 23:44:48 -0800620 if "veritykeyid" not in param:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800621 out_buffer.append(param)
Tao Baoe838d142017-12-23 23:44:48 -0800622 continue
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700623
Tao Baoe838d142017-12-23 23:44:48 -0800624 # Extract keyid using openssl command.
625 p = common.Run(["openssl", "x509", "-in", key_path, "-text"],
Tao Baode1d4792018-02-20 10:05:46 -0800626 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Tao Baoe838d142017-12-23 23:44:48 -0800627 keyid, stderr = p.communicate()
628 assert p.returncode == 0, "Failed to dump certificate: {}".format(stderr)
629 keyid = re.search(
630 r'keyid:([0-9a-fA-F:]*)', keyid).group(1).replace(':', '').lower()
631 print("Replacing verity keyid with {}".format(keyid))
632 out_buffer.append("veritykeyid=id:%s" % (keyid,))
633
634 out_cmdline = ' '.join(out_buffer).strip() + '\n'
635 common.ZipWriteStr(output_zip, "BOOT/cmdline", out_cmdline)
Tao Bao46a59992017-06-05 11:55:16 -0700636
637
638def ReplaceMiscInfoTxt(input_zip, output_zip, misc_info):
639 """Replaces META/misc_info.txt.
640
641 Only writes back the ones in the original META/misc_info.txt. Because the
642 current in-memory dict contains additional items computed at runtime.
643 """
644 misc_info_old = common.LoadDictionaryFromLines(
645 input_zip.read('META/misc_info.txt').split('\n'))
646 items = []
647 for key in sorted(misc_info):
648 if key in misc_info_old:
649 items.append('%s=%s' % (key, misc_info[key]))
650 common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700651
Tao Bao8adcfd12016-06-17 17:01:22 -0700652
Tao Bao639118f2017-06-19 15:48:02 -0700653def ReplaceAvbSigningKeys(misc_info):
654 """Replaces the AVB signing keys."""
655
656 AVB_FOOTER_ARGS_BY_PARTITION = {
Tao Bao0c28d2d2017-12-24 10:37:38 -0800657 'boot' : 'avb_boot_add_hash_footer_args',
658 'dtbo' : 'avb_dtbo_add_hash_footer_args',
659 'recovery' : 'avb_recovery_add_hash_footer_args',
660 'system' : 'avb_system_add_hashtree_footer_args',
661 'vendor' : 'avb_vendor_add_hashtree_footer_args',
662 'vbmeta' : 'avb_vbmeta_args',
Tao Bao639118f2017-06-19 15:48:02 -0700663 }
664
665 def ReplaceAvbPartitionSigningKey(partition):
666 key = OPTIONS.avb_keys.get(partition)
667 if not key:
668 return
669
670 algorithm = OPTIONS.avb_algorithms.get(partition)
671 assert algorithm, 'Missing AVB signing algorithm for %s' % (partition,)
672
Tao Bao0c28d2d2017-12-24 10:37:38 -0800673 print('Replacing AVB signing key for %s with "%s" (%s)' % (
674 partition, key, algorithm))
Tao Bao639118f2017-06-19 15:48:02 -0700675 misc_info['avb_' + partition + '_algorithm'] = algorithm
676 misc_info['avb_' + partition + '_key_path'] = key
677
678 extra_args = OPTIONS.avb_extra_args.get(partition)
679 if extra_args:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800680 print('Setting extra AVB signing args for %s to "%s"' % (
681 partition, extra_args))
Tao Bao639118f2017-06-19 15:48:02 -0700682 args_key = AVB_FOOTER_ARGS_BY_PARTITION[partition]
683 misc_info[args_key] = (misc_info.get(args_key, '') + ' ' + extra_args)
684
685 for partition in AVB_FOOTER_ARGS_BY_PARTITION:
686 ReplaceAvbPartitionSigningKey(partition)
687
688
Doug Zongker831840e2011-09-22 10:28:04 -0700689def BuildKeyMap(misc_info, key_mapping_options):
690 for s, d in key_mapping_options:
691 if s is None: # -d option
692 devkey = misc_info.get("default_system_dev_certificate",
693 "build/target/product/security/testkey")
694 devkeydir = os.path.dirname(devkey)
695
696 OPTIONS.key_map.update({
697 devkeydir + "/testkey": d + "/releasekey",
698 devkeydir + "/devkey": d + "/releasekey",
699 devkeydir + "/media": d + "/media",
700 devkeydir + "/shared": d + "/shared",
701 devkeydir + "/platform": d + "/platform",
702 })
703 else:
704 OPTIONS.key_map[s] = d
705
706
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800707def GetApiLevelAndCodename(input_tf_zip):
708 data = input_tf_zip.read("SYSTEM/build.prop")
709 api_level = None
710 codename = None
711 for line in data.split("\n"):
712 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800713 if line and line[0] != '#' and "=" in line:
714 key, value = line.split("=", 1)
715 key = key.strip()
716 if key == "ro.build.version.sdk":
717 api_level = int(value.strip())
718 elif key == "ro.build.version.codename":
719 codename = value.strip()
720
721 if api_level is None:
722 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
723 if codename is None:
724 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
725
726 return (api_level, codename)
727
728
729def GetCodenameToApiLevelMap(input_tf_zip):
730 data = input_tf_zip.read("SYSTEM/build.prop")
731 api_level = None
732 codenames = None
733 for line in data.split("\n"):
734 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800735 if line and line[0] != '#' and "=" in line:
736 key, value = line.split("=", 1)
737 key = key.strip()
738 if key == "ro.build.version.sdk":
739 api_level = int(value.strip())
740 elif key == "ro.build.version.all_codenames":
741 codenames = value.strip().split(",")
742
743 if api_level is None:
744 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
745 if codenames is None:
746 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
747
748 result = dict()
749 for codename in codenames:
750 codename = codename.strip()
751 if len(codename) > 0:
752 result[codename] = api_level
753 return result
754
755
Doug Zongkereef39442009-04-02 12:14:19 -0700756def main(argv):
757
Doug Zongker831840e2011-09-22 10:28:04 -0700758 key_mapping_options = []
759
Doug Zongkereef39442009-04-02 12:14:19 -0700760 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700761 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700762 names, key = a.split("=")
763 names = names.split(",")
764 for n in names:
765 OPTIONS.extra_apks[n] = key
766 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700767 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700768 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700769 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700770 elif o in ("-o", "--replace_ota_keys"):
771 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700772 elif o in ("-t", "--tag_changes"):
773 new = []
774 for i in a.split(","):
775 i = i.strip()
776 if not i or i[0] not in "-+":
777 raise ValueError("Bad tag change '%s'" % (i,))
778 new.append(i[0] + i[1:].strip())
779 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700780 elif o == "--replace_verity_public_key":
781 OPTIONS.replace_verity_public_key = (True, a)
782 elif o == "--replace_verity_private_key":
783 OPTIONS.replace_verity_private_key = (True, a)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700784 elif o == "--replace_verity_keyid":
785 OPTIONS.replace_verity_keyid = (True, a)
Tao Bao639118f2017-06-19 15:48:02 -0700786 elif o == "--avb_vbmeta_key":
787 OPTIONS.avb_keys['vbmeta'] = a
788 elif o == "--avb_vbmeta_algorithm":
789 OPTIONS.avb_algorithms['vbmeta'] = a
790 elif o == "--avb_vbmeta_extra_args":
791 OPTIONS.avb_extra_args['vbmeta'] = a
792 elif o == "--avb_boot_key":
793 OPTIONS.avb_keys['boot'] = a
794 elif o == "--avb_boot_algorithm":
795 OPTIONS.avb_algorithms['boot'] = a
796 elif o == "--avb_boot_extra_args":
797 OPTIONS.avb_extra_args['boot'] = a
798 elif o == "--avb_dtbo_key":
799 OPTIONS.avb_keys['dtbo'] = a
800 elif o == "--avb_dtbo_algorithm":
801 OPTIONS.avb_algorithms['dtbo'] = a
802 elif o == "--avb_dtbo_extra_args":
803 OPTIONS.avb_extra_args['dtbo'] = a
804 elif o == "--avb_system_key":
805 OPTIONS.avb_keys['system'] = a
806 elif o == "--avb_system_algorithm":
807 OPTIONS.avb_algorithms['system'] = a
808 elif o == "--avb_system_extra_args":
809 OPTIONS.avb_extra_args['system'] = a
810 elif o == "--avb_vendor_key":
811 OPTIONS.avb_keys['vendor'] = a
812 elif o == "--avb_vendor_algorithm":
813 OPTIONS.avb_algorithms['vendor'] = a
814 elif o == "--avb_vendor_extra_args":
815 OPTIONS.avb_extra_args['vendor'] = a
Doug Zongkereef39442009-04-02 12:14:19 -0700816 else:
817 return False
818 return True
819
Tao Bao639118f2017-06-19 15:48:02 -0700820 args = common.ParseOptions(
821 argv, __doc__,
822 extra_opts="e:d:k:ot:",
823 extra_long_opts=[
Tao Bao0c28d2d2017-12-24 10:37:38 -0800824 "extra_apks=",
825 "default_key_mappings=",
826 "key_mapping=",
827 "replace_ota_keys",
828 "tag_changes=",
829 "replace_verity_public_key=",
830 "replace_verity_private_key=",
831 "replace_verity_keyid=",
832 "avb_vbmeta_algorithm=",
833 "avb_vbmeta_key=",
834 "avb_vbmeta_extra_args=",
835 "avb_boot_algorithm=",
836 "avb_boot_key=",
837 "avb_boot_extra_args=",
838 "avb_dtbo_algorithm=",
839 "avb_dtbo_key=",
840 "avb_dtbo_extra_args=",
841 "avb_system_algorithm=",
842 "avb_system_key=",
843 "avb_system_extra_args=",
844 "avb_vendor_algorithm=",
845 "avb_vendor_key=",
846 "avb_vendor_extra_args=",
Tao Bao639118f2017-06-19 15:48:02 -0700847 ],
848 extra_option_handler=option_handler)
Doug Zongkereef39442009-04-02 12:14:19 -0700849
850 if len(args) != 2:
851 common.Usage(__doc__)
852 sys.exit(1)
853
854 input_zip = zipfile.ZipFile(args[0], "r")
Tao Bao2b8f4892017-06-13 12:54:58 -0700855 output_zip = zipfile.ZipFile(args[1], "w",
856 compression=zipfile.ZIP_DEFLATED,
857 allowZip64=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700858
Doug Zongker831840e2011-09-22 10:28:04 -0700859 misc_info = common.LoadInfoDict(input_zip)
860
861 BuildKeyMap(misc_info, key_mapping_options)
862
Narayan Kamatha07bf042017-08-14 14:49:21 +0100863 certmap, compressed_extension = common.ReadApkCerts(input_zip)
864 apk_key_map = GetApkCerts(certmap)
865 CheckAllApksSigned(input_zip, apk_key_map, compressed_extension)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700866
867 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700868 platform_api_level, _ = GetApiLevelAndCodename(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800869 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800870
Doug Zongker412c02f2014-02-13 10:58:24 -0800871 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800872 apk_key_map, key_passwords,
873 platform_api_level,
Narayan Kamatha07bf042017-08-14 14:49:21 +0100874 codename_to_api_level_map,
875 compressed_extension)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700876
Tao Bao2ed665a2015-04-01 11:21:55 -0700877 common.ZipClose(input_zip)
878 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700879
Tianjie Xub48589a2016-08-03 19:21:52 -0700880 # Skip building userdata.img and cache.img when signing the target files.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700881 new_args = ["--is_signing"]
882 # add_img_to_target_files builds the system image from scratch, so the
883 # recovery patch is guaranteed to be regenerated there.
884 if OPTIONS.rebuild_recovery:
885 new_args.append("--rebuild_recovery")
886 new_args.append(args[1])
Tianjie Xub48589a2016-08-03 19:21:52 -0700887 add_img_to_target_files.main(new_args)
Doug Zongker3c84f562014-07-31 11:06:30 -0700888
Tao Bao0c28d2d2017-12-24 10:37:38 -0800889 print("done.")
Doug Zongkereef39442009-04-02 12:14:19 -0700890
891
892if __name__ == '__main__':
893 try:
894 main(sys.argv[1:])
Tao Bao0c28d2d2017-12-24 10:37:38 -0800895 except common.ExternalError as e:
896 print("\n ERROR: %s\n" % (e,))
Doug Zongkereef39442009-04-02 12:14:19 -0700897 sys.exit(1)
Tao Bao639118f2017-06-19 15:48:02 -0700898 finally:
899 common.Cleanup()