blob: 3cf8ce711c584396ef6cae99dbf0b786b20c2628 [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 Baoc218a472017-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 Baoc218a472017-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",
Hung-ying Tyanf829b402017-05-01 21:56:26 +0800228 "SYSTEM/etc/prop.default",
229 "BOOT/RAMDISK/prop.default",
230 "BOOT/RAMDISK/default.prop", # legacy
231 "ROOT/default.prop", # legacy
232 "RECOVERY/RAMDISK/prop.default",
233 "RECOVERY/RAMDISK/default.prop"): # legacy
Doug Zongker17aa9442009-04-17 10:15:58 -0700234 print "rewriting %s:" % (info.filename,)
Hung-ying Tyanf829b402017-05-01 21:56:26 +0800235 if stat.S_ISLNK(info.external_attr >> 16):
236 new_data = data
237 else:
238 new_data = RewriteProps(data, misc_info)
Tao Bao2ed665a2015-04-01 11:21:55 -0700239 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700240
Robert Craig817c5742013-04-19 10:59:22 -0400241 elif info.filename.endswith("mac_permissions.xml"):
242 print "rewriting %s with new keys." % (info.filename,)
243 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700244 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baoa80ed222016-06-16 14:41:24 -0700245
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700246 # Ask add_img_to_target_files to rebuild the recovery patch if needed.
Doug Zongker412c02f2014-02-13 10:58:24 -0800247 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700248 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800249 "SYSTEM/bin/install-recovery.sh"):
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700250 OPTIONS.rebuild_recovery = True
Tao Baoa80ed222016-06-16 14:41:24 -0700251
252 # Don't copy OTA keys if we're replacing them.
Doug Zongker412c02f2014-02-13 10:58:24 -0800253 elif (OPTIONS.replace_ota_keys and
Tao Baoa80ed222016-06-16 14:41:24 -0700254 info.filename in (
255 "BOOT/RAMDISK/res/keys",
Alex Deymob3e8ce62016-08-04 16:06:12 -0700256 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
Tao Baoa80ed222016-06-16 14:41:24 -0700257 "RECOVERY/RAMDISK/res/keys",
258 "SYSTEM/etc/security/otacerts.zip",
259 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800260 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700261
Tao Bao57ae9a22017-06-05 11:55:16 -0700262 # Skip META/misc_info.txt since we will write back the new values later.
263 elif info.filename == "META/misc_info.txt":
Geremy Condraf19b3652014-07-29 17:54:54 -0700264 pass
Tao Bao8adcfd12016-06-17 17:01:22 -0700265
266 # Skip verity public key if we will replace it.
Michael Runge947894f2014-10-14 20:58:38 -0700267 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700268 info.filename in ("BOOT/RAMDISK/verity_key",
Tao Bao8adcfd12016-06-17 17:01:22 -0700269 "ROOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700270 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700271
Tao Bao8adcfd12016-06-17 17:01:22 -0700272 # Skip verity keyid (for system_root_image use) if we will replace it.
273 elif (OPTIONS.replace_verity_keyid and
274 info.filename == "BOOT/cmdline"):
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700275 pass
276
Tianjie Xu4f099002016-08-11 18:04:27 -0700277 # Skip the care_map as we will regenerate the system/vendor images.
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700278 elif info.filename == "META/care_map.txt":
Tianjie Xu4f099002016-08-11 18:04:27 -0700279 pass
280
Tao Baoa80ed222016-06-16 14:41:24 -0700281 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700282 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700283 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700284
Doug Zongker412c02f2014-02-13 10:58:24 -0800285 if OPTIONS.replace_ota_keys:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700286 ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800287
Tao Bao57ae9a22017-06-05 11:55:16 -0700288 # Replace the keyid string in misc_info dict.
Tao Bao8adcfd12016-06-17 17:01:22 -0700289 if OPTIONS.replace_verity_private_key:
Tao Bao57ae9a22017-06-05 11:55:16 -0700290 ReplaceVerityPrivateKey(misc_info, OPTIONS.replace_verity_private_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700291
292 if OPTIONS.replace_verity_public_key:
293 if system_root_image:
294 dest = "ROOT/verity_key"
295 else:
296 dest = "BOOT/RAMDISK/verity_key"
297 # We are replacing the one in boot image only, since the one under
298 # recovery won't ever be needed.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700299 ReplaceVerityPublicKey(
Tao Bao8adcfd12016-06-17 17:01:22 -0700300 output_tf_zip, dest, OPTIONS.replace_verity_public_key[1])
Tao Bao8adcfd12016-06-17 17:01:22 -0700301
302 # Replace the keyid string in BOOT/cmdline.
303 if OPTIONS.replace_verity_keyid:
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700304 ReplaceVerityKeyId(input_tf_zip, output_tf_zip,
305 OPTIONS.replace_verity_keyid[1])
Doug Zongker412c02f2014-02-13 10:58:24 -0800306
Tao Baoc218a472017-06-19 15:48:02 -0700307 # Replace the AVB signing keys, if any.
308 ReplaceAvbSigningKeys(misc_info)
309
Tao Bao57ae9a22017-06-05 11:55:16 -0700310 # Write back misc_info with the latest values.
311 ReplaceMiscInfoTxt(input_tf_zip, output_tf_zip, misc_info)
312
Doug Zongker8e931bf2009-04-06 15:21:45 -0700313
Robert Craig817c5742013-04-19 10:59:22 -0400314def ReplaceCerts(data):
315 """Given a string of data, replace all occurences of a set
316 of X509 certs with a newer set of X509 certs and return
317 the updated data string."""
318 for old, new in OPTIONS.key_map.iteritems():
319 try:
320 if OPTIONS.verbose:
321 print " Replacing %s.x509.pem with %s.x509.pem" % (old, new)
322 f = open(old + ".x509.pem")
323 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
324 f.close()
325 f = open(new + ".x509.pem")
326 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
327 f.close()
328 # Only match entire certs.
329 pattern = "\\b"+old_cert16+"\\b"
330 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
331 if OPTIONS.verbose:
332 print " Replaced %d occurence(s) of %s.x509.pem with " \
333 "%s.x509.pem" % (num, old, new)
Dan Albert8b72aef2015-03-23 19:13:21 -0700334 except IOError as e:
335 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400336 continue
337
338 print " Error accessing %s. %s. Skip replacing %s.x509.pem " \
339 "with %s.x509.pem." % (e.filename, e.strerror, old, new)
340
341 return data
342
343
Doug Zongkerc09abc82010-01-11 13:09:15 -0800344def EditTags(tags):
345 """Given a string containing comma-separated tags, apply the edits
346 specified in OPTIONS.tag_changes and return the updated string."""
347 tags = set(tags.split(","))
348 for ch in OPTIONS.tag_changes:
349 if ch[0] == "-":
350 tags.discard(ch[1:])
351 elif ch[0] == "+":
352 tags.add(ch[1:])
353 return ",".join(sorted(tags))
354
355
Michael Rungedc2661a2014-06-03 14:43:11 -0700356def RewriteProps(data, misc_info):
Doug Zongker17aa9442009-04-17 10:15:58 -0700357 output = []
358 for line in data.split("\n"):
359 line = line.strip()
360 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700361 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700362 key, value = line.split("=", 1)
Michael Rungee07c75a2014-12-09 13:54:23 -0800363 if (key in ("ro.build.fingerprint", "ro.vendor.build.fingerprint")
Michael Rungedc2661a2014-06-03 14:43:11 -0700364 and misc_info.get("oem_fingerprint_properties") is None):
365 pieces = value.split("/")
366 pieces[-1] = EditTags(pieces[-1])
367 value = "/".join(pieces)
Michael Rungee07c75a2014-12-09 13:54:23 -0800368 elif (key in ("ro.build.thumbprint", "ro.vendor.build.thumbprint")
Dan Albert8b72aef2015-03-23 19:13:21 -0700369 and misc_info.get("oem_fingerprint_properties") is not None):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800370 pieces = value.split("/")
371 pieces[-1] = EditTags(pieces[-1])
372 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700373 elif key == "ro.bootimage.build.fingerprint":
374 pieces = value.split("/")
375 pieces[-1] = EditTags(pieces[-1])
376 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700377 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800378 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700379 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800380 pieces[-1] = EditTags(pieces[-1])
381 value = " ".join(pieces)
382 elif key == "ro.build.tags":
383 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700384 elif key == "ro.build.display.id":
385 # change, eg, "JWR66N dev-keys" to "JWR66N"
386 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700387 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800388 value.pop()
389 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800390 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700391 if line != original_line:
392 print " replace: ", original_line
393 print " with: ", line
394 output.append(line)
395 return "\n".join(output) + "\n"
396
397
Doug Zongker831840e2011-09-22 10:28:04 -0700398def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700399 try:
400 keylist = input_tf_zip.read("META/otakeys.txt").split()
401 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700402 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700403
Doug Zongkere121d6a2011-02-01 14:13:52 -0800404 extra_recovery_keys = misc_info.get("extra_recovery_keys", None)
405 if extra_recovery_keys:
406 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
407 for k in extra_recovery_keys.split()]
408 if extra_recovery_keys:
409 print "extra recovery-only key(s): " + ", ".join(extra_recovery_keys)
410 else:
411 extra_recovery_keys = []
412
Doug Zongker8e931bf2009-04-06 15:21:45 -0700413 mapped_keys = []
414 for k in keylist:
415 m = re.match(r"^(.*)\.x509\.pem$", k)
416 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800417 raise common.ExternalError(
418 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700419 k = m.group(1)
420 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
421
Doug Zongkere05628c2009-08-20 17:38:42 -0700422 if mapped_keys:
423 print "using:\n ", "\n ".join(mapped_keys)
424 print "for OTA package verification"
425 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700426 devkey = misc_info.get("default_system_dev_certificate",
427 "build/target/product/security/testkey")
Doug Zongkere05628c2009-08-20 17:38:42 -0700428 mapped_keys.append(
Doug Zongker831840e2011-09-22 10:28:04 -0700429 OPTIONS.key_map.get(devkey, devkey) + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700430 print("META/otakeys.txt has no keys; using %s for OTA package"
431 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700432
433 # recovery uses a version of the key that has been slightly
434 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800435 # extra_recovery_keys are used only in recovery.
Tao Baoe95540e2016-11-08 12:08:53 -0800436 cmd = ([OPTIONS.java_path] + OPTIONS.java_args +
437 ["-jar",
438 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")] +
439 mapped_keys + extra_recovery_keys)
440 p = common.Run(cmd, stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800441 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700442 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700443 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700444
445 # system_root_image puts the recovery keys at BOOT/RAMDISK.
446 if misc_info.get("system_root_image") == "true":
447 recovery_keys_location = "BOOT/RAMDISK/res/keys"
448 else:
449 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
450 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700451
452 # SystemUpdateActivity uses the x509.pem version of the keys, but
453 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800454 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700455
Dan Albert8b72aef2015-03-23 19:13:21 -0700456 temp_file = cStringIO.StringIO()
457 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700458 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700459 common.ZipWrite(certs_zip, k)
460 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700461 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700462 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700463
Tao Baoa80ed222016-06-16 14:41:24 -0700464 # For A/B devices, update the payload verification key.
465 if misc_info.get("ab_update") == "true":
466 # Unlike otacerts.zip that may contain multiple keys, we can only specify
467 # ONE payload verification key.
468 if len(mapped_keys) > 1:
469 print("\n WARNING: Found more than one OTA keys; Using the first one"
470 " as payload verification key.\n\n")
471
472 print "Using %s for payload verification." % (mapped_keys[0],)
Tao Bao13b69622016-07-06 15:28:59 -0700473 cmd = common.Run(
474 ["openssl", "x509", "-pubkey", "-noout", "-in", mapped_keys[0]],
475 stdout=subprocess.PIPE)
476 pubkey, _ = cmd.communicate()
477 common.ZipWriteStr(
Tao Baoa80ed222016-06-16 14:41:24 -0700478 output_tf_zip,
Tao Bao13b69622016-07-06 15:28:59 -0700479 "SYSTEM/etc/update_engine/update-payload-key.pub.pem",
480 pubkey)
Alex Deymob3e8ce62016-08-04 16:06:12 -0700481 common.ZipWriteStr(
482 output_tf_zip,
483 "BOOT/RAMDISK/etc/update_engine/update-payload-key.pub.pem",
484 pubkey)
Tao Baoa80ed222016-06-16 14:41:24 -0700485
Doug Zongker412c02f2014-02-13 10:58:24 -0800486 return new_recovery_keys
487
Tao Bao8adcfd12016-06-17 17:01:22 -0700488
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700489def ReplaceVerityPublicKey(targetfile_zip, filename, key_path):
Tao Bao57ae9a22017-06-05 11:55:16 -0700490 print "Replacing verity public key with %s" % (key_path,)
491 common.ZipWrite(targetfile_zip, key_path, arcname=filename)
Geremy Condraf19b3652014-07-29 17:54:54 -0700492
Tao Bao8adcfd12016-06-17 17:01:22 -0700493
Tao Bao57ae9a22017-06-05 11:55:16 -0700494def ReplaceVerityPrivateKey(misc_info, key_path):
495 print "Replacing verity private key with %s" % (key_path,)
Andrew Boied083f0b2014-09-15 16:01:07 -0700496 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700497
Tao Bao8adcfd12016-06-17 17:01:22 -0700498
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700499def ReplaceVerityKeyId(targetfile_input_zip, targetfile_output_zip, keypath):
500 in_cmdline = targetfile_input_zip.read("BOOT/cmdline")
501 # copy in_cmdline to output_zip if veritykeyid is not present in in_cmdline
502 if "veritykeyid" not in in_cmdline:
503 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", in_cmdline)
504 return in_cmdline
505 out_cmdline = []
506 for param in in_cmdline.split():
507 if "veritykeyid" in param:
508 # extract keyid using openssl command
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700509 p = common.Run(
510 ["openssl", "x509", "-in", keypath, "-text"],
511 stdout=subprocess.PIPE)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700512 keyid, stderr = p.communicate()
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700513 keyid = re.search(
514 r'keyid:([0-9a-fA-F:]*)', keyid).group(1).replace(':', '').lower()
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700515 print "Replacing verity keyid with %s error=%s" % (keyid, stderr)
516 out_cmdline.append("veritykeyid=id:%s" % (keyid,))
517 else:
518 out_cmdline.append(param)
519
520 out_cmdline = ' '.join(out_cmdline)
521 out_cmdline = out_cmdline.strip()
522 print "out_cmdline %s" % (out_cmdline)
523 common.ZipWriteStr(targetfile_output_zip, "BOOT/cmdline", out_cmdline)
Tao Bao57ae9a22017-06-05 11:55:16 -0700524
525
526def ReplaceMiscInfoTxt(input_zip, output_zip, misc_info):
527 """Replaces META/misc_info.txt.
528
529 Only writes back the ones in the original META/misc_info.txt. Because the
530 current in-memory dict contains additional items computed at runtime.
531 """
532 misc_info_old = common.LoadDictionaryFromLines(
533 input_zip.read('META/misc_info.txt').split('\n'))
534 items = []
535 for key in sorted(misc_info):
536 if key in misc_info_old:
537 items.append('%s=%s' % (key, misc_info[key]))
538 common.ZipWriteStr(output_zip, "META/misc_info.txt", '\n'.join(items))
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700539
Tao Bao8adcfd12016-06-17 17:01:22 -0700540
Tao Baoc218a472017-06-19 15:48:02 -0700541def ReplaceAvbSigningKeys(misc_info):
542 """Replaces the AVB signing keys."""
543
544 AVB_FOOTER_ARGS_BY_PARTITION = {
545 'boot' : 'avb_boot_add_hash_footer_args',
546 'dtbo' : 'avb_dtbo_add_hash_footer_args',
547 'system' : 'avb_system_add_hashtree_footer_args',
548 'vendor' : 'avb_vendor_add_hashtree_footer_args',
549 'vbmeta' : 'avb_vbmeta_args',
550 }
551
552 def ReplaceAvbPartitionSigningKey(partition):
553 key = OPTIONS.avb_keys.get(partition)
554 if not key:
555 return
556
557 algorithm = OPTIONS.avb_algorithms.get(partition)
558 assert algorithm, 'Missing AVB signing algorithm for %s' % (partition,)
559
560 print 'Replacing AVB signing key for %s with "%s" (%s)' % (
561 partition, key, algorithm)
562 misc_info['avb_' + partition + '_algorithm'] = algorithm
563 misc_info['avb_' + partition + '_key_path'] = key
564
565 extra_args = OPTIONS.avb_extra_args.get(partition)
566 if extra_args:
567 print 'Setting extra AVB signing args for %s to "%s"' % (
568 partition, extra_args)
569 args_key = AVB_FOOTER_ARGS_BY_PARTITION[partition]
570 misc_info[args_key] = (misc_info.get(args_key, '') + ' ' + extra_args)
571
572 for partition in AVB_FOOTER_ARGS_BY_PARTITION:
573 ReplaceAvbPartitionSigningKey(partition)
574
575
Doug Zongker831840e2011-09-22 10:28:04 -0700576def BuildKeyMap(misc_info, key_mapping_options):
577 for s, d in key_mapping_options:
578 if s is None: # -d option
579 devkey = misc_info.get("default_system_dev_certificate",
580 "build/target/product/security/testkey")
581 devkeydir = os.path.dirname(devkey)
582
583 OPTIONS.key_map.update({
584 devkeydir + "/testkey": d + "/releasekey",
585 devkeydir + "/devkey": d + "/releasekey",
586 devkeydir + "/media": d + "/media",
587 devkeydir + "/shared": d + "/shared",
588 devkeydir + "/platform": d + "/platform",
589 })
590 else:
591 OPTIONS.key_map[s] = d
592
593
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800594def GetApiLevelAndCodename(input_tf_zip):
595 data = input_tf_zip.read("SYSTEM/build.prop")
596 api_level = None
597 codename = None
598 for line in data.split("\n"):
599 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800600 if line and line[0] != '#' and "=" in line:
601 key, value = line.split("=", 1)
602 key = key.strip()
603 if key == "ro.build.version.sdk":
604 api_level = int(value.strip())
605 elif key == "ro.build.version.codename":
606 codename = value.strip()
607
608 if api_level is None:
609 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
610 if codename is None:
611 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
612
613 return (api_level, codename)
614
615
616def GetCodenameToApiLevelMap(input_tf_zip):
617 data = input_tf_zip.read("SYSTEM/build.prop")
618 api_level = None
619 codenames = None
620 for line in data.split("\n"):
621 line = line.strip()
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800622 if line and line[0] != '#' and "=" in line:
623 key, value = line.split("=", 1)
624 key = key.strip()
625 if key == "ro.build.version.sdk":
626 api_level = int(value.strip())
627 elif key == "ro.build.version.all_codenames":
628 codenames = value.strip().split(",")
629
630 if api_level is None:
631 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
632 if codenames is None:
633 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
634
635 result = dict()
636 for codename in codenames:
637 codename = codename.strip()
638 if len(codename) > 0:
639 result[codename] = api_level
640 return result
641
642
Doug Zongkereef39442009-04-02 12:14:19 -0700643def main(argv):
644
Doug Zongker831840e2011-09-22 10:28:04 -0700645 key_mapping_options = []
646
Doug Zongkereef39442009-04-02 12:14:19 -0700647 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700648 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700649 names, key = a.split("=")
650 names = names.split(",")
651 for n in names:
652 OPTIONS.extra_apks[n] = key
653 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700654 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700655 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700656 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700657 elif o in ("-o", "--replace_ota_keys"):
658 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700659 elif o in ("-t", "--tag_changes"):
660 new = []
661 for i in a.split(","):
662 i = i.strip()
663 if not i or i[0] not in "-+":
664 raise ValueError("Bad tag change '%s'" % (i,))
665 new.append(i[0] + i[1:].strip())
666 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700667 elif o == "--replace_verity_public_key":
668 OPTIONS.replace_verity_public_key = (True, a)
669 elif o == "--replace_verity_private_key":
670 OPTIONS.replace_verity_private_key = (True, a)
Badhri Jagan Sridharan35c9b122016-06-16 19:58:44 -0700671 elif o == "--replace_verity_keyid":
672 OPTIONS.replace_verity_keyid = (True, a)
Tao Baoc218a472017-06-19 15:48:02 -0700673 elif o == "--avb_vbmeta_key":
674 OPTIONS.avb_keys['vbmeta'] = a
675 elif o == "--avb_vbmeta_algorithm":
676 OPTIONS.avb_algorithms['vbmeta'] = a
677 elif o == "--avb_vbmeta_extra_args":
678 OPTIONS.avb_extra_args['vbmeta'] = a
679 elif o == "--avb_boot_key":
680 OPTIONS.avb_keys['boot'] = a
681 elif o == "--avb_boot_algorithm":
682 OPTIONS.avb_algorithms['boot'] = a
683 elif o == "--avb_boot_extra_args":
684 OPTIONS.avb_extra_args['boot'] = a
685 elif o == "--avb_dtbo_key":
686 OPTIONS.avb_keys['dtbo'] = a
687 elif o == "--avb_dtbo_algorithm":
688 OPTIONS.avb_algorithms['dtbo'] = a
689 elif o == "--avb_dtbo_extra_args":
690 OPTIONS.avb_extra_args['dtbo'] = a
691 elif o == "--avb_system_key":
692 OPTIONS.avb_keys['system'] = a
693 elif o == "--avb_system_algorithm":
694 OPTIONS.avb_algorithms['system'] = a
695 elif o == "--avb_system_extra_args":
696 OPTIONS.avb_extra_args['system'] = a
697 elif o == "--avb_vendor_key":
698 OPTIONS.avb_keys['vendor'] = a
699 elif o == "--avb_vendor_algorithm":
700 OPTIONS.avb_algorithms['vendor'] = a
701 elif o == "--avb_vendor_extra_args":
702 OPTIONS.avb_extra_args['vendor'] = a
Doug Zongkereef39442009-04-02 12:14:19 -0700703 else:
704 return False
705 return True
706
Tao Baoc218a472017-06-19 15:48:02 -0700707 args = common.ParseOptions(
708 argv, __doc__,
709 extra_opts="e:d:k:ot:",
710 extra_long_opts=[
711 "extra_apks=",
712 "default_key_mappings=",
713 "key_mapping=",
714 "replace_ota_keys",
715 "tag_changes=",
716 "replace_verity_public_key=",
717 "replace_verity_private_key=",
718 "replace_verity_keyid=",
719 "avb_vbmeta_algorithm=",
720 "avb_vbmeta_key=",
721 "avb_vbmeta_extra_args=",
722 "avb_boot_algorithm=",
723 "avb_boot_key=",
724 "avb_boot_extra_args=",
725 "avb_dtbo_algorithm=",
726 "avb_dtbo_key=",
727 "avb_dtbo_extra_args=",
728 "avb_system_algorithm=",
729 "avb_system_key=",
730 "avb_system_extra_args=",
731 "avb_vendor_algorithm=",
732 "avb_vendor_key=",
733 "avb_vendor_extra_args=",
734 ],
735 extra_option_handler=option_handler)
Doug Zongkereef39442009-04-02 12:14:19 -0700736
737 if len(args) != 2:
738 common.Usage(__doc__)
739 sys.exit(1)
740
741 input_zip = zipfile.ZipFile(args[0], "r")
742 output_zip = zipfile.ZipFile(args[1], "w")
743
Doug Zongker831840e2011-09-22 10:28:04 -0700744 misc_info = common.LoadInfoDict(input_zip)
745
746 BuildKeyMap(misc_info, key_mapping_options)
747
Doug Zongkereb338ef2009-05-20 16:50:49 -0700748 apk_key_map = GetApkCerts(input_zip)
749 CheckAllApksSigned(input_zip, apk_key_map)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700750
751 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Tao Bao9aa4b9b2016-09-29 17:53:56 -0700752 platform_api_level, _ = GetApiLevelAndCodename(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800753 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800754
Doug Zongker412c02f2014-02-13 10:58:24 -0800755 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800756 apk_key_map, key_passwords,
757 platform_api_level,
758 codename_to_api_level_map)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700759
Tao Bao2ed665a2015-04-01 11:21:55 -0700760 common.ZipClose(input_zip)
761 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700762
Tianjie Xub48589a2016-08-03 19:21:52 -0700763 # Skip building userdata.img and cache.img when signing the target files.
Tianjie Xu616fbeb2017-05-23 14:51:02 -0700764 new_args = ["--is_signing"]
765 # add_img_to_target_files builds the system image from scratch, so the
766 # recovery patch is guaranteed to be regenerated there.
767 if OPTIONS.rebuild_recovery:
768 new_args.append("--rebuild_recovery")
769 new_args.append(args[1])
Tianjie Xub48589a2016-08-03 19:21:52 -0700770 add_img_to_target_files.main(new_args)
Doug Zongker3c84f562014-07-31 11:06:30 -0700771
Doug Zongkereef39442009-04-02 12:14:19 -0700772 print "done."
773
774
775if __name__ == '__main__':
776 try:
777 main(sys.argv[1:])
778 except common.ExternalError, e:
779 print
780 print " ERROR: %s" % (e,)
781 print
782 sys.exit(1)
Tao Baoc218a472017-06-19 15:48:02 -0700783 finally:
784 common.Cleanup()