blob: e67a166d6500da91aae63d1c5ef771fdac94eb1f [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
Doug Zongkereef39442009-04-02 12:14:19 -070068"""
69
70import sys
71
Doug Zongkercf6d5a92014-02-18 10:57:07 -080072if sys.hexversion < 0x02070000:
73 print >> sys.stderr, "Python 2.7 or newer is required."
Doug Zongkereef39442009-04-02 12:14:19 -070074 sys.exit(1)
75
Robert Craig817c5742013-04-19 10:59:22 -040076import base64
Doug Zongker8e931bf2009-04-06 15:21:45 -070077import cStringIO
78import copy
Robert Craig817c5742013-04-19 10:59:22 -040079import errno
Doug Zongkereef39442009-04-02 12:14:19 -070080import os
81import re
Doug Zongker412c02f2014-02-13 10:58:24 -080082import shutil
Doug Zongkereef39442009-04-02 12:14:19 -070083import subprocess
84import tempfile
85import zipfile
86
Doug Zongker3c84f562014-07-31 11:06:30 -070087import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -070088import common
89
90OPTIONS = common.OPTIONS
91
92OPTIONS.extra_apks = {}
93OPTIONS.key_map = {}
Doug Zongker8e931bf2009-04-06 15:21:45 -070094OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -070095OPTIONS.replace_verity_public_key = False
96OPTIONS.replace_verity_private_key = False
Doug Zongker831840e2011-09-22 10:28:04 -070097OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Doug Zongkereef39442009-04-02 12:14:19 -070098
99def GetApkCerts(tf_zip):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800100 certmap = common.ReadApkCerts(tf_zip)
101
102 # apply the key remapping to the contents of the file
103 for apk, cert in certmap.iteritems():
104 certmap[apk] = OPTIONS.key_map.get(cert, cert)
105
106 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700107 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800108 if not cert:
109 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700110 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800111
Doug Zongkereef39442009-04-02 12:14:19 -0700112 return certmap
113
114
Doug Zongkereb338ef2009-05-20 16:50:49 -0700115def CheckAllApksSigned(input_tf_zip, apk_key_map):
116 """Check that all the APKs we want to sign have keys specified, and
117 error out if they don't."""
118 unknown_apks = []
119 for info in input_tf_zip.infolist():
120 if info.filename.endswith(".apk"):
121 name = os.path.basename(info.filename)
122 if name not in apk_key_map:
123 unknown_apks.append(name)
124 if unknown_apks:
125 print "ERROR: no key specified for:\n\n ",
126 print "\n ".join(unknown_apks)
127 print "\nUse '-e <apkname>=' to specify a key (which may be an"
128 print "empty string to not sign this apk)."
129 sys.exit(1)
130
131
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800132def SignApk(data, keyname, pw, platform_api_level, codename_to_api_level_map):
Doug Zongkereef39442009-04-02 12:14:19 -0700133 unsigned = tempfile.NamedTemporaryFile()
134 unsigned.write(data)
135 unsigned.flush()
136
137 signed = tempfile.NamedTemporaryFile()
138
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800139 # For pre-N builds, don't upgrade to SHA-256 JAR signatures based on the APK's
140 # minSdkVersion to avoid increasing incremental OTA update sizes. If an APK
141 # didn't change, we don't want its signature to change due to the switch
142 # from SHA-1 to SHA-256.
143 # By default, APK signer chooses SHA-256 signatures if the APK's minSdkVersion
144 # is 18 or higher. For pre-N builds we disable this mechanism by pretending
145 # that the APK's minSdkVersion is 1.
146 # For N+ builds, we let APK signer rely on the APK's minSdkVersion to
147 # determine whether to use SHA-256.
148 min_api_level = None
149 if platform_api_level > 23:
150 # Let APK signer choose whether to use SHA-1 or SHA-256, based on the APK's
151 # minSdkVersion attribute
152 min_api_level = None
153 else:
154 # Force APK signer to use SHA-1
155 min_api_level = 1
156
157 common.SignFile(unsigned.name, signed.name, keyname, pw,
158 min_api_level=min_api_level,
159 codename_to_api_level_map=codename_to_api_level_map)
Doug Zongkereef39442009-04-02 12:14:19 -0700160
161 data = signed.read()
162 unsigned.close()
163 signed.close()
164
165 return data
166
167
Doug Zongker412c02f2014-02-13 10:58:24 -0800168def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800169 apk_key_map, key_passwords, platform_api_level,
170 codename_to_api_level_map):
Michael Rungedc2661a2014-06-03 14:43:11 -0700171
Doug Zongkereef39442009-04-02 12:14:19 -0700172 maxsize = max([len(os.path.basename(i.filename))
173 for i in input_tf_zip.infolist()
174 if i.filename.endswith('.apk')])
Doug Zongker412c02f2014-02-13 10:58:24 -0800175 rebuild_recovery = False
Tao Baoa80ed222016-06-16 14:41:24 -0700176 system_root_image = misc_info.get("system_root_image") == "true"
Doug Zongker412c02f2014-02-13 10:58:24 -0800177
Tao Baoa80ed222016-06-16 14:41:24 -0700178 # tmpdir will only be used to regenerate the recovery-from-boot patch.
Doug Zongker412c02f2014-02-13 10:58:24 -0800179 tmpdir = tempfile.mkdtemp()
180 def write_to_temp(fn, attr, data):
181 fn = os.path.join(tmpdir, fn)
182 if fn.endswith("/"):
183 fn = os.path.join(tmpdir, fn)
184 os.mkdir(fn)
185 else:
186 d = os.path.dirname(fn)
187 if d and not os.path.exists(d):
188 os.makedirs(d)
189
190 if attr >> 16 == 0xa1ff:
191 os.symlink(data, fn)
192 else:
193 with open(fn, "wb") as f:
194 f.write(data)
Doug Zongkereef39442009-04-02 12:14:19 -0700195
196 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700197 if info.filename.startswith("IMAGES/"):
198 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700199
Doug Zongkereef39442009-04-02 12:14:19 -0700200 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700201 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800202
Tao Baof2cffbd2015-07-22 12:33:18 -0700203 # Replace keys if requested.
Geremy Condraf19b3652014-07-29 17:54:54 -0700204 if (info.filename == "META/misc_info.txt" and
Michael Runge947894f2014-10-14 20:58:38 -0700205 OPTIONS.replace_verity_private_key):
Dan Albert8b72aef2015-03-23 19:13:21 -0700206 ReplaceVerityPrivateKey(input_tf_zip, output_tf_zip, misc_info,
207 OPTIONS.replace_verity_private_key[1])
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700208 elif (info.filename in ("BOOT/RAMDISK/verity_key",
209 "BOOT/verity_key") and
Dan Albert8b72aef2015-03-23 19:13:21 -0700210 OPTIONS.replace_verity_public_key):
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700211 new_data = ReplaceVerityPublicKey(output_tf_zip, info.filename,
Dan Albert8b72aef2015-03-23 19:13:21 -0700212 OPTIONS.replace_verity_public_key[1])
Andrew Boied083f0b2014-09-15 16:01:07 -0700213 write_to_temp(info.filename, info.external_attr, new_data)
Doug Zongker412c02f2014-02-13 10:58:24 -0800214
Tao Baof2cffbd2015-07-22 12:33:18 -0700215 # Sign APKs.
Doug Zongkereef39442009-04-02 12:14:19 -0700216 if info.filename.endswith(".apk"):
217 name = os.path.basename(info.filename)
Doug Zongker43874f82009-04-14 14:05:15 -0700218 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800219 if key not in common.SPECIAL_CERT_STRINGS:
Doug Zongker43874f82009-04-14 14:05:15 -0700220 print " signing: %-*s (%s)" % (maxsize, name, key)
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800221 signed_data = SignApk(data, key, key_passwords[key], platform_api_level,
222 codename_to_api_level_map)
Tao Bao2ed665a2015-04-01 11:21:55 -0700223 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700224 else:
225 # an APK we're not supposed to sign.
Doug Zongker43874f82009-04-14 14:05:15 -0700226 print "NOT signing: %s" % (name,)
Tao Bao2ed665a2015-04-01 11:21:55 -0700227 common.ZipWriteStr(output_tf_zip, out_info, data)
Tao Baoa80ed222016-06-16 14:41:24 -0700228
229 # System properties.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700230 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800231 "VENDOR/build.prop",
Tao Baocb7ff772015-09-11 15:27:56 -0700232 "BOOT/RAMDISK/default.prop",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700233 "RECOVERY/RAMDISK/default.prop"):
Doug Zongker17aa9442009-04-17 10:15:58 -0700234 print "rewriting %s:" % (info.filename,)
Michael Rungedc2661a2014-06-03 14:43:11 -0700235 new_data = RewriteProps(data, misc_info)
Tao Bao2ed665a2015-04-01 11:21:55 -0700236 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Tao Baocb7ff772015-09-11 15:27:56 -0700237 if info.filename in ("BOOT/RAMDISK/default.prop",
238 "RECOVERY/RAMDISK/default.prop"):
Doug Zongker412c02f2014-02-13 10:58:24 -0800239 write_to_temp(info.filename, info.external_attr, 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
246 # Trigger a rebuild of 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"):
250 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",
256 "RECOVERY/RAMDISK/res/keys",
257 "SYSTEM/etc/security/otacerts.zip",
258 "SYSTEM/etc/update_engine/update-payload-key.pub.pem")):
Doug Zongker412c02f2014-02-13 10:58:24 -0800259 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700260
261 # Skip verity keys since they have been processed above.
262 # TODO: verity_key is at a wrong location (BOOT/verity_key). Will fix and
263 # clean up verity related lines in a separate CL.
Michael Runge947894f2014-10-14 20:58:38 -0700264 elif (OPTIONS.replace_verity_private_key and
Geremy Condraf19b3652014-07-29 17:54:54 -0700265 info.filename == "META/misc_info.txt"):
266 pass
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",
269 "BOOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700270 pass
Tao Baoa80ed222016-06-16 14:41:24 -0700271
272 # Copy BOOT/, RECOVERY/, META/, ROOT/ to rebuild recovery patch. This case
273 # must come AFTER other matching rules.
274 elif (info.filename.startswith("BOOT/") or
275 info.filename.startswith("RECOVERY/") or
276 info.filename.startswith("META/") or
277 info.filename.startswith("ROOT/") or
278 info.filename == "SYSTEM/etc/recovery-resource.dat"):
279 write_to_temp(info.filename, info.external_attr, data)
280 common.ZipWriteStr(output_tf_zip, out_info, data)
281
282 # A non-APK file; copy it verbatim.
Doug Zongkereef39442009-04-02 12:14:19 -0700283 else:
Tao Bao2ed665a2015-04-01 11:21:55 -0700284 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700285
Doug Zongker412c02f2014-02-13 10:58:24 -0800286 if OPTIONS.replace_ota_keys:
287 new_recovery_keys = ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
288 if new_recovery_keys:
Tao Baoa80ed222016-06-16 14:41:24 -0700289 if system_root_image:
290 recovery_keys_location = "BOOT/RAMDISK/res/keys"
291 else:
292 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
293 # The "new_recovery_keys" has been already written into the output_tf_zip
294 # while calling ReplaceOtaKeys(). We're just putting the same copy to
295 # tmpdir in case we need to regenerate the recovery-from-boot patch.
296 write_to_temp(recovery_keys_location, 0o755 << 16, new_recovery_keys)
Doug Zongker412c02f2014-02-13 10:58:24 -0800297
298 if rebuild_recovery:
299 recovery_img = common.GetBootableImage(
300 "recovery.img", "recovery.img", tmpdir, "RECOVERY", info_dict=misc_info)
301 boot_img = common.GetBootableImage(
302 "boot.img", "boot.img", tmpdir, "BOOT", info_dict=misc_info)
303
304 def output_sink(fn, data):
Tao Bao2ed665a2015-04-01 11:21:55 -0700305 common.ZipWriteStr(output_tf_zip, "SYSTEM/" + fn, data)
Doug Zongker412c02f2014-02-13 10:58:24 -0800306
307 common.MakeRecoveryPatch(tmpdir, output_sink, recovery_img, boot_img,
308 info_dict=misc_info)
309
310 shutil.rmtree(tmpdir)
311
Doug Zongker8e931bf2009-04-06 15:21:45 -0700312
Robert Craig817c5742013-04-19 10:59:22 -0400313def ReplaceCerts(data):
314 """Given a string of data, replace all occurences of a set
315 of X509 certs with a newer set of X509 certs and return
316 the updated data string."""
317 for old, new in OPTIONS.key_map.iteritems():
318 try:
319 if OPTIONS.verbose:
320 print " Replacing %s.x509.pem with %s.x509.pem" % (old, new)
321 f = open(old + ".x509.pem")
322 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
323 f.close()
324 f = open(new + ".x509.pem")
325 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
326 f.close()
327 # Only match entire certs.
328 pattern = "\\b"+old_cert16+"\\b"
329 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
330 if OPTIONS.verbose:
331 print " Replaced %d occurence(s) of %s.x509.pem with " \
332 "%s.x509.pem" % (num, old, new)
Dan Albert8b72aef2015-03-23 19:13:21 -0700333 except IOError as e:
334 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400335 continue
336
337 print " Error accessing %s. %s. Skip replacing %s.x509.pem " \
338 "with %s.x509.pem." % (e.filename, e.strerror, old, new)
339
340 return data
341
342
Doug Zongkerc09abc82010-01-11 13:09:15 -0800343def EditTags(tags):
344 """Given a string containing comma-separated tags, apply the edits
345 specified in OPTIONS.tag_changes and return the updated string."""
346 tags = set(tags.split(","))
347 for ch in OPTIONS.tag_changes:
348 if ch[0] == "-":
349 tags.discard(ch[1:])
350 elif ch[0] == "+":
351 tags.add(ch[1:])
352 return ",".join(sorted(tags))
353
354
Michael Rungedc2661a2014-06-03 14:43:11 -0700355def RewriteProps(data, misc_info):
Doug Zongker17aa9442009-04-17 10:15:58 -0700356 output = []
357 for line in data.split("\n"):
358 line = line.strip()
359 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700360 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700361 key, value = line.split("=", 1)
Michael Rungee07c75a2014-12-09 13:54:23 -0800362 if (key in ("ro.build.fingerprint", "ro.vendor.build.fingerprint")
Michael Rungedc2661a2014-06-03 14:43:11 -0700363 and misc_info.get("oem_fingerprint_properties") is None):
364 pieces = value.split("/")
365 pieces[-1] = EditTags(pieces[-1])
366 value = "/".join(pieces)
Michael Rungee07c75a2014-12-09 13:54:23 -0800367 elif (key in ("ro.build.thumbprint", "ro.vendor.build.thumbprint")
Dan Albert8b72aef2015-03-23 19:13:21 -0700368 and misc_info.get("oem_fingerprint_properties") is not None):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800369 pieces = value.split("/")
370 pieces[-1] = EditTags(pieces[-1])
371 value = "/".join(pieces)
Tao Baocb7ff772015-09-11 15:27:56 -0700372 elif key == "ro.bootimage.build.fingerprint":
373 pieces = value.split("/")
374 pieces[-1] = EditTags(pieces[-1])
375 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700376 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800377 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700378 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800379 pieces[-1] = EditTags(pieces[-1])
380 value = " ".join(pieces)
381 elif key == "ro.build.tags":
382 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700383 elif key == "ro.build.display.id":
384 # change, eg, "JWR66N dev-keys" to "JWR66N"
385 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700386 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800387 value.pop()
388 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800389 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700390 if line != original_line:
391 print " replace: ", original_line
392 print " with: ", line
393 output.append(line)
394 return "\n".join(output) + "\n"
395
396
Doug Zongker831840e2011-09-22 10:28:04 -0700397def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700398 try:
399 keylist = input_tf_zip.read("META/otakeys.txt").split()
400 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700401 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700402
Doug Zongkere121d6a2011-02-01 14:13:52 -0800403 extra_recovery_keys = misc_info.get("extra_recovery_keys", None)
404 if extra_recovery_keys:
405 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
406 for k in extra_recovery_keys.split()]
407 if extra_recovery_keys:
408 print "extra recovery-only key(s): " + ", ".join(extra_recovery_keys)
409 else:
410 extra_recovery_keys = []
411
Doug Zongker8e931bf2009-04-06 15:21:45 -0700412 mapped_keys = []
413 for k in keylist:
414 m = re.match(r"^(.*)\.x509\.pem$", k)
415 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800416 raise common.ExternalError(
417 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700418 k = m.group(1)
419 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
420
Doug Zongkere05628c2009-08-20 17:38:42 -0700421 if mapped_keys:
422 print "using:\n ", "\n ".join(mapped_keys)
423 print "for OTA package verification"
424 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700425 devkey = misc_info.get("default_system_dev_certificate",
426 "build/target/product/security/testkey")
Doug Zongkere05628c2009-08-20 17:38:42 -0700427 mapped_keys.append(
Doug Zongker831840e2011-09-22 10:28:04 -0700428 OPTIONS.key_map.get(devkey, devkey) + ".x509.pem")
Tao Baoa80ed222016-06-16 14:41:24 -0700429 print("META/otakeys.txt has no keys; using %s for OTA package"
430 " verification." % (mapped_keys[0],))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700431
432 # recovery uses a version of the key that has been slightly
433 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800434 # extra_recovery_keys are used only in recovery.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700435
Doug Zongker602a84e2009-06-18 08:35:12 -0700436 p = common.Run(["java", "-jar",
437 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")]
Doug Zongkere121d6a2011-02-01 14:13:52 -0800438 + mapped_keys + extra_recovery_keys,
Doug Zongker8e931bf2009-04-06 15:21:45 -0700439 stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800440 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700441 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700442 raise common.ExternalError("failed to run dumpkeys")
Tao Baoa80ed222016-06-16 14:41:24 -0700443
444 # system_root_image puts the recovery keys at BOOT/RAMDISK.
445 if misc_info.get("system_root_image") == "true":
446 recovery_keys_location = "BOOT/RAMDISK/res/keys"
447 else:
448 recovery_keys_location = "RECOVERY/RAMDISK/res/keys"
449 common.ZipWriteStr(output_tf_zip, recovery_keys_location, new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700450
451 # SystemUpdateActivity uses the x509.pem version of the keys, but
452 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800453 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700454
Dan Albert8b72aef2015-03-23 19:13:21 -0700455 temp_file = cStringIO.StringIO()
456 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700457 for k in mapped_keys:
Tao Bao83cd79d2016-04-11 23:05:52 -0700458 common.ZipWrite(certs_zip, k)
459 common.ZipClose(certs_zip)
Doug Zongker048e7ca2009-06-15 14:31:53 -0700460 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700461 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700462
Tao Baoa80ed222016-06-16 14:41:24 -0700463 # For A/B devices, update the payload verification key.
464 if misc_info.get("ab_update") == "true":
465 # Unlike otacerts.zip that may contain multiple keys, we can only specify
466 # ONE payload verification key.
467 if len(mapped_keys) > 1:
468 print("\n WARNING: Found more than one OTA keys; Using the first one"
469 " as payload verification key.\n\n")
470
471 print "Using %s for payload verification." % (mapped_keys[0],)
472 common.ZipWrite(
473 output_tf_zip,
474 mapped_keys[0],
475 arcname="SYSTEM/etc/update_engine/update-payload-key.pub.pem")
476
Doug Zongker412c02f2014-02-13 10:58:24 -0800477 return new_recovery_keys
478
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700479def ReplaceVerityPublicKey(targetfile_zip, filename, key_path):
Geremy Condraf19b3652014-07-29 17:54:54 -0700480 print "Replacing verity public key with %s" % key_path
481 with open(key_path) as f:
Andrew Boied083f0b2014-09-15 16:01:07 -0700482 data = f.read()
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700483 common.ZipWriteStr(targetfile_zip, filename, data)
Andrew Boied083f0b2014-09-15 16:01:07 -0700484 return data
Geremy Condraf19b3652014-07-29 17:54:54 -0700485
Dan Albert8b72aef2015-03-23 19:13:21 -0700486def ReplaceVerityPrivateKey(targetfile_input_zip, targetfile_output_zip,
487 misc_info, key_path):
Geremy Condraf19b3652014-07-29 17:54:54 -0700488 print "Replacing verity private key with %s" % key_path
489 current_key = misc_info["verity_key"]
490 original_misc_info = targetfile_input_zip.read("META/misc_info.txt")
491 new_misc_info = original_misc_info.replace(current_key, key_path)
492 common.ZipWriteStr(targetfile_output_zip, "META/misc_info.txt", new_misc_info)
Andrew Boied083f0b2014-09-15 16:01:07 -0700493 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700494
Doug Zongker831840e2011-09-22 10:28:04 -0700495def BuildKeyMap(misc_info, key_mapping_options):
496 for s, d in key_mapping_options:
497 if s is None: # -d option
498 devkey = misc_info.get("default_system_dev_certificate",
499 "build/target/product/security/testkey")
500 devkeydir = os.path.dirname(devkey)
501
502 OPTIONS.key_map.update({
503 devkeydir + "/testkey": d + "/releasekey",
504 devkeydir + "/devkey": d + "/releasekey",
505 devkeydir + "/media": d + "/media",
506 devkeydir + "/shared": d + "/shared",
507 devkeydir + "/platform": d + "/platform",
508 })
509 else:
510 OPTIONS.key_map[s] = d
511
512
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800513def GetApiLevelAndCodename(input_tf_zip):
514 data = input_tf_zip.read("SYSTEM/build.prop")
515 api_level = None
516 codename = None
517 for line in data.split("\n"):
518 line = line.strip()
519 original_line = line
520 if line and line[0] != '#' and "=" in line:
521 key, value = line.split("=", 1)
522 key = key.strip()
523 if key == "ro.build.version.sdk":
524 api_level = int(value.strip())
525 elif key == "ro.build.version.codename":
526 codename = value.strip()
527
528 if api_level is None:
529 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
530 if codename is None:
531 raise ValueError("No ro.build.version.codename in SYSTEM/build.prop")
532
533 return (api_level, codename)
534
535
536def GetCodenameToApiLevelMap(input_tf_zip):
537 data = input_tf_zip.read("SYSTEM/build.prop")
538 api_level = None
539 codenames = None
540 for line in data.split("\n"):
541 line = line.strip()
542 original_line = line
543 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.all_codenames":
549 codenames = value.strip().split(",")
550
551 if api_level is None:
552 raise ValueError("No ro.build.version.sdk in SYSTEM/build.prop")
553 if codenames is None:
554 raise ValueError("No ro.build.version.all_codenames in SYSTEM/build.prop")
555
556 result = dict()
557 for codename in codenames:
558 codename = codename.strip()
559 if len(codename) > 0:
560 result[codename] = api_level
561 return result
562
563
Doug Zongkereef39442009-04-02 12:14:19 -0700564def main(argv):
565
Doug Zongker831840e2011-09-22 10:28:04 -0700566 key_mapping_options = []
567
Doug Zongkereef39442009-04-02 12:14:19 -0700568 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700569 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700570 names, key = a.split("=")
571 names = names.split(",")
572 for n in names:
573 OPTIONS.extra_apks[n] = key
574 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700575 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700576 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700577 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700578 elif o in ("-o", "--replace_ota_keys"):
579 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700580 elif o in ("-t", "--tag_changes"):
581 new = []
582 for i in a.split(","):
583 i = i.strip()
584 if not i or i[0] not in "-+":
585 raise ValueError("Bad tag change '%s'" % (i,))
586 new.append(i[0] + i[1:].strip())
587 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700588 elif o == "--replace_verity_public_key":
589 OPTIONS.replace_verity_public_key = (True, a)
590 elif o == "--replace_verity_private_key":
591 OPTIONS.replace_verity_private_key = (True, a)
Doug Zongkereef39442009-04-02 12:14:19 -0700592 else:
593 return False
594 return True
595
596 args = common.ParseOptions(argv, __doc__,
Doug Zongker05d3dea2009-06-22 11:32:31 -0700597 extra_opts="e:d:k:ot:",
598 extra_long_opts=["extra_apks=",
Doug Zongkereef39442009-04-02 12:14:19 -0700599 "default_key_mappings=",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700600 "key_mapping=",
Doug Zongker17aa9442009-04-17 10:15:58 -0700601 "replace_ota_keys",
Geremy Condraf19b3652014-07-29 17:54:54 -0700602 "tag_changes=",
603 "replace_verity_public_key=",
604 "replace_verity_private_key="],
Doug Zongkereef39442009-04-02 12:14:19 -0700605 extra_option_handler=option_handler)
606
607 if len(args) != 2:
608 common.Usage(__doc__)
609 sys.exit(1)
610
611 input_zip = zipfile.ZipFile(args[0], "r")
612 output_zip = zipfile.ZipFile(args[1], "w")
613
Doug Zongker831840e2011-09-22 10:28:04 -0700614 misc_info = common.LoadInfoDict(input_zip)
615
616 BuildKeyMap(misc_info, key_mapping_options)
617
Doug Zongkereb338ef2009-05-20 16:50:49 -0700618 apk_key_map = GetApkCerts(input_zip)
619 CheckAllApksSigned(input_zip, apk_key_map)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700620
621 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800622 platform_api_level, platform_codename = GetApiLevelAndCodename(input_zip)
623 codename_to_api_level_map = GetCodenameToApiLevelMap(input_zip)
624 # Android N will be API Level 24, but isn't yet.
625 # TODO: Remove this workaround once Android N is officially API Level 24.
626 if platform_api_level == 23 and platform_codename == "N":
627 platform_api_level = 24
628
Doug Zongker412c02f2014-02-13 10:58:24 -0800629 ProcessTargetFiles(input_zip, output_zip, misc_info,
Alex Klyubin2cfd1d12016-01-13 10:32:47 -0800630 apk_key_map, key_passwords,
631 platform_api_level,
632 codename_to_api_level_map)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700633
Tao Bao2ed665a2015-04-01 11:21:55 -0700634 common.ZipClose(input_zip)
635 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700636
Doug Zongker3c84f562014-07-31 11:06:30 -0700637 add_img_to_target_files.AddImagesToTargetFiles(args[1])
638
Doug Zongkereef39442009-04-02 12:14:19 -0700639 print "done."
640
641
642if __name__ == '__main__':
643 try:
644 main(sys.argv[1:])
645 except common.ExternalError, e:
646 print
647 print " ERROR: %s" % (e,)
648 print
649 sys.exit(1)