blob: e98eb8f5e460ad2ec551bba69fef1bb89bf82e0a [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)
54 Replace the certificate (public key) used by OTA package
55 verification with the one specified in the input target_files
56 zip (in the META/otakeys.txt file). Key remapping (-k and -d)
57 is performed on this key.
Doug Zongker17aa9442009-04-17 10:15:58 -070058
Doug Zongkerae877012009-04-21 10:04:51 -070059 -t (--tag_changes) <+tag>,<-tag>,...
60 Comma-separated list of changes to make to the set of tags (in
61 the last component of the build fingerprint). Prefix each with
62 '+' or '-' to indicate whether that tag should be added or
63 removed. Changes are processed in the order they appear.
Doug Zongker831840e2011-09-22 10:28:04 -070064 Default value is "-test-keys,-dev-keys,+release-keys".
Doug Zongkerae877012009-04-21 10:04:51 -070065
Doug Zongkereef39442009-04-02 12:14:19 -070066"""
67
68import sys
69
Doug Zongkercf6d5a92014-02-18 10:57:07 -080070if sys.hexversion < 0x02070000:
71 print >> sys.stderr, "Python 2.7 or newer is required."
Doug Zongkereef39442009-04-02 12:14:19 -070072 sys.exit(1)
73
Robert Craig817c5742013-04-19 10:59:22 -040074import base64
Doug Zongker8e931bf2009-04-06 15:21:45 -070075import cStringIO
76import copy
Robert Craig817c5742013-04-19 10:59:22 -040077import errno
Doug Zongkereef39442009-04-02 12:14:19 -070078import os
79import re
Doug Zongker412c02f2014-02-13 10:58:24 -080080import shutil
Doug Zongkereef39442009-04-02 12:14:19 -070081import subprocess
82import tempfile
83import zipfile
84
Doug Zongker3c84f562014-07-31 11:06:30 -070085import add_img_to_target_files
Doug Zongkereef39442009-04-02 12:14:19 -070086import common
87
88OPTIONS = common.OPTIONS
89
90OPTIONS.extra_apks = {}
91OPTIONS.key_map = {}
Doug Zongker8e931bf2009-04-06 15:21:45 -070092OPTIONS.replace_ota_keys = False
Geremy Condraf19b3652014-07-29 17:54:54 -070093OPTIONS.replace_verity_public_key = False
94OPTIONS.replace_verity_private_key = False
Doug Zongker831840e2011-09-22 10:28:04 -070095OPTIONS.tag_changes = ("-test-keys", "-dev-keys", "+release-keys")
Doug Zongkereef39442009-04-02 12:14:19 -070096
97def GetApkCerts(tf_zip):
Doug Zongkerf6a53aa2009-12-15 15:06:55 -080098 certmap = common.ReadApkCerts(tf_zip)
99
100 # apply the key remapping to the contents of the file
101 for apk, cert in certmap.iteritems():
102 certmap[apk] = OPTIONS.key_map.get(cert, cert)
103
104 # apply all the -e options, overriding anything in the file
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700105 for apk, cert in OPTIONS.extra_apks.iteritems():
Doug Zongkerdecf9952009-12-15 17:27:49 -0800106 if not cert:
107 cert = "PRESIGNED"
Doug Zongkerad88c7c2009-04-14 12:34:27 -0700108 certmap[apk] = OPTIONS.key_map.get(cert, cert)
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800109
Doug Zongkereef39442009-04-02 12:14:19 -0700110 return certmap
111
112
Doug Zongkereb338ef2009-05-20 16:50:49 -0700113def CheckAllApksSigned(input_tf_zip, apk_key_map):
114 """Check that all the APKs we want to sign have keys specified, and
115 error out if they don't."""
116 unknown_apks = []
117 for info in input_tf_zip.infolist():
118 if info.filename.endswith(".apk"):
119 name = os.path.basename(info.filename)
120 if name not in apk_key_map:
121 unknown_apks.append(name)
122 if unknown_apks:
123 print "ERROR: no key specified for:\n\n ",
124 print "\n ".join(unknown_apks)
125 print "\nUse '-e <apkname>=' to specify a key (which may be an"
126 print "empty string to not sign this apk)."
127 sys.exit(1)
128
129
Doug Zongkereef39442009-04-02 12:14:19 -0700130def SignApk(data, keyname, pw):
131 unsigned = tempfile.NamedTemporaryFile()
132 unsigned.write(data)
133 unsigned.flush()
134
135 signed = tempfile.NamedTemporaryFile()
136
137 common.SignFile(unsigned.name, signed.name, keyname, pw, align=4)
138
139 data = signed.read()
140 unsigned.close()
141 signed.close()
142
143 return data
144
145
Doug Zongker412c02f2014-02-13 10:58:24 -0800146def ProcessTargetFiles(input_tf_zip, output_tf_zip, misc_info,
147 apk_key_map, key_passwords):
Michael Rungedc2661a2014-06-03 14:43:11 -0700148
Doug Zongkereef39442009-04-02 12:14:19 -0700149 maxsize = max([len(os.path.basename(i.filename))
150 for i in input_tf_zip.infolist()
151 if i.filename.endswith('.apk')])
Doug Zongker412c02f2014-02-13 10:58:24 -0800152 rebuild_recovery = False
153
154 tmpdir = tempfile.mkdtemp()
155 def write_to_temp(fn, attr, data):
156 fn = os.path.join(tmpdir, fn)
157 if fn.endswith("/"):
158 fn = os.path.join(tmpdir, fn)
159 os.mkdir(fn)
160 else:
161 d = os.path.dirname(fn)
162 if d and not os.path.exists(d):
163 os.makedirs(d)
164
165 if attr >> 16 == 0xa1ff:
166 os.symlink(data, fn)
167 else:
168 with open(fn, "wb") as f:
169 f.write(data)
Doug Zongkereef39442009-04-02 12:14:19 -0700170
171 for info in input_tf_zip.infolist():
Dan Albert8b72aef2015-03-23 19:13:21 -0700172 if info.filename.startswith("IMAGES/"):
173 continue
Doug Zongker3c84f562014-07-31 11:06:30 -0700174
Doug Zongkereef39442009-04-02 12:14:19 -0700175 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700176 out_info = copy.copy(info)
Doug Zongker412c02f2014-02-13 10:58:24 -0800177
Tao Baof2cffbd2015-07-22 12:33:18 -0700178 # Replace keys if requested.
Geremy Condraf19b3652014-07-29 17:54:54 -0700179 if (info.filename == "META/misc_info.txt" and
Michael Runge947894f2014-10-14 20:58:38 -0700180 OPTIONS.replace_verity_private_key):
Dan Albert8b72aef2015-03-23 19:13:21 -0700181 ReplaceVerityPrivateKey(input_tf_zip, output_tf_zip, misc_info,
182 OPTIONS.replace_verity_private_key[1])
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700183 elif (info.filename in ("BOOT/RAMDISK/verity_key",
184 "BOOT/verity_key") and
Dan Albert8b72aef2015-03-23 19:13:21 -0700185 OPTIONS.replace_verity_public_key):
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700186 new_data = ReplaceVerityPublicKey(output_tf_zip, info.filename,
Dan Albert8b72aef2015-03-23 19:13:21 -0700187 OPTIONS.replace_verity_public_key[1])
Andrew Boied083f0b2014-09-15 16:01:07 -0700188 write_to_temp(info.filename, info.external_attr, new_data)
Tao Baof2cffbd2015-07-22 12:33:18 -0700189 # Copy BOOT/, RECOVERY/, META/, ROOT/ to rebuild recovery patch.
Geremy Condraf19b3652014-07-29 17:54:54 -0700190 elif (info.filename.startswith("BOOT/") or
Dan Albert8b72aef2015-03-23 19:13:21 -0700191 info.filename.startswith("RECOVERY/") or
192 info.filename.startswith("META/") or
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700193 info.filename.startswith("ROOT/") or
Dan Albert8b72aef2015-03-23 19:13:21 -0700194 info.filename == "SYSTEM/etc/recovery-resource.dat"):
Doug Zongker412c02f2014-02-13 10:58:24 -0800195 write_to_temp(info.filename, info.external_attr, data)
196
Tao Baof2cffbd2015-07-22 12:33:18 -0700197 # Sign APKs.
Doug Zongkereef39442009-04-02 12:14:19 -0700198 if info.filename.endswith(".apk"):
199 name = os.path.basename(info.filename)
Doug Zongker43874f82009-04-14 14:05:15 -0700200 key = apk_key_map[name]
Doug Zongkerf6a53aa2009-12-15 15:06:55 -0800201 if key not in common.SPECIAL_CERT_STRINGS:
Doug Zongker43874f82009-04-14 14:05:15 -0700202 print " signing: %-*s (%s)" % (maxsize, name, key)
Doug Zongkereef39442009-04-02 12:14:19 -0700203 signed_data = SignApk(data, key, key_passwords[key])
Tao Bao2ed665a2015-04-01 11:21:55 -0700204 common.ZipWriteStr(output_tf_zip, out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700205 else:
206 # an APK we're not supposed to sign.
Doug Zongker43874f82009-04-14 14:05:15 -0700207 print "NOT signing: %s" % (name,)
Tao Bao2ed665a2015-04-01 11:21:55 -0700208 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700209 elif info.filename in ("SYSTEM/build.prop",
Jesse Zhao2625d272015-02-06 09:49:55 -0800210 "VENDOR/build.prop",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700211 "RECOVERY/RAMDISK/default.prop"):
Doug Zongker17aa9442009-04-17 10:15:58 -0700212 print "rewriting %s:" % (info.filename,)
Michael Rungedc2661a2014-06-03 14:43:11 -0700213 new_data = RewriteProps(data, misc_info)
Tao Bao2ed665a2015-04-01 11:21:55 -0700214 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Doug Zongker412c02f2014-02-13 10:58:24 -0800215 if info.filename == "RECOVERY/RAMDISK/default.prop":
216 write_to_temp(info.filename, info.external_attr, new_data)
Robert Craig817c5742013-04-19 10:59:22 -0400217 elif info.filename.endswith("mac_permissions.xml"):
218 print "rewriting %s with new keys." % (info.filename,)
219 new_data = ReplaceCerts(data)
Tao Bao2ed665a2015-04-01 11:21:55 -0700220 common.ZipWriteStr(output_tf_zip, out_info, new_data)
Doug Zongker412c02f2014-02-13 10:58:24 -0800221 elif info.filename in ("SYSTEM/recovery-from-boot.p",
Tao Baof2cffbd2015-07-22 12:33:18 -0700222 "SYSTEM/etc/recovery.img",
Doug Zongker412c02f2014-02-13 10:58:24 -0800223 "SYSTEM/bin/install-recovery.sh"):
224 rebuild_recovery = True
225 elif (OPTIONS.replace_ota_keys and
226 info.filename in ("RECOVERY/RAMDISK/res/keys",
227 "SYSTEM/etc/security/otacerts.zip")):
228 # don't copy these files if we're regenerating them below
229 pass
Michael Runge947894f2014-10-14 20:58:38 -0700230 elif (OPTIONS.replace_verity_private_key and
Geremy Condraf19b3652014-07-29 17:54:54 -0700231 info.filename == "META/misc_info.txt"):
232 pass
Michael Runge947894f2014-10-14 20:58:38 -0700233 elif (OPTIONS.replace_verity_public_key and
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700234 info.filename in ("BOOT/RAMDISK/verity_key",
235 "BOOT/verity_key")):
Geremy Condraf19b3652014-07-29 17:54:54 -0700236 pass
Doug Zongkereef39442009-04-02 12:14:19 -0700237 else:
238 # a non-APK file; copy it verbatim
Tao Bao2ed665a2015-04-01 11:21:55 -0700239 common.ZipWriteStr(output_tf_zip, out_info, data)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700240
Doug Zongker412c02f2014-02-13 10:58:24 -0800241 if OPTIONS.replace_ota_keys:
242 new_recovery_keys = ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info)
243 if new_recovery_keys:
Dan Albert8b72aef2015-03-23 19:13:21 -0700244 write_to_temp("RECOVERY/RAMDISK/res/keys", 0o755 << 16, new_recovery_keys)
Doug Zongker412c02f2014-02-13 10:58:24 -0800245
246 if rebuild_recovery:
247 recovery_img = common.GetBootableImage(
248 "recovery.img", "recovery.img", tmpdir, "RECOVERY", info_dict=misc_info)
249 boot_img = common.GetBootableImage(
250 "boot.img", "boot.img", tmpdir, "BOOT", info_dict=misc_info)
251
252 def output_sink(fn, data):
Tao Bao2ed665a2015-04-01 11:21:55 -0700253 common.ZipWriteStr(output_tf_zip, "SYSTEM/" + fn, data)
Doug Zongker412c02f2014-02-13 10:58:24 -0800254
255 common.MakeRecoveryPatch(tmpdir, output_sink, recovery_img, boot_img,
256 info_dict=misc_info)
257
258 shutil.rmtree(tmpdir)
259
Doug Zongker8e931bf2009-04-06 15:21:45 -0700260
Robert Craig817c5742013-04-19 10:59:22 -0400261def ReplaceCerts(data):
262 """Given a string of data, replace all occurences of a set
263 of X509 certs with a newer set of X509 certs and return
264 the updated data string."""
265 for old, new in OPTIONS.key_map.iteritems():
266 try:
267 if OPTIONS.verbose:
268 print " Replacing %s.x509.pem with %s.x509.pem" % (old, new)
269 f = open(old + ".x509.pem")
270 old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
271 f.close()
272 f = open(new + ".x509.pem")
273 new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
274 f.close()
275 # Only match entire certs.
276 pattern = "\\b"+old_cert16+"\\b"
277 (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
278 if OPTIONS.verbose:
279 print " Replaced %d occurence(s) of %s.x509.pem with " \
280 "%s.x509.pem" % (num, old, new)
Dan Albert8b72aef2015-03-23 19:13:21 -0700281 except IOError as e:
282 if e.errno == errno.ENOENT and not OPTIONS.verbose:
Robert Craig817c5742013-04-19 10:59:22 -0400283 continue
284
285 print " Error accessing %s. %s. Skip replacing %s.x509.pem " \
286 "with %s.x509.pem." % (e.filename, e.strerror, old, new)
287
288 return data
289
290
Doug Zongkerc09abc82010-01-11 13:09:15 -0800291def EditTags(tags):
292 """Given a string containing comma-separated tags, apply the edits
293 specified in OPTIONS.tag_changes and return the updated string."""
294 tags = set(tags.split(","))
295 for ch in OPTIONS.tag_changes:
296 if ch[0] == "-":
297 tags.discard(ch[1:])
298 elif ch[0] == "+":
299 tags.add(ch[1:])
300 return ",".join(sorted(tags))
301
302
Michael Rungedc2661a2014-06-03 14:43:11 -0700303def RewriteProps(data, misc_info):
Doug Zongker17aa9442009-04-17 10:15:58 -0700304 output = []
305 for line in data.split("\n"):
306 line = line.strip()
307 original_line = line
Michael Rungedc2661a2014-06-03 14:43:11 -0700308 if line and line[0] != '#' and "=" in line:
Doug Zongker17aa9442009-04-17 10:15:58 -0700309 key, value = line.split("=", 1)
Michael Rungee07c75a2014-12-09 13:54:23 -0800310 if (key in ("ro.build.fingerprint", "ro.vendor.build.fingerprint")
Michael Rungedc2661a2014-06-03 14:43:11 -0700311 and misc_info.get("oem_fingerprint_properties") is None):
312 pieces = value.split("/")
313 pieces[-1] = EditTags(pieces[-1])
314 value = "/".join(pieces)
Michael Rungee07c75a2014-12-09 13:54:23 -0800315 elif (key in ("ro.build.thumbprint", "ro.vendor.build.thumbprint")
Dan Albert8b72aef2015-03-23 19:13:21 -0700316 and misc_info.get("oem_fingerprint_properties") is not None):
Doug Zongkerc09abc82010-01-11 13:09:15 -0800317 pieces = value.split("/")
318 pieces[-1] = EditTags(pieces[-1])
319 value = "/".join(pieces)
Doug Zongker17aa9442009-04-17 10:15:58 -0700320 elif key == "ro.build.description":
Doug Zongkerc09abc82010-01-11 13:09:15 -0800321 pieces = value.split(" ")
Doug Zongker17aa9442009-04-17 10:15:58 -0700322 assert len(pieces) == 5
Doug Zongkerc09abc82010-01-11 13:09:15 -0800323 pieces[-1] = EditTags(pieces[-1])
324 value = " ".join(pieces)
325 elif key == "ro.build.tags":
326 value = EditTags(value)
Doug Zongkera8608a72013-07-23 11:51:04 -0700327 elif key == "ro.build.display.id":
328 # change, eg, "JWR66N dev-keys" to "JWR66N"
329 value = value.split()
Michael Rungedc2661a2014-06-03 14:43:11 -0700330 if len(value) > 1 and value[-1].endswith("-keys"):
Andrew Boie73d5abb2013-12-11 12:42:03 -0800331 value.pop()
332 value = " ".join(value)
Doug Zongkerc09abc82010-01-11 13:09:15 -0800333 line = key + "=" + value
Doug Zongker17aa9442009-04-17 10:15:58 -0700334 if line != original_line:
335 print " replace: ", original_line
336 print " with: ", line
337 output.append(line)
338 return "\n".join(output) + "\n"
339
340
Doug Zongker831840e2011-09-22 10:28:04 -0700341def ReplaceOtaKeys(input_tf_zip, output_tf_zip, misc_info):
Doug Zongker8e931bf2009-04-06 15:21:45 -0700342 try:
343 keylist = input_tf_zip.read("META/otakeys.txt").split()
344 except KeyError:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700345 raise common.ExternalError("can't read META/otakeys.txt from input")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700346
Doug Zongkere121d6a2011-02-01 14:13:52 -0800347 extra_recovery_keys = misc_info.get("extra_recovery_keys", None)
348 if extra_recovery_keys:
349 extra_recovery_keys = [OPTIONS.key_map.get(k, k) + ".x509.pem"
350 for k in extra_recovery_keys.split()]
351 if extra_recovery_keys:
352 print "extra recovery-only key(s): " + ", ".join(extra_recovery_keys)
353 else:
354 extra_recovery_keys = []
355
Doug Zongker8e931bf2009-04-06 15:21:45 -0700356 mapped_keys = []
357 for k in keylist:
358 m = re.match(r"^(.*)\.x509\.pem$", k)
359 if not m:
Doug Zongker412c02f2014-02-13 10:58:24 -0800360 raise common.ExternalError(
361 "can't parse \"%s\" from META/otakeys.txt" % (k,))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700362 k = m.group(1)
363 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
364
Doug Zongkere05628c2009-08-20 17:38:42 -0700365 if mapped_keys:
366 print "using:\n ", "\n ".join(mapped_keys)
367 print "for OTA package verification"
368 else:
Doug Zongker831840e2011-09-22 10:28:04 -0700369 devkey = misc_info.get("default_system_dev_certificate",
370 "build/target/product/security/testkey")
Doug Zongkere05628c2009-08-20 17:38:42 -0700371 mapped_keys.append(
Doug Zongker831840e2011-09-22 10:28:04 -0700372 OPTIONS.key_map.get(devkey, devkey) + ".x509.pem")
Doug Zongkere05628c2009-08-20 17:38:42 -0700373 print "META/otakeys.txt has no keys; using", mapped_keys[0]
Doug Zongker8e931bf2009-04-06 15:21:45 -0700374
375 # recovery uses a version of the key that has been slightly
376 # predigested (by DumpPublicKey.java) and put in res/keys.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800377 # extra_recovery_keys are used only in recovery.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700378
Doug Zongker602a84e2009-06-18 08:35:12 -0700379 p = common.Run(["java", "-jar",
380 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")]
Doug Zongkere121d6a2011-02-01 14:13:52 -0800381 + mapped_keys + extra_recovery_keys,
Doug Zongker8e931bf2009-04-06 15:21:45 -0700382 stdout=subprocess.PIPE)
Doug Zongker412c02f2014-02-13 10:58:24 -0800383 new_recovery_keys, _ = p.communicate()
Doug Zongker8e931bf2009-04-06 15:21:45 -0700384 if p.returncode != 0:
T.R. Fullharta28acc62013-03-18 10:31:26 -0700385 raise common.ExternalError("failed to run dumpkeys")
Doug Zongker412c02f2014-02-13 10:58:24 -0800386 common.ZipWriteStr(output_tf_zip, "RECOVERY/RAMDISK/res/keys",
387 new_recovery_keys)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700388
389 # SystemUpdateActivity uses the x509.pem version of the keys, but
390 # put into a zipfile system/etc/security/otacerts.zip.
Doug Zongkere121d6a2011-02-01 14:13:52 -0800391 # We DO NOT include the extra_recovery_keys (if any) here.
Doug Zongker8e931bf2009-04-06 15:21:45 -0700392
Dan Albert8b72aef2015-03-23 19:13:21 -0700393 temp_file = cStringIO.StringIO()
394 certs_zip = zipfile.ZipFile(temp_file, "w")
Doug Zongker8e931bf2009-04-06 15:21:45 -0700395 for k in mapped_keys:
396 certs_zip.write(k)
397 certs_zip.close()
Doug Zongker048e7ca2009-06-15 14:31:53 -0700398 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
Dan Albert8b72aef2015-03-23 19:13:21 -0700399 temp_file.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700400
Doug Zongker412c02f2014-02-13 10:58:24 -0800401 return new_recovery_keys
402
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700403def ReplaceVerityPublicKey(targetfile_zip, filename, key_path):
Geremy Condraf19b3652014-07-29 17:54:54 -0700404 print "Replacing verity public key with %s" % key_path
405 with open(key_path) as f:
Andrew Boied083f0b2014-09-15 16:01:07 -0700406 data = f.read()
Tao Bao7a5bf8a2015-07-21 18:01:20 -0700407 common.ZipWriteStr(targetfile_zip, filename, data)
Andrew Boied083f0b2014-09-15 16:01:07 -0700408 return data
Geremy Condraf19b3652014-07-29 17:54:54 -0700409
Dan Albert8b72aef2015-03-23 19:13:21 -0700410def ReplaceVerityPrivateKey(targetfile_input_zip, targetfile_output_zip,
411 misc_info, key_path):
Geremy Condraf19b3652014-07-29 17:54:54 -0700412 print "Replacing verity private key with %s" % key_path
413 current_key = misc_info["verity_key"]
414 original_misc_info = targetfile_input_zip.read("META/misc_info.txt")
415 new_misc_info = original_misc_info.replace(current_key, key_path)
416 common.ZipWriteStr(targetfile_output_zip, "META/misc_info.txt", new_misc_info)
Andrew Boied083f0b2014-09-15 16:01:07 -0700417 misc_info["verity_key"] = key_path
Doug Zongkereef39442009-04-02 12:14:19 -0700418
Doug Zongker831840e2011-09-22 10:28:04 -0700419def BuildKeyMap(misc_info, key_mapping_options):
420 for s, d in key_mapping_options:
421 if s is None: # -d option
422 devkey = misc_info.get("default_system_dev_certificate",
423 "build/target/product/security/testkey")
424 devkeydir = os.path.dirname(devkey)
425
426 OPTIONS.key_map.update({
427 devkeydir + "/testkey": d + "/releasekey",
428 devkeydir + "/devkey": d + "/releasekey",
429 devkeydir + "/media": d + "/media",
430 devkeydir + "/shared": d + "/shared",
431 devkeydir + "/platform": d + "/platform",
432 })
433 else:
434 OPTIONS.key_map[s] = d
435
436
Doug Zongkereef39442009-04-02 12:14:19 -0700437def main(argv):
438
Doug Zongker831840e2011-09-22 10:28:04 -0700439 key_mapping_options = []
440
Doug Zongkereef39442009-04-02 12:14:19 -0700441 def option_handler(o, a):
Doug Zongker05d3dea2009-06-22 11:32:31 -0700442 if o in ("-e", "--extra_apks"):
Doug Zongkereef39442009-04-02 12:14:19 -0700443 names, key = a.split("=")
444 names = names.split(",")
445 for n in names:
446 OPTIONS.extra_apks[n] = key
447 elif o in ("-d", "--default_key_mappings"):
Doug Zongker831840e2011-09-22 10:28:04 -0700448 key_mapping_options.append((None, a))
Doug Zongkereef39442009-04-02 12:14:19 -0700449 elif o in ("-k", "--key_mapping"):
Doug Zongker831840e2011-09-22 10:28:04 -0700450 key_mapping_options.append(a.split("=", 1))
Doug Zongker8e931bf2009-04-06 15:21:45 -0700451 elif o in ("-o", "--replace_ota_keys"):
452 OPTIONS.replace_ota_keys = True
Doug Zongkerae877012009-04-21 10:04:51 -0700453 elif o in ("-t", "--tag_changes"):
454 new = []
455 for i in a.split(","):
456 i = i.strip()
457 if not i or i[0] not in "-+":
458 raise ValueError("Bad tag change '%s'" % (i,))
459 new.append(i[0] + i[1:].strip())
460 OPTIONS.tag_changes = tuple(new)
Geremy Condraf19b3652014-07-29 17:54:54 -0700461 elif o == "--replace_verity_public_key":
462 OPTIONS.replace_verity_public_key = (True, a)
463 elif o == "--replace_verity_private_key":
464 OPTIONS.replace_verity_private_key = (True, a)
Doug Zongkereef39442009-04-02 12:14:19 -0700465 else:
466 return False
467 return True
468
469 args = common.ParseOptions(argv, __doc__,
Doug Zongker05d3dea2009-06-22 11:32:31 -0700470 extra_opts="e:d:k:ot:",
471 extra_long_opts=["extra_apks=",
Doug Zongkereef39442009-04-02 12:14:19 -0700472 "default_key_mappings=",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700473 "key_mapping=",
Doug Zongker17aa9442009-04-17 10:15:58 -0700474 "replace_ota_keys",
Geremy Condraf19b3652014-07-29 17:54:54 -0700475 "tag_changes=",
476 "replace_verity_public_key=",
477 "replace_verity_private_key="],
Doug Zongkereef39442009-04-02 12:14:19 -0700478 extra_option_handler=option_handler)
479
480 if len(args) != 2:
481 common.Usage(__doc__)
482 sys.exit(1)
483
484 input_zip = zipfile.ZipFile(args[0], "r")
485 output_zip = zipfile.ZipFile(args[1], "w")
486
Doug Zongker831840e2011-09-22 10:28:04 -0700487 misc_info = common.LoadInfoDict(input_zip)
488
489 BuildKeyMap(misc_info, key_mapping_options)
490
Doug Zongkereb338ef2009-05-20 16:50:49 -0700491 apk_key_map = GetApkCerts(input_zip)
492 CheckAllApksSigned(input_zip, apk_key_map)
Doug Zongkereb338ef2009-05-20 16:50:49 -0700493
494 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
Doug Zongker412c02f2014-02-13 10:58:24 -0800495 ProcessTargetFiles(input_zip, output_zip, misc_info,
496 apk_key_map, key_passwords)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700497
Tao Bao2ed665a2015-04-01 11:21:55 -0700498 common.ZipClose(input_zip)
499 common.ZipClose(output_zip)
Doug Zongkereef39442009-04-02 12:14:19 -0700500
Doug Zongker3c84f562014-07-31 11:06:30 -0700501 add_img_to_target_files.AddImagesToTargetFiles(args[1])
502
Doug Zongkereef39442009-04-02 12:14:19 -0700503 print "done."
504
505
506if __name__ == '__main__':
507 try:
508 main(sys.argv[1:])
509 except common.ExternalError, e:
510 print
511 print " ERROR: %s" % (e,)
512 print
513 sys.exit(1)