blob: 73d77e7bc56234445338b7db4b1552c0ea11c8ab [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
107
Doug Zongker3c84f562014-07-31 11:06:30 -0700108import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -0700109import common
110
Tao Bao0c28d2d2017-12-24 10:37:38 -0800111
112if sys.hexversion < 0x02070000:
113 print("Python 2.7 or newer is required.", file=sys.stderr)
114 sys.exit(1)
115
116
Doug Zongkereef39442009-04-02 12:14:19 -0700117OPTIONS = common.OPTIONS
118
119OPTIONS.extra_apks = {}
120OPTIONS.key_map = {}
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700121OPTIONS.rebuild_recovery = False
Doug Zongker8e931bf2009-04-06 15:21:45 -0700122OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -0700123OPTIONS.replace_verity_public_key = False
124OPTIONS.replace_verity_private_key = False
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700125OPTIONS.replace_verity_keyid = False
Doug Zongker831840e2011-09-22 10:28:04 -0700126OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Tao Bao639118f2017-06-19 15:48:02 -0700127OPTIONS.avb_keys = {}
128OPTIONS.avb_algorithms = {}
129OPTIONS.avb_extra_args = {}
Doug Zongkereef39442009-04-02 12:14:19 -0700130
Tao Bao0c28d2d2017-12-24 10:37:38 -0800131
Narayan Kamatha07bf042017-08-14 14:49:21 +0100132def GetApkCerts(certmap):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800133 # apply the key remapping to the contents of the file
134 for apk, cert in certmap.iteritems():
135 certmap[apk] = OPTIONS.key_map.get(cert, cert)
136
137 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700138 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800139 if not cert:
140 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700141 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800142
Doug Zongkereef39442009-04-02 12:14:19 -0700143 return certmap
144
145
Narayan Kamatha07bf042017-08-14 14:49:21 +0100146def CheckAllApksSigned(input_tf_zip, apk_key_map, compressed_extension):
Doug Zongkereb338ef2009-05-20 16:50:49 -0700147 """Check that all the APKs we want to sign have keys specified, and
148 error out if they don't."""
149 unknown_apks = []
Narayan Kamatha07bf042017-08-14 14:49:21 +0100150 compressed_apk_extension = None
151 if compressed_extension:
152 compressed_apk_extension = ".apk" + compressed_extension
Doug Zongkereb338ef2009-05-20 16:50:49 -0700153 for info in input_tf_zip.infolist():
Narayan Kamatha07bf042017-08-14 14:49:21 +0100154 if (info.filename.endswith(".apk") or
Tao Bao0c28d2d2017-12-24 10:37:38 -0800155 (compressed_apk_extension and
156 info.filename.endswith(compressed_apk_extension))):
Doug Zongkereb338ef2009-05-20 16:50:49 -0700157 name = os.path.basename(info.filename)
Narayan Kamatha07bf042017-08-14 14:49:21 +0100158 if compressed_apk_extension and name.endswith(compressed_apk_extension):
159 name = name[:-len(compressed_extension)]
Doug Zongkereb338ef2009-05-20 16:50:49 -0700160 if name not in apk_key_map:
161 unknown_apks.append(name)
162 if unknown_apks:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800163 print("ERROR: no key specified for:\n")
164 print(" " + "\n ".join(unknown_apks))
165 print("\nUse '-e <apkname>=' to specify a key (which may be an empty "
166 "string to not sign this apk).")
Doug Zongkereb338ef2009-05-20 16:50:49 -0700167 sys.exit(1)
168
169
Narayan Kamatha07bf042017-08-14 14:49:21 +0100170def SignApk(data, keyname, pw, platform_api_level, codename_to_api_level_map,
171 is_compressed):
Doug Zongkereef39442009-04-02 12:14:19 -0700172 unsigned = tempfile.NamedTemporaryFile()
173 unsigned.write(data)
174 unsigned.flush()
175
Narayan Kamatha07bf042017-08-14 14:49:21 +0100176 if is_compressed:
177 uncompressed = tempfile.NamedTemporaryFile()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800178 with gzip.open(unsigned.name, "rb") as in_file, \
179 open(uncompressed.name, "wb") as out_file:
Narayan Kamatha07bf042017-08-14 14:49:21 +0100180 shutil.copyfileobj(in_file, out_file)
181
182 # Finally, close the "unsigned" file (which is gzip compressed), and then
183 # replace it with the uncompressed version.
184 #
185 # TODO(narayan): All this nastiness can be avoided if python 3.2 is in use,
186 # we could just gzip / gunzip in-memory buffers instead.
187 unsigned.close()
188 unsigned = uncompressed
189
Doug Zongkereef39442009-04-02 12:14:19 -0700190 signed = tempfile.NamedTemporaryFile()
191
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800192 # For pre-N builds, don't upgrade to SHA-256 JAR signatures based on the APK's
193 # minSdkVersion to avoid increasing incremental OTA update sizes. If an APK
194 # didn't change, we don't want its signature to change due to the switch
195 # from SHA-1 to SHA-256.
196 # By default, APK signer chooses SHA-256 signatures if the APK's minSdkVersion
197 # is 18 or higher. For pre-N builds we disable this mechanism by pretending
198 # that the APK's minSdkVersion is 1.
199 # For N+ builds, we let APK signer rely on the APK's minSdkVersion to
200 # determine whether to use SHA-256.
201 min_api_level = None
202 if platform_api_level > 23:
203 # Let APK signer choose whether to use SHA-1 or SHA-256, based on the APK's
204 # minSdkVersion attribute
205 min_api_level = None
206 else:
207 # Force APK signer to use SHA-1
208 min_api_level = 1
209
210 common.SignFile(unsigned.name, signed.name, keyname, pw,
Tao Bao0c28d2d2017-12-24 10:37:38 -0800211 min_api_level=min_api_level,
212 codename_to_api_level_map=codename_to_api_level_map)
Doug Zongkereef39442009-04-02 12:14:19 -0700213
Tao Bao0c28d2d2017-12-24 10:37:38 -0800214 data = None
Narayan Kamatha07bf042017-08-14 14:49:21 +0100215 if is_compressed:
216 # Recompress the file after it has been signed.
217 compressed = tempfile.NamedTemporaryFile()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800218 with open(signed.name, "rb") as in_file, \
219 gzip.open(compressed.name, "wb") as out_file:
Narayan Kamatha07bf042017-08-14 14:49:21 +0100220 shutil.copyfileobj(in_file, out_file)
221
222 data = compressed.read()
223 compressed.close()
224 else:
225 data = signed.read()
226
Doug Zongkereef39442009-04-02 12:14:19 -0700227 unsigned.close()
228 signed.close()
229
230 return data
231
232
Doug Zongker412c02f2014-02-13 10:58:24 -0800233def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800234 apk_key_map, key_passwords, platform_api_level,
Narayan Kamatha07bf042017-08-14 14:49:21 +0100235 codename_to_api_level_map,
236 compressed_extension):
237
238 compressed_apk_extension = None
239 if compressed_extension:
240 compressed_apk_extension = ".apk" + compressed_extension
Michael Rungedc2661a2014-06-03 14:43:11 -0700241
Tao Bao0c28d2d2017-12-24 10:37:38 -0800242 maxsize = max(
243 [len(os.path.basename(i.filename)) for i in input_tf_zip.infolist()
244 if (i.filename.endswith('.apk') or
245 (compressed_apk_extension and
246 i.filename.endswith(compressed_apk_extension)))])
Tao Baoa80ed222016-06-16 14:41:24 -0700247 system_root_image = misc_info.get("system_root_image") == "true"
Doug Zongker412c02f2014-02-13 10:58:24 -0800248
Doug Zongkereef39442009-04-02 12:14:19 -0700249 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700250 if info.filename.startswith("IMAGES/"):
251 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700252
Doug Zongkereef39442009-04-02 12:14:19 -0700253 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700254 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800255
Tao Baof2cffbd2015-07-22 12:33:18 -0700256 # Sign APKs.
Narayan Kamatha07bf042017-08-14 14:49:21 +0100257 if (info.filename.endswith(".apk") or
Tao Bao0c28d2d2017-12-24 10:37:38 -0800258 (compressed_apk_extension and
259 info.filename.endswith(compressed_apk_extension))):
260 is_compressed = (compressed_extension and
261 info.filename.endswith(compressed_apk_extension))
Doug Zongkereef39442009-04-02 12:14:19 -0700262 name = os.path.basename(info.filename)
Narayan Kamatha07bf042017-08-14 14:49:21 +0100263 if is_compressed:
264 name = name[:-len(compressed_extension)]
265
Doug Zongker43874f82009-04-14 14:05:15 -0700266 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800267 if key not in common.SPECIAL_CERT_STRINGS:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800268 print(" signing: %-*s (%s)" % (maxsize, name, key))
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800269 signed_data = SignApk(data, key, key_passwords[key], platform_api_level,
Tao Bao0c28d2d2017-12-24 10:37:38 -0800270 codename_to_api_level_map, is_compressed)
Tao Bao2ed665a2015-04-01 11:21:55 -0700271 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700272 else:
273 # an APK we're not supposed to sign.
Tao Bao0c28d2d2017-12-24 10:37:38 -0800274 print("NOT signing: %s" % (name,))
Tao Bao2ed665a2015-04-01 11:21:55 -0700275 common.ZipWriteStr(output_tf_zip, out_info, data)
Tao Baoa80ed222016-06-16 14:41:24 -0700276
277 # System properties.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700278 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800279 "VENDOR/build.prop",
Hung-ying Tyan7eb6a922017-05-01 21:56:26 +0800280 "SYSTEM/etc/prop.default",
281 "BOOT/RAMDISK/prop.default",
282 "BOOT/RAMDISK/default.prop", # legacy
283 "ROOT/default.prop", # legacy
284 "RECOVERY/RAMDISK/prop.default",
285 "RECOVERY/RAMDISK/default.prop"): # legacy
Tao Bao0c28d2d2017-12-24 10:37:38 -0800286 print("Rewriting %s:" % (info.filename,))
Hung-ying Tyan7eb6a922017-05-01 21:56:26 +0800287 if stat.S_ISLNK(info.external_attr >> 16):
288 new_data = data
289 else:
Tao Baoa7054ee2017-12-08 14:42:16 -0800290 new_data = RewriteProps(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700291 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700292
Robert Craig817c5742013-04-19 10:59:22 -0400293 elif info.filename.endswith("mac_permissions.xml"):
Tao Bao0c28d2d2017-12-24 10:37:38 -0800294 print("Rewriting %s with new keys." % (info.filename,))
Robert Craig817c5742013-04-19 10:59:22 -0400295 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700296 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700297
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700298 # Ask add_img_to_target_files to rebuild the recovery patch if needed.
Doug Zongker412c02f2014-02-13 10:58:24 -0800299 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700300 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800301 "SYSTEM/bin/install-recovery.sh"):
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700302 OPTIONS.rebuild_recovery = True
Tao Baoa80ed222016-06-16 14:41:24 -0700303
304 # Don't copy OTA keys if we're replacing them.
Doug Zongker412c02f2014-02-13 10:58:24 -0800305 elif (OPTIONS.replace_ota_keys and
Tao Baoa80ed222016-06-16 14:41:24 -0700306 info.filename in (
307 "BOOT/RAMDISK/res/keys",
Alex Deymob3e8ce62016-08-04 16:06:12 -0700308 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
Tao Baoa80ed222016-06-16 14:41:24 -0700309 "RECOVERY/RAMDISK/res/keys",
310 "SYSTEM/etc/security/otacerts.zip",
311 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800312 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700313
Tao Bao46a59992017-06-05 11:55:16 -0700314 # Skip META/misc_info.txt since we will write back the new values later.
315 elif info.filename == "META/misc_info.txt":
Geremy Condraf19b3652014-07-29 17:54:54 -0700316 pass
Tao Bao8adcfd12016-06-17 17:01:22 -0700317
318 # Skip verity public key if we will replace it.
Michael Runge947894f2014-10-14 20:58:38 -0700319 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700320 info.filename in ("BOOT/RAMDISK/verity_key",
Tao Bao8adcfd12016-06-17 17:01:22 -0700321 "ROOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700322 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700323
Tao Bao8adcfd12016-06-17 17:01:22 -0700324 # Skip verity keyid (for system_root_image use) if we will replace it.
325 elif (OPTIONS.replace_verity_keyid and
326 info.filename == "BOOT/cmdline"):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700327 pass
328
Tianjie Xu4f099002016-08-11 18:04:27 -0700329 # Skip the care_map as we will regenerate the system/vendor images.
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700330 elif info.filename == "META/care_map.txt":
Tianjie Xu4f099002016-08-11 18:04:27 -0700331 pass
332
Tao Baoa80ed222016-06-16 14:41:24 -0700333 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700334 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700335 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700336
Doug Zongker412c02f2014-02-13 10:58:24 -0800337 if OPTIONS.replace_ota_keys:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700338 ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800339
Tao Bao46a59992017-06-05 11:55:16 -0700340 # Replace the keyid string in misc_info dict.
Tao Bao8adcfd12016-06-17 17:01:22 -0700341 if OPTIONS.replace_verity_private_key:
Tao Bao46a59992017-06-05 11:55:16 -0700342 ReplaceVerityPrivateKey(misc_info, OPTIONS.replace_verity_private_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700343
344 if OPTIONS.replace_verity_public_key:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800345 dest = "ROOT/verity_key" if system_root_image else "BOOT/RAMDISK/verity_key"
Tao Bao8adcfd12016-06-17 17:01:22 -0700346 # We are replacing the one in boot image only, since the one under
347 # recovery won't ever be needed.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700348 ReplaceVerityPublicKey(
Tao Bao8adcfd12016-06-17 17:01:22 -0700349 output_tf_zip, dest, OPTIONS.replace_verity_public_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700350
351 # Replace the keyid string in BOOT/cmdline.
352 if OPTIONS.replace_verity_keyid:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700353 ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
354 OPTIONS.replace_verity_keyid[1])
Doug Zongker412c02f2014-02-13 10:58:24 -0800355
Tao Bao639118f2017-06-19 15:48:02 -0700356 # Replace the AVB signing keys, if any.
357 ReplaceAvbSigningKeys(misc_info)
358
Tao Bao46a59992017-06-05 11:55:16 -0700359 # Write back misc_info with the latest values.
360 ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
361
Doug Zongker8e931bf2009-04-06 15:21:45 -0700362
Robert Craig817c5742013-04-19 10:59:22 -0400363def ReplaceCerts(data):
364 """Given a string of data, replace all occurences of a set
365 of X509 certs with a newer set of X509 certs and return
366 the updated data string."""
367 for old, new in OPTIONS.key_map.iteritems():
368 try:
369 if OPTIONS.verbose:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800370 print(" Replacing %s.x509.pem with %s.x509.pem" % (old, new))
Robert Craig817c5742013-04-19 10:59:22 -0400371 f = open(old + ".x509.pem")
372 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
373 f.close()
374 f = open(new + ".x509.pem")
375 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
376 f.close()
377 # Only match entire certs.
Tao Bao0c28d2d2017-12-24 10:37:38 -0800378 pattern = "\\b" + old_cert16 + "\\b"
Robert Craig817c5742013-04-19 10:59:22 -0400379 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
380 if OPTIONS.verbose:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800381 print(" Replaced %d occurence(s) of %s.x509.pem with "
382 "%s.x509.pem" % (num, old, new))
Dan Albert8b72aef2015-03-23 19:13:21 -0700383 except IOError as e:
384 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400385 continue
386
Tao Bao0c28d2d2017-12-24 10:37:38 -0800387 print(" Error accessing %s. %s. Skip replacing %s.x509.pem with "
388 "%s.x509.pem." % (e.filename, e.strerror, old, new))
Robert Craig817c5742013-04-19 10:59:22 -0400389
390 return data
391
392
Doug Zongkerc09abc82010-01-11 13:09:15 -0800393def EditTags(tags):
Tao Baoa7054ee2017-12-08 14:42:16 -0800394 """Applies the edits to the tag string as specified in OPTIONS.tag_changes.
395
396 Args:
397 tags: The input string that contains comma-separated tags.
398
399 Returns:
400 The updated tags (comma-separated and sorted).
401 """
Doug Zongkerc09abc82010-01-11 13:09:15 -0800402 tags = set(tags.split(","))
403 for ch in OPTIONS.tag_changes:
404 if ch[0] == "-":
405 tags.discard(ch[1:])
406 elif ch[0] == "+":
407 tags.add(ch[1:])
408 return ",".join(sorted(tags))
409
410
Tao Baoa7054ee2017-12-08 14:42:16 -0800411def RewriteProps(data):
412 """Rewrites the system properties in the given string.
413
414 Each property is expected in 'key=value' format. The properties that contain
415 build tags (i.e. test-keys, dev-keys) will be updated accordingly by calling
416 EditTags().
417
418 Args:
419 data: Input string, separated by newlines.
420
421 Returns:
422 The string with modified properties.
423 """
Doug Zongker17aa9442009-04-17 10:15:58 -0700424 output = []
425 for line in data.split("\n"):
426 line = line.strip()
427 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700428 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700429 key, value = line.split("=", 1)
Tao Baoa7054ee2017-12-08 14:42:16 -0800430 if key in ("ro.build.fingerprint", "ro.build.thumbprint",
431 "ro.vendor.build.fingerprint", "ro.vendor.build.thumbprint"):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800432 pieces = value.split("/")
433 pieces[-1] = EditTags(pieces[-1])
434 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700435 elif key == "ro.bootimage.build.fingerprint":
436 pieces = value.split("/")
437 pieces[-1] = EditTags(pieces[-1])
438 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700439 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800440 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700441 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800442 pieces[-1] = EditTags(pieces[-1])
443 value = " ".join(pieces)
444 elif key == "ro.build.tags":
445 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700446 elif key == "ro.build.display.id":
447 # change, eg, "JWR66N dev-keys" to "JWR66N"
448 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700449 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800450 value.pop()
451 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800452 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700453 if line != original_line:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800454 print(" replace: ", original_line)
455 print(" with: ", line)
Doug Zongker17aa9442009-04-17 10:15:58 -0700456 output.append(line)
457 return "\n".join(output) + "\n"
458
459
Doug Zongker831840e2011-09-22 10:28:04 -0700460def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700461 try:
462 keylist = input_tf_zip.read("META/otakeys.txt").split()
463 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700464 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700465
Tao Baof718f902017-11-09 10:10:10 -0800466 extra_recovery_keys = misc_info.get("extra_recovery_keys")
Doug Zongkere121d6a2011-02-01 14:13:52 -0800467 if extra_recovery_keys:
468 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
469 for k in extra_recovery_keys.split()]
470 if extra_recovery_keys:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800471 print("extra recovery-only key(s): " + ", ".join(extra_recovery_keys))
Doug Zongkere121d6a2011-02-01 14:13:52 -0800472 else:
473 extra_recovery_keys = []
474
Doug Zongker8e931bf2009-04-06 15:21:45 -0700475 mapped_keys = []
476 for k in keylist:
477 m = re.match(r"^(.*)\.x509\.pem$", k)
478 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800479 raise common.ExternalError(
480 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700481 k = m.group(1)
482 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
483
Doug Zongkere05628c2009-08-20 17:38:42 -0700484 if mapped_keys:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800485 print("using:\n ", "\n ".join(mapped_keys))
486 print("for OTA package verification")
Doug Zongkere05628c2009-08-20 17:38:42 -0700487 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700488 devkey = misc_info.get("default_system_dev_certificate",
489 "build/target/product/security/testkey")
Tao Baof718f902017-11-09 10:10:10 -0800490 mapped_devkey = OPTIONS.key_map.get(devkey, devkey)
491 if mapped_devkey != devkey:
492 misc_info["default_system_dev_certificate"] = mapped_devkey
493 mapped_keys.append(mapped_devkey + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700494 print("META/otakeys.txt has no keys; using %s for OTA package"
495 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700496
497 # recovery uses a version of the key that has been slightly
498 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800499 # extra_recovery_keys are used only in recovery.
Tao Baoe95540e2016-11-08 12:08:53 -0800500 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
501 ["-jar",
502 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")] +
503 mapped_keys + extra_recovery_keys)
504 p = common.Run(cmd, stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800505 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700506 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700507 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700508
509 # system_root_image puts the recovery keys at BOOT/RAMDISK.
510 if misc_info.get("system_root_image") == "true":
511 recovery_keys_location = "BOOT/RAMDISK/res/keys"
512 else:
513 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
514 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700515
516 # SystemUpdateActivity uses the x509.pem version of the keys, but
517 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800518 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700519
Tao Bao0c28d2d2017-12-24 10:37:38 -0800520 try:
521 from StringIO import StringIO
522 except ImportError:
523 from io import StringIO
524 temp_file = StringIO()
Dan Albert8b72aef2015-03-23 19:13:21 -0700525 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700526 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700527 common.ZipWrite(certs_zip, k)
528 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700529 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700530 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700531
Tao Baoa80ed222016-06-16 14:41:24 -0700532 # For A/B devices, update the payload verification key.
533 if misc_info.get("ab_update") == "true":
534 # Unlike otacerts.zip that may contain multiple keys, we can only specify
535 # ONE payload verification key.
536 if len(mapped_keys) > 1:
537 print("\n WARNING: Found more than one OTA keys; Using the first one"
538 " as payload verification key.\n\n")
539
Tao Bao0c28d2d2017-12-24 10:37:38 -0800540 print("Using %s for payload verification." % (mapped_keys[0],))
Tao Bao13b69622016-07-06 15:28:59 -0700541 cmd = common.Run(
542 ["openssl", "x509", "-pubkey", "-noout", "-in", mapped_keys[0]],
543 stdout=subprocess.PIPE)
544 pubkey, _ = cmd.communicate()
545 common.ZipWriteStr(
Tao Baoa80ed222016-06-16 14:41:24 -0700546 output_tf_zip,
Tao Bao13b69622016-07-06 15:28:59 -0700547 "SYSTEM/etc/update_engine/update-payload-key.pub.pem",
548 pubkey)
Alex Deymob3e8ce62016-08-04 16:06:12 -0700549 common.ZipWriteStr(
550 output_tf_zip,
551 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
552 pubkey)
Tao Baoa80ed222016-06-16 14:41:24 -0700553
Doug Zongker412c02f2014-02-13 10:58:24 -0800554 return new_recovery_keys
555
Tao Bao8adcfd12016-06-17 17:01:22 -0700556
Tao Bao0c28d2d2017-12-24 10:37:38 -0800557def ReplaceVerityPublicKey(output_zip, filename, key_path):
558 """Replaces the verity public key at the given path in the given zip.
559
560 Args:
561 output_zip: The output target_files zip.
562 filename: The archive name in the output zip.
563 key_path: The path to the public key.
564 """
565 print("Replacing verity public key with %s" % (key_path,))
566 common.ZipWrite(output_zip, key_path, arcname=filename)
Geremy Condraf19b3652014-07-29 17:54:54 -0700567
Tao Bao8adcfd12016-06-17 17:01:22 -0700568
Tao Bao46a59992017-06-05 11:55:16 -0700569def ReplaceVerityPrivateKey(misc_info, key_path):
Tao Bao0c28d2d2017-12-24 10:37:38 -0800570 """Replaces the verity private key in misc_info dict.
571
572 Args:
573 misc_info: The info dict.
574 key_path: The path to the private key in PKCS#8 format.
575 """
576 print("Replacing verity private key with %s" % (key_path,))
Andrew Boied083f0b2014-09-15 16:01:07 -0700577 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700578
Tao Bao8adcfd12016-06-17 17:01:22 -0700579
Tao Bao0c28d2d2017-12-24 10:37:38 -0800580def ReplaceVerityKeyId(targetfile_input_zip, targetfile_output_zip, key_path):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700581 in_cmdline = targetfile_input_zip.read("BOOT/cmdline")
582 # copy in_cmdline to output_zip if veritykeyid is not present in in_cmdline
583 if "veritykeyid" not in in_cmdline:
584 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", in_cmdline)
585 return in_cmdline
Tao Bao0c28d2d2017-12-24 10:37:38 -0800586 out_buffer = []
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700587 for param in in_cmdline.split():
588 if "veritykeyid" in param:
589 # extract keyid using openssl command
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700590 p = common.Run(
Tao Bao0c28d2d2017-12-24 10:37:38 -0800591 ["openssl", "x509", "-in", key_path, "-text"],
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700592 stdout=subprocess.PIPE)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700593 keyid, stderr = p.communicate()
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700594 keyid = re.search(
595 r'keyid:([0-9a-fA-F:]*)', keyid).group(1).replace(':', '').lower()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800596 print("Replacing verity keyid with %s error=%s" % (keyid, stderr))
597 out_buffer.append("veritykeyid=id:%s" % (keyid,))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700598 else:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800599 out_buffer.append(param)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700600
Tao Bao0c28d2d2017-12-24 10:37:38 -0800601 out_cmdline = ' '.join(out_buffer)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700602 out_cmdline = out_cmdline.strip()
Tao Bao0c28d2d2017-12-24 10:37:38 -0800603 print("out_cmdline %s" % (out_cmdline))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700604 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", out_cmdline)
Tao Bao46a59992017-06-05 11:55:16 -0700605
606
607def ReplaceMiscInfoTxt(input_zip, output_zip, misc_info):
608 """Replaces META/misc_info.txt.
609
610 Only writes back the ones in the original META/misc_info.txt. Because the
611 current in-memory dict contains additional items computed at runtime.
612 """
613 misc_info_old = common.LoadDictionaryFromLines(
614 input_zip.read('META/misc_info.txt').split('\n'))
615 items = []
616 for key in sorted(misc_info):
617 if key in misc_info_old:
618 items.append('%s=%s' % (key, misc_info[key]))
619 common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700620
Tao Bao8adcfd12016-06-17 17:01:22 -0700621
Tao Bao639118f2017-06-19 15:48:02 -0700622def ReplaceAvbSigningKeys(misc_info):
623 """Replaces the AVB signing keys."""
624
625 AVB_FOOTER_ARGS_BY_PARTITION = {
Tao Bao0c28d2d2017-12-24 10:37:38 -0800626 'boot' : 'avb_boot_add_hash_footer_args',
627 'dtbo' : 'avb_dtbo_add_hash_footer_args',
628 'recovery' : 'avb_recovery_add_hash_footer_args',
629 'system' : 'avb_system_add_hashtree_footer_args',
630 'vendor' : 'avb_vendor_add_hashtree_footer_args',
631 'vbmeta' : 'avb_vbmeta_args',
Tao Bao639118f2017-06-19 15:48:02 -0700632 }
633
634 def ReplaceAvbPartitionSigningKey(partition):
635 key = OPTIONS.avb_keys.get(partition)
636 if not key:
637 return
638
639 algorithm = OPTIONS.avb_algorithms.get(partition)
640 assert algorithm, 'Missing AVB signing algorithm for %s' % (partition,)
641
Tao Bao0c28d2d2017-12-24 10:37:38 -0800642 print('Replacing AVB signing key for %s with "%s" (%s)' % (
643 partition, key, algorithm))
Tao Bao639118f2017-06-19 15:48:02 -0700644 misc_info['avb_' + partition + '_algorithm'] = algorithm
645 misc_info['avb_' + partition + '_key_path'] = key
646
647 extra_args = OPTIONS.avb_extra_args.get(partition)
648 if extra_args:
Tao Bao0c28d2d2017-12-24 10:37:38 -0800649 print('Setting extra AVB signing args for %s to "%s"' % (
650 partition, extra_args))
Tao Bao639118f2017-06-19 15:48:02 -0700651 args_key = AVB_FOOTER_ARGS_BY_PARTITION[partition]
652 misc_info[args_key] = (misc_info.get(args_key, '') + ' ' + extra_args)
653
654 for partition in AVB_FOOTER_ARGS_BY_PARTITION:
655 ReplaceAvbPartitionSigningKey(partition)
656
657
Doug Zongker831840e2011-09-22 10:28:04 -0700658def BuildKeyMap(misc_info, key_mapping_options):
659 for s, d in key_mapping_options:
660 if s is None: # -d option
661 devkey = misc_info.get("default_system_dev_certificate",
662 "build/target/product/security/testkey")
663 devkeydir = os.path.dirname(devkey)
664
665 OPTIONS.key_map.update({
666 devkeydir + "/testkey": d + "/releasekey",
667 devkeydir + "/devkey": d + "/releasekey",
668 devkeydir + "/media": d + "/media",
669 devkeydir + "/shared": d + "/shared",
670 devkeydir + "/platform": d + "/platform",
671 })
672 else:
673 OPTIONS.key_map[s] = d
674
675
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800676def GetApiLevelAndCodename(input_tf_zip):
677 data = input_tf_zip.read("SYSTEM/build.prop")
678 api_level = None
679 codename = None
680 for line in data.split("\n"):
681 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800682 if line and line[0] != '#' and "=" in line:
683 key, value = line.split("=", 1)
684 key = key.strip()
685 if key == "ro.build.version.sdk":
686 api_level = int(value.strip())
687 elif key == "ro.build.version.codename":
688 codename = value.strip()
689
690 if api_level is None:
691 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
692 if codename is None:
693 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
694
695 return (api_level, codename)
696
697
698def GetCodenameToApiLevelMap(input_tf_zip):
699 data = input_tf_zip.read("SYSTEM/build.prop")
700 api_level = None
701 codenames = None
702 for line in data.split("\n"):
703 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800704 if line and line[0] != '#' and "=" in line:
705 key, value = line.split("=", 1)
706 key = key.strip()
707 if key == "ro.build.version.sdk":
708 api_level = int(value.strip())
709 elif key == "ro.build.version.all_codenames":
710 codenames = value.strip().split(",")
711
712 if api_level is None:
713 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
714 if codenames is None:
715 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
716
717 result = dict()
718 for codename in codenames:
719 codename = codename.strip()
720 if len(codename) > 0:
721 result[codename] = api_level
722 return result
723
724
Doug Zongkereef39442009-04-02 12:14:19 -0700725def main(argv):
726
Doug Zongker831840e2011-09-22 10:28:04 -0700727 key_mapping_options = []
728
Doug Zongkereef39442009-04-02 12:14:19 -0700729 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700730 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700731 names, key = a.split("=")
732 names = names.split(",")
733 for n in names:
734 OPTIONS.extra_apks[n] = key
735 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700736 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700737 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700738 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700739 elif o in ("-o", "--replace_ota_keys"):
740 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700741 elif o in ("-t", "--tag_changes"):
742 new = []
743 for i in a.split(","):
744 i = i.strip()
745 if not i or i[0] not in "-+":
746 raise ValueError("Bad tag change '%s'" % (i,))
747 new.append(i[0] + i[1:].strip())
748 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700749 elif o == "--replace_verity_public_key":
750 OPTIONS.replace_verity_public_key = (True, a)
751 elif o == "--replace_verity_private_key":
752 OPTIONS.replace_verity_private_key = (True, a)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700753 elif o == "--replace_verity_keyid":
754 OPTIONS.replace_verity_keyid = (True, a)
Tao Bao639118f2017-06-19 15:48:02 -0700755 elif o == "--avb_vbmeta_key":
756 OPTIONS.avb_keys['vbmeta'] = a
757 elif o == "--avb_vbmeta_algorithm":
758 OPTIONS.avb_algorithms['vbmeta'] = a
759 elif o == "--avb_vbmeta_extra_args":
760 OPTIONS.avb_extra_args['vbmeta'] = a
761 elif o == "--avb_boot_key":
762 OPTIONS.avb_keys['boot'] = a
763 elif o == "--avb_boot_algorithm":
764 OPTIONS.avb_algorithms['boot'] = a
765 elif o == "--avb_boot_extra_args":
766 OPTIONS.avb_extra_args['boot'] = a
767 elif o == "--avb_dtbo_key":
768 OPTIONS.avb_keys['dtbo'] = a
769 elif o == "--avb_dtbo_algorithm":
770 OPTIONS.avb_algorithms['dtbo'] = a
771 elif o == "--avb_dtbo_extra_args":
772 OPTIONS.avb_extra_args['dtbo'] = a
773 elif o == "--avb_system_key":
774 OPTIONS.avb_keys['system'] = a
775 elif o == "--avb_system_algorithm":
776 OPTIONS.avb_algorithms['system'] = a
777 elif o == "--avb_system_extra_args":
778 OPTIONS.avb_extra_args['system'] = a
779 elif o == "--avb_vendor_key":
780 OPTIONS.avb_keys['vendor'] = a
781 elif o == "--avb_vendor_algorithm":
782 OPTIONS.avb_algorithms['vendor'] = a
783 elif o == "--avb_vendor_extra_args":
784 OPTIONS.avb_extra_args['vendor'] = a
Doug Zongkereef39442009-04-02 12:14:19 -0700785 else:
786 return False
787 return True
788
Tao Bao639118f2017-06-19 15:48:02 -0700789 args = common.ParseOptions(
790 argv, __doc__,
791 extra_opts="e:d:k:ot:",
792 extra_long_opts=[
Tao Bao0c28d2d2017-12-24 10:37:38 -0800793 "extra_apks=",
794 "default_key_mappings=",
795 "key_mapping=",
796 "replace_ota_keys",
797 "tag_changes=",
798 "replace_verity_public_key=",
799 "replace_verity_private_key=",
800 "replace_verity_keyid=",
801 "avb_vbmeta_algorithm=",
802 "avb_vbmeta_key=",
803 "avb_vbmeta_extra_args=",
804 "avb_boot_algorithm=",
805 "avb_boot_key=",
806 "avb_boot_extra_args=",
807 "avb_dtbo_algorithm=",
808 "avb_dtbo_key=",
809 "avb_dtbo_extra_args=",
810 "avb_system_algorithm=",
811 "avb_system_key=",
812 "avb_system_extra_args=",
813 "avb_vendor_algorithm=",
814 "avb_vendor_key=",
815 "avb_vendor_extra_args=",
Tao Bao639118f2017-06-19 15:48:02 -0700816 ],
817 extra_option_handler=option_handler)
Doug Zongkereef39442009-04-02 12:14:19 -0700818
819 if len(args) != 2:
820 common.Usage(__doc__)
821 sys.exit(1)
822
823 input_zip = zipfile.ZipFile(args[0], "r")
Tao Bao2b8f4892017-06-13 12:54:58 -0700824 output_zip = zipfile.ZipFile(args[1], "w",
825 compression=zipfile.ZIP_DEFLATED,
826 allowZip64=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700827
Doug Zongker831840e2011-09-22 10:28:04 -0700828 misc_info = common.LoadInfoDict(input_zip)
829
830 BuildKeyMap(misc_info, key_mapping_options)
831
Narayan Kamatha07bf042017-08-14 14:49:21 +0100832 certmap, compressed_extension = common.ReadApkCerts(input_zip)
833 apk_key_map = GetApkCerts(certmap)
834 CheckAllApksSigned(input_zip, apk_key_map, compressed_extension)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700835
836 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700837 platform_api_level, _ = GetApiLevelAndCodename(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800838 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800839
Doug Zongker412c02f2014-02-13 10:58:24 -0800840 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800841 apk_key_map, key_passwords,
842 platform_api_level,
Narayan Kamatha07bf042017-08-14 14:49:21 +0100843 codename_to_api_level_map,
844 compressed_extension)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700845
Tao Bao2ed665a2015-04-01 11:21:55 -0700846 common.ZipClose(input_zip)
847 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700848
Tianjie Xub48589a2016-08-03 19:21:52 -0700849 # Skip building userdata.img and cache.img when signing the target files.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700850 new_args = ["--is_signing"]
851 # add_img_to_target_files builds the system image from scratch, so the
852 # recovery patch is guaranteed to be regenerated there.
853 if OPTIONS.rebuild_recovery:
854 new_args.append("--rebuild_recovery")
855 new_args.append(args[1])
Tianjie Xub48589a2016-08-03 19:21:52 -0700856 add_img_to_target_files.main(new_args)
Doug Zongker3c84f562014-07-31 11:06:30 -0700857
Tao Bao0c28d2d2017-12-24 10:37:38 -0800858 print("done.")
Doug Zongkereef39442009-04-02 12:14:19 -0700859
860
861if __name__ == '__main__':
862 try:
863 main(sys.argv[1:])
Tao Bao0c28d2d2017-12-24 10:37:38 -0800864 except common.ExternalError as e:
865 print("\n ERROR: %s\n" % (e,))
Doug Zongkereef39442009-04-02 12:14:19 -0700866 sys.exit(1)
Tao Bao639118f2017-06-19 15:48:02 -0700867 finally:
868 common.Cleanup()