blob: a76c9c992e241d5fd2a3ad1761067d658443b243 [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
93import sys
94
Doug Zongkercf6d5a92014-02-18 10:57:07 -080095if sys.hexversion < 0x02070000:
96 print >> sys.stderr, "Python 2.7 or newer is required."
Doug Zongkereef39442009-04-02 12:14:19 -070097 sys.exit(1)
98
Robert Craig817c5742013-04-19 10:59:22 -040099import base64
Doug Zongker8e931bf2009-04-06 15:21:45 -0700100import cStringIO
101import copy
Robert Craig817c5742013-04-19 10:59:22 -0400102import errno
Doug Zongkereef39442009-04-02 12:14:19 -0700103import os
104import re
105import subprocess
106import tempfile
107import zipfile
108
Doug Zongker3c84f562014-07-31 11:06:30 -0700109import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -0700110import common
111
112OPTIONS = common.OPTIONS
113
114OPTIONS.extra_apks = {}
115OPTIONS.key_map = {}
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700116OPTIONS.rebuild_recovery = False
Doug Zongker8e931bf2009-04-06 15:21:45 -0700117OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -0700118OPTIONS.replace_verity_public_key = False
119OPTIONS.replace_verity_private_key = False
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700120OPTIONS.replace_verity_keyid = False
Doug Zongker831840e2011-09-22 10:28:04 -0700121OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Tao Bao639118f2017-06-19 15:48:02 -0700122OPTIONS.avb_keys = {}
123OPTIONS.avb_algorithms = {}
124OPTIONS.avb_extra_args = {}
Doug Zongkereef39442009-04-02 12:14:19 -0700125
126def GetApkCerts(tf_zip):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800127 certmap = common.ReadApkCerts(tf_zip)
128
129 # apply the key remapping to the contents of the file
130 for apk, cert in certmap.iteritems():
131 certmap[apk] = OPTIONS.key_map.get(cert, cert)
132
133 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700134 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800135 if not cert:
136 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700137 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800138
Doug Zongkereef39442009-04-02 12:14:19 -0700139 return certmap
140
141
Doug Zongkereb338ef2009-05-20 16:50:49 -0700142def CheckAllApksSigned(input_tf_zip, apk_key_map):
143 """Check that all the APKs we want to sign have keys specified, and
144 error out if they don't."""
145 unknown_apks = []
146 for info in input_tf_zip.infolist():
147 if info.filename.endswith(".apk"):
148 name = os.path.basename(info.filename)
149 if name not in apk_key_map:
150 unknown_apks.append(name)
151 if unknown_apks:
152 print "ERROR: no key specified for:\n\n ",
153 print "\n ".join(unknown_apks)
154 print "\nUse '-e <apkname>=' to specify a key (which may be an"
155 print "empty string to not sign this apk)."
156 sys.exit(1)
157
158
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800159def SignApk(data, keyname, pw, platform_api_level, codename_to_api_level_map):
Doug Zongkereef39442009-04-02 12:14:19 -0700160 unsigned = tempfile.NamedTemporaryFile()
161 unsigned.write(data)
162 unsigned.flush()
163
164 signed = tempfile.NamedTemporaryFile()
165
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800166 # For pre-N builds, don't upgrade to SHA-256 JAR signatures based on the APK's
167 # minSdkVersion to avoid increasing incremental OTA update sizes. If an APK
168 # didn't change, we don't want its signature to change due to the switch
169 # from SHA-1 to SHA-256.
170 # By default, APK signer chooses SHA-256 signatures if the APK's minSdkVersion
171 # is 18 or higher. For pre-N builds we disable this mechanism by pretending
172 # that the APK's minSdkVersion is 1.
173 # For N+ builds, we let APK signer rely on the APK's minSdkVersion to
174 # determine whether to use SHA-256.
175 min_api_level = None
176 if platform_api_level > 23:
177 # Let APK signer choose whether to use SHA-1 or SHA-256, based on the APK's
178 # minSdkVersion attribute
179 min_api_level = None
180 else:
181 # Force APK signer to use SHA-1
182 min_api_level = 1
183
184 common.SignFile(unsigned.name, signed.name, keyname, pw,
185 min_api_level=min_api_level,
186 codename_to_api_level_map=codename_to_api_level_map)
Doug Zongkereef39442009-04-02 12:14:19 -0700187
188 data = signed.read()
189 unsigned.close()
190 signed.close()
191
192 return data
193
194
Doug Zongker412c02f2014-02-13 10:58:24 -0800195def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800196 apk_key_map, key_passwords, platform_api_level,
197 codename_to_api_level_map):
Michael Rungedc2661a2014-06-03 14:43:11 -0700198
Doug Zongkereef39442009-04-02 12:14:19 -0700199 maxsize = max([len(os.path.basename(i.filename))
200 for i in input_tf_zip.infolist()
201 if i.filename.endswith('.apk')])
Tao Baoa80ed222016-06-16 14:41:24 -0700202 system_root_image = misc_info.get("system_root_image") == "true"
Doug Zongker412c02f2014-02-13 10:58:24 -0800203
Doug Zongkereef39442009-04-02 12:14:19 -0700204 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700205 if info.filename.startswith("IMAGES/"):
206 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700207
Doug Zongkereef39442009-04-02 12:14:19 -0700208 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700209 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800210
Tao Baof2cffbd2015-07-22 12:33:18 -0700211 # Sign APKs.
Doug Zongkereef39442009-04-02 12:14:19 -0700212 if info.filename.endswith(".apk"):
213 name = os.path.basename(info.filename)
Doug Zongker43874f82009-04-14 14:05:15 -0700214 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800215 if key not in common.SPECIAL_CERT_STRINGS:
Doug Zongker43874f82009-04-14 14:05:15 -0700216 print " signing: %-*s (%s)" % (maxsize, name, key)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800217 signed_data = SignApk(data, key, key_passwords[key], platform_api_level,
218 codename_to_api_level_map)
Tao Bao2ed665a2015-04-01 11:21:55 -0700219 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700220 else:
221 # an APK we're not supposed to sign.
Doug Zongker43874f82009-04-14 14:05:15 -0700222 print "NOT signing: %s" % (name,)
Tao Bao2ed665a2015-04-01 11:21:55 -0700223 common.ZipWriteStr(output_tf_zip, out_info, data)
Tao Baoa80ed222016-06-16 14:41:24 -0700224
225 # System properties.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700226 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800227 "VENDOR/build.prop",
Tao Baocb7ff772015-09-11 15:27:56 -0700228 "BOOT/RAMDISK/default.prop",
Tao Bao28e2fa12016-08-11 11:00:58 -0700229 "ROOT/default.prop",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700230 "RECOVERY/RAMDISK/default.prop"):
Doug Zongker17aa9442009-04-17 10:15:58 -0700231 print "rewriting %s:" % (info.filename,)
Michael Rungedc2661a2014-06-03 14:43:11 -0700232 new_data = RewriteProps(data, misc_info)
Tao Bao2ed665a2015-04-01 11:21:55 -0700233 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700234
Robert Craig817c5742013-04-19 10:59:22 -0400235 elif info.filename.endswith("mac_permissions.xml"):
236 print "rewriting %s with new keys." % (info.filename,)
237 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700238 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700239
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700240 # Ask add_img_to_target_files to rebuild the recovery patch if needed.
Doug Zongker412c02f2014-02-13 10:58:24 -0800241 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700242 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800243 "SYSTEM/bin/install-recovery.sh"):
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700244 OPTIONS.rebuild_recovery = True
Tao Baoa80ed222016-06-16 14:41:24 -0700245
246 # Don't copy OTA keys if we're replacing them.
Doug Zongker412c02f2014-02-13 10:58:24 -0800247 elif (OPTIONS.replace_ota_keys and
Tao Baoa80ed222016-06-16 14:41:24 -0700248 info.filename in (
249 "BOOT/RAMDISK/res/keys",
Alex Deymob3e8ce62016-08-04 16:06:12 -0700250 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
Tao Baoa80ed222016-06-16 14:41:24 -0700251 "RECOVERY/RAMDISK/res/keys",
252 "SYSTEM/etc/security/otacerts.zip",
253 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800254 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700255
Tao Bao46a59992017-06-05 11:55:16 -0700256 # Skip META/misc_info.txt since we will write back the new values later.
257 elif info.filename == "META/misc_info.txt":
Geremy Condraf19b3652014-07-29 17:54:54 -0700258 pass
Tao Bao8adcfd12016-06-17 17:01:22 -0700259
260 # Skip verity public key if we will replace it.
Michael Runge947894f2014-10-14 20:58:38 -0700261 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700262 info.filename in ("BOOT/RAMDISK/verity_key",
Tao Bao8adcfd12016-06-17 17:01:22 -0700263 "ROOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700264 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700265
Tao Bao8adcfd12016-06-17 17:01:22 -0700266 # Skip verity keyid (for system_root_image use) if we will replace it.
267 elif (OPTIONS.replace_verity_keyid and
268 info.filename == "BOOT/cmdline"):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700269 pass
270
Tianjie Xu4f099002016-08-11 18:04:27 -0700271 # Skip the care_map as we will regenerate the system/vendor images.
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700272 elif info.filename == "META/care_map.txt":
Tianjie Xu4f099002016-08-11 18:04:27 -0700273 pass
274
Tao Baoa80ed222016-06-16 14:41:24 -0700275 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700276 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700277 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700278
Doug Zongker412c02f2014-02-13 10:58:24 -0800279 if OPTIONS.replace_ota_keys:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700280 ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800281
Tao Bao46a59992017-06-05 11:55:16 -0700282 # Replace the keyid string in misc_info dict.
Tao Bao8adcfd12016-06-17 17:01:22 -0700283 if OPTIONS.replace_verity_private_key:
Tao Bao46a59992017-06-05 11:55:16 -0700284 ReplaceVerityPrivateKey(misc_info, OPTIONS.replace_verity_private_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700285
286 if OPTIONS.replace_verity_public_key:
287 if system_root_image:
288 dest = "ROOT/verity_key"
289 else:
290 dest = "BOOT/RAMDISK/verity_key"
291 # We are replacing the one in boot image only, since the one under
292 # recovery won't ever be needed.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700293 ReplaceVerityPublicKey(
Tao Bao8adcfd12016-06-17 17:01:22 -0700294 output_tf_zip, dest, OPTIONS.replace_verity_public_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700295
296 # Replace the keyid string in BOOT/cmdline.
297 if OPTIONS.replace_verity_keyid:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700298 ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
299 OPTIONS.replace_verity_keyid[1])
Doug Zongker412c02f2014-02-13 10:58:24 -0800300
Tao Bao639118f2017-06-19 15:48:02 -0700301 # Replace the AVB signing keys, if any.
302 ReplaceAvbSigningKeys(misc_info)
303
Tao Bao46a59992017-06-05 11:55:16 -0700304 # Write back misc_info with the latest values.
305 ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
306
Doug Zongker8e931bf2009-04-06 15:21:45 -0700307
Robert Craig817c5742013-04-19 10:59:22 -0400308def ReplaceCerts(data):
309 """Given a string of data, replace all occurences of a set
310 of X509 certs with a newer set of X509 certs and return
311 the updated data string."""
312 for old, new in OPTIONS.key_map.iteritems():
313 try:
314 if OPTIONS.verbose:
315 print " Replacing %s.x509.pem with %s.x509.pem" % (old, new)
316 f = open(old + ".x509.pem")
317 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
318 f.close()
319 f = open(new + ".x509.pem")
320 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
321 f.close()
322 # Only match entire certs.
323 pattern = "\\b"+old_cert16+"\\b"
324 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
325 if OPTIONS.verbose:
326 print " Replaced %d occurence(s) of %s.x509.pem with " \
327 "%s.x509.pem" % (num, old, new)
Dan Albert8b72aef2015-03-23 19:13:21 -0700328 except IOError as e:
329 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400330 continue
331
332 print " Error accessing %s. %s. Skip replacing %s.x509.pem " \
333 "with %s.x509.pem." % (e.filename, e.strerror, old, new)
334
335 return data
336
337
Doug Zongkerc09abc82010-01-11 13:09:15 -0800338def EditTags(tags):
339 """Given a string containing comma-separated tags, apply the edits
340 specified in OPTIONS.tag_changes and return the updated string."""
341 tags = set(tags.split(","))
342 for ch in OPTIONS.tag_changes:
343 if ch[0] == "-":
344 tags.discard(ch[1:])
345 elif ch[0] == "+":
346 tags.add(ch[1:])
347 return ",".join(sorted(tags))
348
349
Michael Rungedc2661a2014-06-03 14:43:11 -0700350def RewriteProps(data, misc_info):
Doug Zongker17aa9442009-04-17 10:15:58 -0700351 output = []
352 for line in data.split("\n"):
353 line = line.strip()
354 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700355 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700356 key, value = line.split("=", 1)
Michael Rungee07c75a2014-12-09 13:54:23 -0800357 if (key in ("ro.build.fingerprint", "ro.vendor.build.fingerprint")
Michael Rungedc2661a2014-06-03 14:43:11 -0700358 and misc_info.get("oem_fingerprint_properties") is None):
359 pieces = value.split("/")
360 pieces[-1] = EditTags(pieces[-1])
361 value = "/".join(pieces)
Michael Rungee07c75a2014-12-09 13:54:23 -0800362 elif (key in ("ro.build.thumbprint", "ro.vendor.build.thumbprint")
Dan Albert8b72aef2015-03-23 19:13:21 -0700363 and misc_info.get("oem_fingerprint_properties") is not None):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800364 pieces = value.split("/")
365 pieces[-1] = EditTags(pieces[-1])
366 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700367 elif key == "ro.bootimage.build.fingerprint":
368 pieces = value.split("/")
369 pieces[-1] = EditTags(pieces[-1])
370 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700371 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800372 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700373 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800374 pieces[-1] = EditTags(pieces[-1])
375 value = " ".join(pieces)
376 elif key == "ro.build.tags":
377 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700378 elif key == "ro.build.display.id":
379 # change, eg, "JWR66N dev-keys" to "JWR66N"
380 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700381 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800382 value.pop()
383 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800384 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700385 if line != original_line:
386 print " replace: ", original_line
387 print " with: ", line
388 output.append(line)
389 return "\n".join(output) + "\n"
390
391
Doug Zongker831840e2011-09-22 10:28:04 -0700392def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700393 try:
394 keylist = input_tf_zip.read("META/otakeys.txt").split()
395 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700396 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700397
Doug Zongkere121d6a2011-02-01 14:13:52 -0800398 extra_recovery_keys = misc_info.get("extra_recovery_keys", None)
399 if extra_recovery_keys:
400 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
401 for k in extra_recovery_keys.split()]
402 if extra_recovery_keys:
403 print "extra recovery-only key(s): " + ", ".join(extra_recovery_keys)
404 else:
405 extra_recovery_keys = []
406
Doug Zongker8e931bf2009-04-06 15:21:45 -0700407 mapped_keys = []
408 for k in keylist:
409 m = re.match(r"^(.*)\.x509\.pem$", k)
410 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800411 raise common.ExternalError(
412 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700413 k = m.group(1)
414 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
415
Doug Zongkere05628c2009-08-20 17:38:42 -0700416 if mapped_keys:
417 print "using:\n ", "\n ".join(mapped_keys)
418 print "for OTA package verification"
419 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700420 devkey = misc_info.get("default_system_dev_certificate",
421 "build/target/product/security/testkey")
Doug Zongkere05628c2009-08-20 17:38:42 -0700422 mapped_keys.append(
Doug Zongker831840e2011-09-22 10:28:04 -0700423 OPTIONS.key_map.get(devkey, devkey) + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700424 print("META/otakeys.txt has no keys; using %s for OTA package"
425 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700426
427 # recovery uses a version of the key that has been slightly
428 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800429 # extra_recovery_keys are used only in recovery.
Tao Baoe95540e2016-11-08 12:08:53 -0800430 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
431 ["-jar",
432 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")] +
433 mapped_keys + extra_recovery_keys)
434 p = common.Run(cmd, stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800435 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700436 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700437 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700438
439 # system_root_image puts the recovery keys at BOOT/RAMDISK.
440 if misc_info.get("system_root_image") == "true":
441 recovery_keys_location = "BOOT/RAMDISK/res/keys"
442 else:
443 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
444 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700445
446 # SystemUpdateActivity uses the x509.pem version of the keys, but
447 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800448 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700449
Dan Albert8b72aef2015-03-23 19:13:21 -0700450 temp_file = cStringIO.StringIO()
451 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700452 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700453 common.ZipWrite(certs_zip, k)
454 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700455 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700456 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700457
Tao Baoa80ed222016-06-16 14:41:24 -0700458 # For A/B devices, update the payload verification key.
459 if misc_info.get("ab_update") == "true":
460 # Unlike otacerts.zip that may contain multiple keys, we can only specify
461 # ONE payload verification key.
462 if len(mapped_keys) > 1:
463 print("\n WARNING: Found more than one OTA keys; Using the first one"
464 " as payload verification key.\n\n")
465
466 print "Using %s for payload verification." % (mapped_keys[0],)
Tao Bao13b69622016-07-06 15:28:59 -0700467 cmd = common.Run(
468 ["openssl", "x509", "-pubkey", "-noout", "-in", mapped_keys[0]],
469 stdout=subprocess.PIPE)
470 pubkey, _ = cmd.communicate()
471 common.ZipWriteStr(
Tao Baoa80ed222016-06-16 14:41:24 -0700472 output_tf_zip,
Tao Bao13b69622016-07-06 15:28:59 -0700473 "SYSTEM/etc/update_engine/update-payload-key.pub.pem",
474 pubkey)
Alex Deymob3e8ce62016-08-04 16:06:12 -0700475 common.ZipWriteStr(
476 output_tf_zip,
477 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
478 pubkey)
Tao Baoa80ed222016-06-16 14:41:24 -0700479
Doug Zongker412c02f2014-02-13 10:58:24 -0800480 return new_recovery_keys
481
Tao Bao8adcfd12016-06-17 17:01:22 -0700482
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700483def ReplaceVerityPublicKey(targetfile_zip, filename, key_path):
Tao Bao46a59992017-06-05 11:55:16 -0700484 print "Replacing verity public key with %s" % (key_path,)
485 common.ZipWrite(targetfile_zip, key_path, arcname=filename)
Geremy Condraf19b3652014-07-29 17:54:54 -0700486
Tao Bao8adcfd12016-06-17 17:01:22 -0700487
Tao Bao46a59992017-06-05 11:55:16 -0700488def ReplaceVerityPrivateKey(misc_info, key_path):
489 print "Replacing verity private key with %s" % (key_path,)
Andrew Boied083f0b2014-09-15 16:01:07 -0700490 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700491
Tao Bao8adcfd12016-06-17 17:01:22 -0700492
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700493def ReplaceVerityKeyId(targetfile_input_zip, targetfile_output_zip, keypath):
494 in_cmdline = targetfile_input_zip.read("BOOT/cmdline")
495 # copy in_cmdline to output_zip if veritykeyid is not present in in_cmdline
496 if "veritykeyid" not in in_cmdline:
497 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", in_cmdline)
498 return in_cmdline
499 out_cmdline = []
500 for param in in_cmdline.split():
501 if "veritykeyid" in param:
502 # extract keyid using openssl command
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700503 p = common.Run(
504 ["openssl", "x509", "-in", keypath, "-text"],
505 stdout=subprocess.PIPE)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700506 keyid, stderr = p.communicate()
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700507 keyid = re.search(
508 r'keyid:([0-9a-fA-F:]*)', keyid).group(1).replace(':', '').lower()
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700509 print "Replacing verity keyid with %s error=%s" % (keyid, stderr)
510 out_cmdline.append("veritykeyid=id:%s" % (keyid,))
511 else:
512 out_cmdline.append(param)
513
514 out_cmdline = ' '.join(out_cmdline)
515 out_cmdline = out_cmdline.strip()
516 print "out_cmdline %s" % (out_cmdline)
517 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", out_cmdline)
Tao Bao46a59992017-06-05 11:55:16 -0700518
519
520def ReplaceMiscInfoTxt(input_zip, output_zip, misc_info):
521 """Replaces META/misc_info.txt.
522
523 Only writes back the ones in the original META/misc_info.txt. Because the
524 current in-memory dict contains additional items computed at runtime.
525 """
526 misc_info_old = common.LoadDictionaryFromLines(
527 input_zip.read('META/misc_info.txt').split('\n'))
528 items = []
529 for key in sorted(misc_info):
530 if key in misc_info_old:
531 items.append('%s=%s' % (key, misc_info[key]))
532 common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700533
Tao Bao8adcfd12016-06-17 17:01:22 -0700534
Tao Bao639118f2017-06-19 15:48:02 -0700535def ReplaceAvbSigningKeys(misc_info):
536 """Replaces the AVB signing keys."""
537
538 AVB_FOOTER_ARGS_BY_PARTITION = {
539 'boot' : 'avb_boot_add_hash_footer_args',
540 'dtbo' : 'avb_dtbo_add_hash_footer_args',
541 'system' : 'avb_system_add_hashtree_footer_args',
542 'vendor' : 'avb_vendor_add_hashtree_footer_args',
543 'vbmeta' : 'avb_vbmeta_args',
544 }
545
546 def ReplaceAvbPartitionSigningKey(partition):
547 key = OPTIONS.avb_keys.get(partition)
548 if not key:
549 return
550
551 algorithm = OPTIONS.avb_algorithms.get(partition)
552 assert algorithm, 'Missing AVB signing algorithm for %s' % (partition,)
553
554 print 'Replacing AVB signing key for %s with "%s" (%s)' % (
555 partition, key, algorithm)
556 misc_info['avb_' + partition + '_algorithm'] = algorithm
557 misc_info['avb_' + partition + '_key_path'] = key
558
559 extra_args = OPTIONS.avb_extra_args.get(partition)
560 if extra_args:
561 print 'Setting extra AVB signing args for %s to "%s"' % (
562 partition, extra_args)
563 args_key = AVB_FOOTER_ARGS_BY_PARTITION[partition]
564 misc_info[args_key] = (misc_info.get(args_key, '') + ' ' + extra_args)
565
566 for partition in AVB_FOOTER_ARGS_BY_PARTITION:
567 ReplaceAvbPartitionSigningKey(partition)
568
569
Doug Zongker831840e2011-09-22 10:28:04 -0700570def BuildKeyMap(misc_info, key_mapping_options):
571 for s, d in key_mapping_options:
572 if s is None: # -d option
573 devkey = misc_info.get("default_system_dev_certificate",
574 "build/target/product/security/testkey")
575 devkeydir = os.path.dirname(devkey)
576
577 OPTIONS.key_map.update({
578 devkeydir + "/testkey": d + "/releasekey",
579 devkeydir + "/devkey": d + "/releasekey",
580 devkeydir + "/media": d + "/media",
581 devkeydir + "/shared": d + "/shared",
582 devkeydir + "/platform": d + "/platform",
583 })
584 else:
585 OPTIONS.key_map[s] = d
586
587
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800588def GetApiLevelAndCodename(input_tf_zip):
589 data = input_tf_zip.read("SYSTEM/build.prop")
590 api_level = None
591 codename = None
592 for line in data.split("\n"):
593 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800594 if line and line[0] != '#' and "=" in line:
595 key, value = line.split("=", 1)
596 key = key.strip()
597 if key == "ro.build.version.sdk":
598 api_level = int(value.strip())
599 elif key == "ro.build.version.codename":
600 codename = value.strip()
601
602 if api_level is None:
603 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
604 if codename is None:
605 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
606
607 return (api_level, codename)
608
609
610def GetCodenameToApiLevelMap(input_tf_zip):
611 data = input_tf_zip.read("SYSTEM/build.prop")
612 api_level = None
613 codenames = None
614 for line in data.split("\n"):
615 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800616 if line and line[0] != '#' and "=" in line:
617 key, value = line.split("=", 1)
618 key = key.strip()
619 if key == "ro.build.version.sdk":
620 api_level = int(value.strip())
621 elif key == "ro.build.version.all_codenames":
622 codenames = value.strip().split(",")
623
624 if api_level is None:
625 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
626 if codenames is None:
627 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
628
629 result = dict()
630 for codename in codenames:
631 codename = codename.strip()
632 if len(codename) > 0:
633 result[codename] = api_level
634 return result
635
636
Doug Zongkereef39442009-04-02 12:14:19 -0700637def main(argv):
638
Doug Zongker831840e2011-09-22 10:28:04 -0700639 key_mapping_options = []
640
Doug Zongkereef39442009-04-02 12:14:19 -0700641 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700642 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700643 names, key = a.split("=")
644 names = names.split(",")
645 for n in names:
646 OPTIONS.extra_apks[n] = key
647 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700648 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700649 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700650 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700651 elif o in ("-o", "--replace_ota_keys"):
652 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700653 elif o in ("-t", "--tag_changes"):
654 new = []
655 for i in a.split(","):
656 i = i.strip()
657 if not i or i[0] not in "-+":
658 raise ValueError("Bad tag change '%s'" % (i,))
659 new.append(i[0] + i[1:].strip())
660 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700661 elif o == "--replace_verity_public_key":
662 OPTIONS.replace_verity_public_key = (True, a)
663 elif o == "--replace_verity_private_key":
664 OPTIONS.replace_verity_private_key = (True, a)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700665 elif o == "--replace_verity_keyid":
666 OPTIONS.replace_verity_keyid = (True, a)
Tao Bao639118f2017-06-19 15:48:02 -0700667 elif o == "--avb_vbmeta_key":
668 OPTIONS.avb_keys['vbmeta'] = a
669 elif o == "--avb_vbmeta_algorithm":
670 OPTIONS.avb_algorithms['vbmeta'] = a
671 elif o == "--avb_vbmeta_extra_args":
672 OPTIONS.avb_extra_args['vbmeta'] = a
673 elif o == "--avb_boot_key":
674 OPTIONS.avb_keys['boot'] = a
675 elif o == "--avb_boot_algorithm":
676 OPTIONS.avb_algorithms['boot'] = a
677 elif o == "--avb_boot_extra_args":
678 OPTIONS.avb_extra_args['boot'] = a
679 elif o == "--avb_dtbo_key":
680 OPTIONS.avb_keys['dtbo'] = a
681 elif o == "--avb_dtbo_algorithm":
682 OPTIONS.avb_algorithms['dtbo'] = a
683 elif o == "--avb_dtbo_extra_args":
684 OPTIONS.avb_extra_args['dtbo'] = a
685 elif o == "--avb_system_key":
686 OPTIONS.avb_keys['system'] = a
687 elif o == "--avb_system_algorithm":
688 OPTIONS.avb_algorithms['system'] = a
689 elif o == "--avb_system_extra_args":
690 OPTIONS.avb_extra_args['system'] = a
691 elif o == "--avb_vendor_key":
692 OPTIONS.avb_keys['vendor'] = a
693 elif o == "--avb_vendor_algorithm":
694 OPTIONS.avb_algorithms['vendor'] = a
695 elif o == "--avb_vendor_extra_args":
696 OPTIONS.avb_extra_args['vendor'] = a
Doug Zongkereef39442009-04-02 12:14:19 -0700697 else:
698 return False
699 return True
700
Tao Bao639118f2017-06-19 15:48:02 -0700701 args = common.ParseOptions(
702 argv, __doc__,
703 extra_opts="e:d:k:ot:",
704 extra_long_opts=[
705 "extra_apks=",
706 "default_key_mappings=",
707 "key_mapping=",
708 "replace_ota_keys",
709 "tag_changes=",
710 "replace_verity_public_key=",
711 "replace_verity_private_key=",
712 "replace_verity_keyid=",
713 "avb_vbmeta_algorithm=",
714 "avb_vbmeta_key=",
715 "avb_vbmeta_extra_args=",
716 "avb_boot_algorithm=",
717 "avb_boot_key=",
718 "avb_boot_extra_args=",
719 "avb_dtbo_algorithm=",
720 "avb_dtbo_key=",
721 "avb_dtbo_extra_args=",
722 "avb_system_algorithm=",
723 "avb_system_key=",
724 "avb_system_extra_args=",
725 "avb_vendor_algorithm=",
726 "avb_vendor_key=",
727 "avb_vendor_extra_args=",
728 ],
729 extra_option_handler=option_handler)
Doug Zongkereef39442009-04-02 12:14:19 -0700730
731 if len(args) != 2:
732 common.Usage(__doc__)
733 sys.exit(1)
734
735 input_zip = zipfile.ZipFile(args[0], "r")
Tao Bao2b8f4892017-06-13 12:54:58 -0700736 output_zip = zipfile.ZipFile(args[1], "w",
737 compression=zipfile.ZIP_DEFLATED,
738 allowZip64=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700739
Doug Zongker831840e2011-09-22 10:28:04 -0700740 misc_info = common.LoadInfoDict(input_zip)
741
742 BuildKeyMap(misc_info, key_mapping_options)
743
Doug Zongkereb338ef2009-05-20 16:50:49 -0700744 apk_key_map = GetApkCerts(input_zip)
745 CheckAllApksSigned(input_zip, apk_key_map)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700746
747 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700748 platform_api_level, _ = GetApiLevelAndCodename(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800749 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800750
Doug Zongker412c02f2014-02-13 10:58:24 -0800751 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800752 apk_key_map, key_passwords,
753 platform_api_level,
754 codename_to_api_level_map)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700755
Tao Bao2ed665a2015-04-01 11:21:55 -0700756 common.ZipClose(input_zip)
757 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700758
Tianjie Xub48589a2016-08-03 19:21:52 -0700759 # Skip building userdata.img and cache.img when signing the target files.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700760 new_args = ["--is_signing"]
761 # add_img_to_target_files builds the system image from scratch, so the
762 # recovery patch is guaranteed to be regenerated there.
763 if OPTIONS.rebuild_recovery:
764 new_args.append("--rebuild_recovery")
765 new_args.append(args[1])
Tianjie Xub48589a2016-08-03 19:21:52 -0700766 add_img_to_target_files.main(new_args)
Doug Zongker3c84f562014-07-31 11:06:30 -0700767
Doug Zongkereef39442009-04-02 12:14:19 -0700768 print "done."
769
770
771if __name__ == '__main__':
772 try:
773 main(sys.argv[1:])
774 except common.ExternalError, e:
775 print
776 print " ERROR: %s" % (e,)
777 print
778 sys.exit(1)
Tao Bao639118f2017-06-19 15:48:02 -0700779 finally:
780 common.Cleanup()