blob: 33fcf22d8ff45000b01d38666877a40e718b46b9 [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
23 -s (--signapk_jar) <path>
24 Path of the signapks.jar file used to sign an individual APK
25 file.
26
27 -e (--extra_apks) <name,name,...=key>
28 Add extra APK name/key pairs as though they appeared in
29 apkcerts.zip. Option may be repeated to give multiple extra
30 packages.
31
32 -k (--key_mapping) <src_key=dest_key>
33 Add a mapping from the key name as specified in apkcerts.txt (the
34 src_key) to the real key you wish to sign the package with
35 (dest_key). Option may be repeated to give multiple key
36 mappings.
37
38 -d (--default_key_mappings) <dir>
39 Set up the following key mappings:
40
41 build/target/product/security/testkey ==> $dir/releasekey
42 build/target/product/security/media ==> $dir/media
43 build/target/product/security/shared ==> $dir/shared
44 build/target/product/security/platform ==> $dir/platform
45
46 -d and -k options are added to the set of mappings in the order
47 in which they appear on the command line.
Doug Zongker8e931bf2009-04-06 15:21:45 -070048
49 -o (--replace_ota_keys)
50 Replace the certificate (public key) used by OTA package
51 verification with the one specified in the input target_files
52 zip (in the META/otakeys.txt file). Key remapping (-k and -d)
53 is performed on this key.
Doug Zongkereef39442009-04-02 12:14:19 -070054"""
55
56import sys
57
58if sys.hexversion < 0x02040000:
59 print >> sys.stderr, "Python 2.4 or newer is required."
60 sys.exit(1)
61
Doug Zongker8e931bf2009-04-06 15:21:45 -070062import cStringIO
63import copy
Doug Zongkereef39442009-04-02 12:14:19 -070064import os
65import re
66import subprocess
67import tempfile
68import zipfile
69
70import common
71
72OPTIONS = common.OPTIONS
73
74OPTIONS.extra_apks = {}
75OPTIONS.key_map = {}
Doug Zongker8e931bf2009-04-06 15:21:45 -070076OPTIONS.replace_ota_keys = False
Doug Zongkereef39442009-04-02 12:14:19 -070077
78def GetApkCerts(tf_zip):
79 certmap = OPTIONS.extra_apks.copy()
80 for line in tf_zip.read("META/apkcerts.txt").split("\n"):
81 line = line.strip()
82 if not line: continue
83 m = re.match(r'^name="(.*)"\s+certificate="(.*)\.x509\.pem"\s+'
84 r'private_key="\2\.pk8"$', line)
85 if not m:
86 raise SigningError("failed to parse line from apkcerts.txt:\n" + line)
87 certmap[m.group(1)] = OPTIONS.key_map.get(m.group(2), m.group(2))
88 return certmap
89
90
91def SignApk(data, keyname, pw):
92 unsigned = tempfile.NamedTemporaryFile()
93 unsigned.write(data)
94 unsigned.flush()
95
96 signed = tempfile.NamedTemporaryFile()
97
98 common.SignFile(unsigned.name, signed.name, keyname, pw, align=4)
99
100 data = signed.read()
101 unsigned.close()
102 signed.close()
103
104 return data
105
106
107def SignApks(input_tf_zip, output_tf_zip):
108 apk_key_map = GetApkCerts(input_tf_zip)
109
110 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
111
112 maxsize = max([len(os.path.basename(i.filename))
113 for i in input_tf_zip.infolist()
114 if i.filename.endswith('.apk')])
115
116 for info in input_tf_zip.infolist():
117 data = input_tf_zip.read(info.filename)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700118 out_info = copy.copy(info)
Doug Zongkereef39442009-04-02 12:14:19 -0700119 if info.filename.endswith(".apk"):
120 name = os.path.basename(info.filename)
121 key = apk_key_map.get(name, None)
122 if key is not None:
123 print "signing: %-*s (%s)" % (maxsize, name, key)
124 signed_data = SignApk(data, key, key_passwords[key])
Doug Zongker8e931bf2009-04-06 15:21:45 -0700125 output_tf_zip.writestr(out_info, signed_data)
Doug Zongkereef39442009-04-02 12:14:19 -0700126 else:
127 # an APK we're not supposed to sign.
128 print "skipping: %s" % (name,)
Doug Zongker8e931bf2009-04-06 15:21:45 -0700129 output_tf_zip.writestr(out_info, data)
130 elif info.filename in ("SYSTEM/build.prop",
131 "RECOVERY/RAMDISK/default.prop"):
Doug Zongkereef39442009-04-02 12:14:19 -0700132 # Change build fingerprint to reflect the fact that apps are signed.
133 m = re.search(r"ro\.build\.fingerprint=.*\b(test-keys)\b.*", data)
134 if not m:
135 print 'WARNING: ro.build.fingerprint does not contain "test-keys"'
136 else:
137 data = data[:m.start(1)] + "release-keys" + data[m.end(1):]
138 m = re.search(r"ro\.build\.description=.*\b(test-keys)\b.*", data)
139 if not m:
140 print 'WARNING: ro.build.description does not contain "test-keys"'
141 else:
142 data = data[:m.start(1)] + "release-keys" + data[m.end(1):]
Doug Zongker8e931bf2009-04-06 15:21:45 -0700143 output_tf_zip.writestr(out_info, data)
Doug Zongkereef39442009-04-02 12:14:19 -0700144 else:
145 # a non-APK file; copy it verbatim
Doug Zongker8e931bf2009-04-06 15:21:45 -0700146 output_tf_zip.writestr(out_info, data)
147
148
149def ReplaceOtaKeys(input_tf_zip, output_tf_zip):
150 try:
151 keylist = input_tf_zip.read("META/otakeys.txt").split()
152 except KeyError:
153 raise ExternalError("can't read META/otakeys.txt from input")
154
155 mapped_keys = []
156 for k in keylist:
157 m = re.match(r"^(.*)\.x509\.pem$", k)
158 if not m:
159 raise ExternalError("can't parse \"%s\" from META/otakeys.txt" % (k,))
160 k = m.group(1)
161 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
162
163 print "using:\n ", "\n ".join(mapped_keys)
164 print "for OTA package verification"
165
166 # recovery uses a version of the key that has been slightly
167 # predigested (by DumpPublicKey.java) and put in res/keys.
168
169 p = common.Run(["java", "-jar", OPTIONS.dumpkey_jar] + mapped_keys,
170 stdout=subprocess.PIPE)
171 data, _ = p.communicate()
172 if p.returncode != 0:
173 raise ExternalError("failed to run dumpkeys")
174 output_tf_zip.writestr("RECOVERY/RAMDISK/res/keys", data)
175
176 # SystemUpdateActivity uses the x509.pem version of the keys, but
177 # put into a zipfile system/etc/security/otacerts.zip.
178
179 tempfile = cStringIO.StringIO()
180 certs_zip = zipfile.ZipFile(tempfile, "w")
181 for k in mapped_keys:
182 certs_zip.write(k)
183 certs_zip.close()
184 output_tf_zip.writestr("SYSTEM/etc/security/otacerts.zip",
185 tempfile.getvalue())
Doug Zongkereef39442009-04-02 12:14:19 -0700186
187
188def main(argv):
189
190 def option_handler(o, a):
191 if o in ("-s", "--signapk_jar"):
192 OPTIONS.signapk_jar = a
193 elif o in ("-e", "--extra_apks"):
194 names, key = a.split("=")
195 names = names.split(",")
196 for n in names:
197 OPTIONS.extra_apks[n] = key
198 elif o in ("-d", "--default_key_mappings"):
199 OPTIONS.key_map.update({
200 "build/target/product/security/testkey": "%s/releasekey" % (a,),
201 "build/target/product/security/media": "%s/media" % (a,),
202 "build/target/product/security/shared": "%s/shared" % (a,),
203 "build/target/product/security/platform": "%s/platform" % (a,),
204 })
205 elif o in ("-k", "--key_mapping"):
206 s, d = a.split("=")
207 OPTIONS.key_map[s] = d
Doug Zongker8e931bf2009-04-06 15:21:45 -0700208 elif o in ("-o", "--replace_ota_keys"):
209 OPTIONS.replace_ota_keys = True
Doug Zongkereef39442009-04-02 12:14:19 -0700210 else:
211 return False
212 return True
213
214 args = common.ParseOptions(argv, __doc__,
Doug Zongker8e931bf2009-04-06 15:21:45 -0700215 extra_opts="s:e:d:k:o",
Doug Zongkereef39442009-04-02 12:14:19 -0700216 extra_long_opts=["signapk_jar=",
217 "extra_apks=",
218 "default_key_mappings=",
Doug Zongker8e931bf2009-04-06 15:21:45 -0700219 "key_mapping=",
220 "replace_ota_keys"],
Doug Zongkereef39442009-04-02 12:14:19 -0700221 extra_option_handler=option_handler)
222
223 if len(args) != 2:
224 common.Usage(__doc__)
225 sys.exit(1)
226
227 input_zip = zipfile.ZipFile(args[0], "r")
228 output_zip = zipfile.ZipFile(args[1], "w")
229
230 SignApks(input_zip, output_zip)
231
Doug Zongker8e931bf2009-04-06 15:21:45 -0700232 if OPTIONS.replace_ota_keys:
233 ReplaceOtaKeys(input_zip, output_zip)
234
Doug Zongkereef39442009-04-02 12:14:19 -0700235 input_zip.close()
236 output_zip.close()
237
238 print "done."
239
240
241if __name__ == '__main__':
242 try:
243 main(sys.argv[1:])
244 except common.ExternalError, e:
245 print
246 print " ERROR: %s" % (e,)
247 print
248 sys.exit(1)