blob: c66133363222a49f4f56f9233ae5f3c75447e61f [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>.
Doug Zongkereef39442009-04-02 12:14:19 -070081"""
82
83import sys
84
Doug Zongkercf6d5a92014-02-18 10:57:07 -080085if sys.hexversion < 0x02070000:
86 print >> sys.stderr, "Python 2.7 or newer is required."
Doug Zongkereef39442009-04-02 12:14:19 -070087 sys.exit(1)
88
Robert Craig817c5742013-04-19 10:59:22 -040089import base64
Doug Zongker8e931bf2009-04-06 15:21:45 -070090import cStringIO
91import copy
Robert Craig817c5742013-04-19 10:59:22 -040092import errno
Doug Zongkereef39442009-04-02 12:14:19 -070093import os
94import re
95import subprocess
96import tempfile
97import zipfile
98
Doug Zongker3c84f562014-07-31 11:06:30 -070099import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -0700100import common
101
102OPTIONS = common.OPTIONS
103
104OPTIONS.extra_apks = {}
105OPTIONS.key_map = {}
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700106OPTIONS.rebuild_recovery = False
Doug Zongker8e931bf2009-04-06 15:21:45 -0700107OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -0700108OPTIONS.replace_verity_public_key = False
109OPTIONS.replace_verity_private_key = False
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700110OPTIONS.replace_verity_keyid = False
Doug Zongker831840e2011-09-22 10:28:04 -0700111OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Doug Zongkereef39442009-04-02 12:14:19 -0700112
113def GetApkCerts(tf_zip):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800114 certmap = common.ReadApkCerts(tf_zip)
115
116 # apply the key remapping to the contents of the file
117 for apk, cert in certmap.iteritems():
118 certmap[apk] = OPTIONS.key_map.get(cert, cert)
119
120 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700121 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800122 if not cert:
123 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700124 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800125
Doug Zongkereef39442009-04-02 12:14:19 -0700126 return certmap
127
128
Doug Zongkereb338ef2009-05-20 16:50:49 -0700129def CheckAllApksSigned(input_tf_zip, apk_key_map):
130 """Check that all the APKs we want to sign have keys specified, and
131 error out if they don't."""
132 unknown_apks = []
133 for info in input_tf_zip.infolist():
134 if info.filename.endswith(".apk"):
135 name = os.path.basename(info.filename)
136 if name not in apk_key_map:
137 unknown_apks.append(name)
138 if unknown_apks:
139 print "ERROR: no key specified for:\n\n ",
140 print "\n ".join(unknown_apks)
141 print "\nUse '-e <apkname>=' to specify a key (which may be an"
142 print "empty string to not sign this apk)."
143 sys.exit(1)
144
145
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800146def SignApk(data, keyname, pw, platform_api_level, codename_to_api_level_map):
Doug Zongkereef39442009-04-02 12:14:19 -0700147 unsigned = tempfile.NamedTemporaryFile()
148 unsigned.write(data)
149 unsigned.flush()
150
151 signed = tempfile.NamedTemporaryFile()
152
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800153 # For pre-N builds, don't upgrade to SHA-256 JAR signatures based on the APK's
154 # minSdkVersion to avoid increasing incremental OTA update sizes. If an APK
155 # didn't change, we don't want its signature to change due to the switch
156 # from SHA-1 to SHA-256.
157 # By default, APK signer chooses SHA-256 signatures if the APK's minSdkVersion
158 # is 18 or higher. For pre-N builds we disable this mechanism by pretending
159 # that the APK's minSdkVersion is 1.
160 # For N+ builds, we let APK signer rely on the APK's minSdkVersion to
161 # determine whether to use SHA-256.
162 min_api_level = None
163 if platform_api_level > 23:
164 # Let APK signer choose whether to use SHA-1 or SHA-256, based on the APK's
165 # minSdkVersion attribute
166 min_api_level = None
167 else:
168 # Force APK signer to use SHA-1
169 min_api_level = 1
170
171 common.SignFile(unsigned.name, signed.name, keyname, pw,
172 min_api_level=min_api_level,
173 codename_to_api_level_map=codename_to_api_level_map)
Doug Zongkereef39442009-04-02 12:14:19 -0700174
175 data = signed.read()
176 unsigned.close()
177 signed.close()
178
179 return data
180
181
Doug Zongker412c02f2014-02-13 10:58:24 -0800182def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800183 apk_key_map, key_passwords, platform_api_level,
184 codename_to_api_level_map):
Michael Rungedc2661a2014-06-03 14:43:11 -0700185
Doug Zongkereef39442009-04-02 12:14:19 -0700186 maxsize = max([len(os.path.basename(i.filename))
187 for i in input_tf_zip.infolist()
188 if i.filename.endswith('.apk')])
Tao Baoa80ed222016-06-16 14:41:24 -0700189 system_root_image = misc_info.get("system_root_image") == "true"
Doug Zongker412c02f2014-02-13 10:58:24 -0800190
Doug Zongkereef39442009-04-02 12:14:19 -0700191 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700192 if info.filename.startswith("IMAGES/"):
193 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700194
Doug Zongkereef39442009-04-02 12:14:19 -0700195 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700196 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800197
Tao Baof2cffbd2015-07-22 12:33:18 -0700198 # Sign APKs.
Doug Zongkereef39442009-04-02 12:14:19 -0700199 if info.filename.endswith(".apk"):
200 name = os.path.basename(info.filename)
Doug Zongker43874f82009-04-14 14:05:15 -0700201 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800202 if key not in common.SPECIAL_CERT_STRINGS:
Doug Zongker43874f82009-04-14 14:05:15 -0700203 print " signing: %-*s (%s)" % (maxsize, name, key)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800204 signed_data = SignApk(data, key, key_passwords[key], platform_api_level,
205 codename_to_api_level_map)
Tao Bao2ed665a2015-04-01 11:21:55 -0700206 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700207 else:
208 # an APK we're not supposed to sign.
Doug Zongker43874f82009-04-14 14:05:15 -0700209 print "NOT signing: %s" % (name,)
Tao Bao2ed665a2015-04-01 11:21:55 -0700210 common.ZipWriteStr(output_tf_zip, out_info, data)
Tao Baoa80ed222016-06-16 14:41:24 -0700211
212 # System properties.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700213 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800214 "VENDOR/build.prop",
Tao Baocb7ff772015-09-11 15:27:56 -0700215 "BOOT/RAMDISK/default.prop",
Tao Bao28e2fa12016-08-11 11:00:58 -0700216 "ROOT/default.prop",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700217 "RECOVERY/RAMDISK/default.prop"):
Doug Zongker17aa9442009-04-17 10:15:58 -0700218 print "rewriting %s:" % (info.filename,)
Michael Rungedc2661a2014-06-03 14:43:11 -0700219 new_data = RewriteProps(data, misc_info)
Tao Bao2ed665a2015-04-01 11:21:55 -0700220 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700221
Robert Craig817c5742013-04-19 10:59:22 -0400222 elif info.filename.endswith("mac_permissions.xml"):
223 print "rewriting %s with new keys." % (info.filename,)
224 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700225 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700226
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700227 # Ask add_img_to_target_files to rebuild the recovery patch if needed.
Doug Zongker412c02f2014-02-13 10:58:24 -0800228 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700229 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800230 "SYSTEM/bin/install-recovery.sh"):
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700231 OPTIONS.rebuild_recovery = True
Tao Baoa80ed222016-06-16 14:41:24 -0700232
233 # Don't copy OTA keys if we're replacing them.
Doug Zongker412c02f2014-02-13 10:58:24 -0800234 elif (OPTIONS.replace_ota_keys and
Tao Baoa80ed222016-06-16 14:41:24 -0700235 info.filename in (
236 "BOOT/RAMDISK/res/keys",
Alex Deymob3e8ce62016-08-04 16:06:12 -0700237 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
Tao Baoa80ed222016-06-16 14:41:24 -0700238 "RECOVERY/RAMDISK/res/keys",
239 "SYSTEM/etc/security/otacerts.zip",
240 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800241 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700242
Tao Bao46a59992017-06-05 11:55:16 -0700243 # Skip META/misc_info.txt since we will write back the new values later.
244 elif info.filename == "META/misc_info.txt":
Geremy Condraf19b3652014-07-29 17:54:54 -0700245 pass
Tao Bao8adcfd12016-06-17 17:01:22 -0700246
247 # Skip verity public key if we will replace it.
Michael Runge947894f2014-10-14 20:58:38 -0700248 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700249 info.filename in ("BOOT/RAMDISK/verity_key",
Tao Bao8adcfd12016-06-17 17:01:22 -0700250 "ROOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700251 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700252
Tao Bao8adcfd12016-06-17 17:01:22 -0700253 # Skip verity keyid (for system_root_image use) if we will replace it.
254 elif (OPTIONS.replace_verity_keyid and
255 info.filename == "BOOT/cmdline"):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700256 pass
257
Tianjie Xu4f099002016-08-11 18:04:27 -0700258 # Skip the care_map as we will regenerate the system/vendor images.
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700259 elif info.filename == "META/care_map.txt":
Tianjie Xu4f099002016-08-11 18:04:27 -0700260 pass
261
Tao Baoa80ed222016-06-16 14:41:24 -0700262 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700263 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700264 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700265
Doug Zongker412c02f2014-02-13 10:58:24 -0800266 if OPTIONS.replace_ota_keys:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700267 ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800268
Tao Bao46a59992017-06-05 11:55:16 -0700269 # Replace the keyid string in misc_info dict.
Tao Bao8adcfd12016-06-17 17:01:22 -0700270 if OPTIONS.replace_verity_private_key:
Tao Bao46a59992017-06-05 11:55:16 -0700271 ReplaceVerityPrivateKey(misc_info, OPTIONS.replace_verity_private_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700272
273 if OPTIONS.replace_verity_public_key:
274 if system_root_image:
275 dest = "ROOT/verity_key"
276 else:
277 dest = "BOOT/RAMDISK/verity_key"
278 # We are replacing the one in boot image only, since the one under
279 # recovery won't ever be needed.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700280 ReplaceVerityPublicKey(
Tao Bao8adcfd12016-06-17 17:01:22 -0700281 output_tf_zip, dest, OPTIONS.replace_verity_public_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700282
283 # Replace the keyid string in BOOT/cmdline.
284 if OPTIONS.replace_verity_keyid:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700285 ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
286 OPTIONS.replace_verity_keyid[1])
Doug Zongker412c02f2014-02-13 10:58:24 -0800287
Tao Bao46a59992017-06-05 11:55:16 -0700288 # Write back misc_info with the latest values.
289 ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
290
Doug Zongker8e931bf2009-04-06 15:21:45 -0700291
Robert Craig817c5742013-04-19 10:59:22 -0400292def ReplaceCerts(data):
293 """Given a string of data, replace all occurences of a set
294 of X509 certs with a newer set of X509 certs and return
295 the updated data string."""
296 for old, new in OPTIONS.key_map.iteritems():
297 try:
298 if OPTIONS.verbose:
299 print " Replacing %s.x509.pem with %s.x509.pem" % (old, new)
300 f = open(old + ".x509.pem")
301 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
302 f.close()
303 f = open(new + ".x509.pem")
304 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
305 f.close()
306 # Only match entire certs.
307 pattern = "\\b"+old_cert16+"\\b"
308 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
309 if OPTIONS.verbose:
310 print " Replaced %d occurence(s) of %s.x509.pem with " \
311 "%s.x509.pem" % (num, old, new)
Dan Albert8b72aef2015-03-23 19:13:21 -0700312 except IOError as e:
313 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400314 continue
315
316 print " Error accessing %s. %s. Skip replacing %s.x509.pem " \
317 "with %s.x509.pem." % (e.filename, e.strerror, old, new)
318
319 return data
320
321
Doug Zongkerc09abc82010-01-11 13:09:15 -0800322def EditTags(tags):
323 """Given a string containing comma-separated tags, apply the edits
324 specified in OPTIONS.tag_changes and return the updated string."""
325 tags = set(tags.split(","))
326 for ch in OPTIONS.tag_changes:
327 if ch[0] == "-":
328 tags.discard(ch[1:])
329 elif ch[0] == "+":
330 tags.add(ch[1:])
331 return ",".join(sorted(tags))
332
333
Michael Rungedc2661a2014-06-03 14:43:11 -0700334def RewriteProps(data, misc_info):
Doug Zongker17aa9442009-04-17 10:15:58 -0700335 output = []
336 for line in data.split("\n"):
337 line = line.strip()
338 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700339 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700340 key, value = line.split("=", 1)
Michael Rungee07c75a2014-12-09 13:54:23 -0800341 if (key in ("ro.build.fingerprint", "ro.vendor.build.fingerprint")
Michael Rungedc2661a2014-06-03 14:43:11 -0700342 and misc_info.get("oem_fingerprint_properties") is None):
343 pieces = value.split("/")
344 pieces[-1] = EditTags(pieces[-1])
345 value = "/".join(pieces)
Michael Rungee07c75a2014-12-09 13:54:23 -0800346 elif (key in ("ro.build.thumbprint", "ro.vendor.build.thumbprint")
Dan Albert8b72aef2015-03-23 19:13:21 -0700347 and misc_info.get("oem_fingerprint_properties") is not None):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800348 pieces = value.split("/")
349 pieces[-1] = EditTags(pieces[-1])
350 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700351 elif key == "ro.bootimage.build.fingerprint":
352 pieces = value.split("/")
353 pieces[-1] = EditTags(pieces[-1])
354 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700355 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800356 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700357 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800358 pieces[-1] = EditTags(pieces[-1])
359 value = " ".join(pieces)
360 elif key == "ro.build.tags":
361 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700362 elif key == "ro.build.display.id":
363 # change, eg, "JWR66N dev-keys" to "JWR66N"
364 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700365 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800366 value.pop()
367 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800368 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700369 if line != original_line:
370 print " replace: ", original_line
371 print " with: ", line
372 output.append(line)
373 return "\n".join(output) + "\n"
374
375
Doug Zongker831840e2011-09-22 10:28:04 -0700376def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700377 try:
378 keylist = input_tf_zip.read("META/otakeys.txt").split()
379 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700380 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700381
Doug Zongkere121d6a2011-02-01 14:13:52 -0800382 extra_recovery_keys = misc_info.get("extra_recovery_keys", None)
383 if extra_recovery_keys:
384 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
385 for k in extra_recovery_keys.split()]
386 if extra_recovery_keys:
387 print "extra recovery-only key(s): " + ", ".join(extra_recovery_keys)
388 else:
389 extra_recovery_keys = []
390
Doug Zongker8e931bf2009-04-06 15:21:45 -0700391 mapped_keys = []
392 for k in keylist:
393 m = re.match(r"^(.*)\.x509\.pem$", k)
394 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800395 raise common.ExternalError(
396 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700397 k = m.group(1)
398 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
399
Doug Zongkere05628c2009-08-20 17:38:42 -0700400 if mapped_keys:
401 print "using:\n ", "\n ".join(mapped_keys)
402 print "for OTA package verification"
403 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700404 devkey = misc_info.get("default_system_dev_certificate",
405 "build/target/product/security/testkey")
Doug Zongkere05628c2009-08-20 17:38:42 -0700406 mapped_keys.append(
Doug Zongker831840e2011-09-22 10:28:04 -0700407 OPTIONS.key_map.get(devkey, devkey) + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700408 print("META/otakeys.txt has no keys; using %s for OTA package"
409 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700410
411 # recovery uses a version of the key that has been slightly
412 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800413 # extra_recovery_keys are used only in recovery.
Tao Baoe95540e2016-11-08 12:08:53 -0800414 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
415 ["-jar",
416 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")] +
417 mapped_keys + extra_recovery_keys)
418 p = common.Run(cmd, stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800419 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700420 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700421 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700422
423 # system_root_image puts the recovery keys at BOOT/RAMDISK.
424 if misc_info.get("system_root_image") == "true":
425 recovery_keys_location = "BOOT/RAMDISK/res/keys"
426 else:
427 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
428 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700429
430 # SystemUpdateActivity uses the x509.pem version of the keys, but
431 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800432 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700433
Dan Albert8b72aef2015-03-23 19:13:21 -0700434 temp_file = cStringIO.StringIO()
435 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700436 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700437 common.ZipWrite(certs_zip, k)
438 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700439 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700440 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700441
Tao Baoa80ed222016-06-16 14:41:24 -0700442 # For A/B devices, update the payload verification key.
443 if misc_info.get("ab_update") == "true":
444 # Unlike otacerts.zip that may contain multiple keys, we can only specify
445 # ONE payload verification key.
446 if len(mapped_keys) > 1:
447 print("\n WARNING: Found more than one OTA keys; Using the first one"
448 " as payload verification key.\n\n")
449
450 print "Using %s for payload verification." % (mapped_keys[0],)
Tao Bao13b69622016-07-06 15:28:59 -0700451 cmd = common.Run(
452 ["openssl", "x509", "-pubkey", "-noout", "-in", mapped_keys[0]],
453 stdout=subprocess.PIPE)
454 pubkey, _ = cmd.communicate()
455 common.ZipWriteStr(
Tao Baoa80ed222016-06-16 14:41:24 -0700456 output_tf_zip,
Tao Bao13b69622016-07-06 15:28:59 -0700457 "SYSTEM/etc/update_engine/update-payload-key.pub.pem",
458 pubkey)
Alex Deymob3e8ce62016-08-04 16:06:12 -0700459 common.ZipWriteStr(
460 output_tf_zip,
461 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
462 pubkey)
Tao Baoa80ed222016-06-16 14:41:24 -0700463
Doug Zongker412c02f2014-02-13 10:58:24 -0800464 return new_recovery_keys
465
Tao Bao8adcfd12016-06-17 17:01:22 -0700466
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700467def ReplaceVerityPublicKey(targetfile_zip, filename, key_path):
Tao Bao46a59992017-06-05 11:55:16 -0700468 print "Replacing verity public key with %s" % (key_path,)
469 common.ZipWrite(targetfile_zip, key_path, arcname=filename)
Geremy Condraf19b3652014-07-29 17:54:54 -0700470
Tao Bao8adcfd12016-06-17 17:01:22 -0700471
Tao Bao46a59992017-06-05 11:55:16 -0700472def ReplaceVerityPrivateKey(misc_info, key_path):
473 print "Replacing verity private key with %s" % (key_path,)
Andrew Boied083f0b2014-09-15 16:01:07 -0700474 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700475
Tao Bao8adcfd12016-06-17 17:01:22 -0700476
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700477def ReplaceVerityKeyId(targetfile_input_zip, targetfile_output_zip, keypath):
478 in_cmdline = targetfile_input_zip.read("BOOT/cmdline")
479 # copy in_cmdline to output_zip if veritykeyid is not present in in_cmdline
480 if "veritykeyid" not in in_cmdline:
481 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", in_cmdline)
482 return in_cmdline
483 out_cmdline = []
484 for param in in_cmdline.split():
485 if "veritykeyid" in param:
486 # extract keyid using openssl command
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700487 p = common.Run(
488 ["openssl", "x509", "-in", keypath, "-text"],
489 stdout=subprocess.PIPE)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700490 keyid, stderr = p.communicate()
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700491 keyid = re.search(
492 r'keyid:([0-9a-fA-F:]*)', keyid).group(1).replace(':', '').lower()
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700493 print "Replacing verity keyid with %s error=%s" % (keyid, stderr)
494 out_cmdline.append("veritykeyid=id:%s" % (keyid,))
495 else:
496 out_cmdline.append(param)
497
498 out_cmdline = ' '.join(out_cmdline)
499 out_cmdline = out_cmdline.strip()
500 print "out_cmdline %s" % (out_cmdline)
501 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", out_cmdline)
Tao Bao46a59992017-06-05 11:55:16 -0700502
503
504def ReplaceMiscInfoTxt(input_zip, output_zip, misc_info):
505 """Replaces META/misc_info.txt.
506
507 Only writes back the ones in the original META/misc_info.txt. Because the
508 current in-memory dict contains additional items computed at runtime.
509 """
510 misc_info_old = common.LoadDictionaryFromLines(
511 input_zip.read('META/misc_info.txt').split('\n'))
512 items = []
513 for key in sorted(misc_info):
514 if key in misc_info_old:
515 items.append('%s=%s' % (key, misc_info[key]))
516 common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700517
Tao Bao8adcfd12016-06-17 17:01:22 -0700518
Doug Zongker831840e2011-09-22 10:28:04 -0700519def BuildKeyMap(misc_info, key_mapping_options):
520 for s, d in key_mapping_options:
521 if s is None: # -d option
522 devkey = misc_info.get("default_system_dev_certificate",
523 "build/target/product/security/testkey")
524 devkeydir = os.path.dirname(devkey)
525
526 OPTIONS.key_map.update({
527 devkeydir + "/testkey": d + "/releasekey",
528 devkeydir + "/devkey": d + "/releasekey",
529 devkeydir + "/media": d + "/media",
530 devkeydir + "/shared": d + "/shared",
531 devkeydir + "/platform": d + "/platform",
532 })
533 else:
534 OPTIONS.key_map[s] = d
535
536
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800537def GetApiLevelAndCodename(input_tf_zip):
538 data = input_tf_zip.read("SYSTEM/build.prop")
539 api_level = None
540 codename = None
541 for line in data.split("\n"):
542 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800543 if line and line[0] != '#' and "=" in line:
544 key, value = line.split("=", 1)
545 key = key.strip()
546 if key == "ro.build.version.sdk":
547 api_level = int(value.strip())
548 elif key == "ro.build.version.codename":
549 codename = value.strip()
550
551 if api_level is None:
552 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
553 if codename is None:
554 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
555
556 return (api_level, codename)
557
558
559def GetCodenameToApiLevelMap(input_tf_zip):
560 data = input_tf_zip.read("SYSTEM/build.prop")
561 api_level = None
562 codenames = None
563 for line in data.split("\n"):
564 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800565 if line and line[0] != '#' and "=" in line:
566 key, value = line.split("=", 1)
567 key = key.strip()
568 if key == "ro.build.version.sdk":
569 api_level = int(value.strip())
570 elif key == "ro.build.version.all_codenames":
571 codenames = value.strip().split(",")
572
573 if api_level is None:
574 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
575 if codenames is None:
576 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
577
578 result = dict()
579 for codename in codenames:
580 codename = codename.strip()
581 if len(codename) > 0:
582 result[codename] = api_level
583 return result
584
585
Doug Zongkereef39442009-04-02 12:14:19 -0700586def main(argv):
587
Doug Zongker831840e2011-09-22 10:28:04 -0700588 key_mapping_options = []
589
Doug Zongkereef39442009-04-02 12:14:19 -0700590 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700591 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700592 names, key = a.split("=")
593 names = names.split(",")
594 for n in names:
595 OPTIONS.extra_apks[n] = key
596 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700597 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700598 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700599 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700600 elif o in ("-o", "--replace_ota_keys"):
601 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700602 elif o in ("-t", "--tag_changes"):
603 new = []
604 for i in a.split(","):
605 i = i.strip()
606 if not i or i[0] not in "-+":
607 raise ValueError("Bad tag change '%s'" % (i,))
608 new.append(i[0] + i[1:].strip())
609 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700610 elif o == "--replace_verity_public_key":
611 OPTIONS.replace_verity_public_key = (True, a)
612 elif o == "--replace_verity_private_key":
613 OPTIONS.replace_verity_private_key = (True, a)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700614 elif o == "--replace_verity_keyid":
615 OPTIONS.replace_verity_keyid = (True, a)
Doug Zongkereef39442009-04-02 12:14:19 -0700616 else:
617 return False
618 return True
619
620 args = common.ParseOptions(argv, __doc__,
Doug Zongker05d3dea2009-06-22 11:32:31 -0700621 extra_opts="e:d:k:ot:",
622 extra_long_opts=["extra_apks=",
Doug Zongkereef39442009-04-02 12:14:19 -0700623 "default_key_mappings=",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700624 "key_mapping=",
Doug Zongker17aa9442009-04-17 10:15:58 -0700625 "replace_ota_keys",
Geremy Condraf19b3652014-07-29 17:54:54 -0700626 "tag_changes=",
627 "replace_verity_public_key=",
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700628 "replace_verity_private_key=",
629 "replace_verity_keyid="],
Doug Zongkereef39442009-04-02 12:14:19 -0700630 extra_option_handler=option_handler)
631
632 if len(args) != 2:
633 common.Usage(__doc__)
634 sys.exit(1)
635
636 input_zip = zipfile.ZipFile(args[0], "r")
Tao Bao2b8f4892017-06-13 12:54:58 -0700637 output_zip = zipfile.ZipFile(args[1], "w",
638 compression=zipfile.ZIP_DEFLATED,
639 allowZip64=True)
Doug Zongkereef39442009-04-02 12:14:19 -0700640
Doug Zongker831840e2011-09-22 10:28:04 -0700641 misc_info = common.LoadInfoDict(input_zip)
642
643 BuildKeyMap(misc_info, key_mapping_options)
644
Doug Zongkereb338ef2009-05-20 16:50:49 -0700645 apk_key_map = GetApkCerts(input_zip)
646 CheckAllApksSigned(input_zip, apk_key_map)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700647
648 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700649 platform_api_level, _ = GetApiLevelAndCodename(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800650 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800651
Doug Zongker412c02f2014-02-13 10:58:24 -0800652 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800653 apk_key_map, key_passwords,
654 platform_api_level,
655 codename_to_api_level_map)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700656
Tao Bao2ed665a2015-04-01 11:21:55 -0700657 common.ZipClose(input_zip)
658 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700659
Tianjie Xub48589a2016-08-03 19:21:52 -0700660 # Skip building userdata.img and cache.img when signing the target files.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700661 new_args = ["--is_signing"]
662 # add_img_to_target_files builds the system image from scratch, so the
663 # recovery patch is guaranteed to be regenerated there.
664 if OPTIONS.rebuild_recovery:
665 new_args.append("--rebuild_recovery")
666 new_args.append(args[1])
Tianjie Xub48589a2016-08-03 19:21:52 -0700667 add_img_to_target_files.main(new_args)
Doug Zongker3c84f562014-07-31 11:06:30 -0700668
Doug Zongkereef39442009-04-02 12:14:19 -0700669 print "done."
670
671
672if __name__ == '__main__':
673 try:
674 main(sys.argv[1:])
675 except common.ExternalError, e:
676 print
677 print " ERROR: %s" % (e,)
678 print
679 sys.exit(1)