3 # Copyright (C) 2008 The Android Open Source Project
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
18 Signs all the APK files in a target-files zipfile, producing a new
21 Usage: sign_target_files_apks [flags] input_target_files output_target_files
23 -s (--signapk_jar) <path>
24 Path of the signapks.jar file used to sign an individual APK
27 -e (--extra_apks) <name,name,...=key>
28 Add extra APK name/key pairs as though they appeared in
29 apkcerts.txt (so mappings specified by -k and -d are applied).
30 Keys specified in -e override any value for that app contained
31 in the apkcerts.txt file. Option may be repeated to give
32 multiple extra packages.
34 -k (--key_mapping) <src_key=dest_key>
35 Add a mapping from the key name as specified in apkcerts.txt (the
36 src_key) to the real key you wish to sign the package with
37 (dest_key). Option may be repeated to give multiple key
40 -d (--default_key_mappings) <dir>
41 Set up the following key mappings:
43 build/target/product/security/testkey ==> $dir/releasekey
44 build/target/product/security/media ==> $dir/media
45 build/target/product/security/shared ==> $dir/shared
46 build/target/product/security/platform ==> $dir/platform
48 -d and -k options are added to the set of mappings in the order
49 in which they appear on the command line.
51 -o (--replace_ota_keys)
52 Replace the certificate (public key) used by OTA package
53 verification with the one specified in the input target_files
54 zip (in the META/otakeys.txt file). Key remapping (-k and -d)
55 is performed on this key.
57 -t (--tag_changes) <+tag>,<-tag>,...
58 Comma-separated list of changes to make to the set of tags (in
59 the last component of the build fingerprint). Prefix each with
60 '+' or '-' to indicate whether that tag should be added or
61 removed. Changes are processed in the order they appear.
62 Default value is "-test-keys,+ota-rel-keys,+release-keys".
68 if sys.hexversion < 0x02040000:
69 print >> sys.stderr, "Python 2.4 or newer is required."
82 OPTIONS = common.OPTIONS
84 OPTIONS.extra_apks = {}
86 OPTIONS.replace_ota_keys = False
87 OPTIONS.tag_changes = ("-test-keys", "+ota-rel-keys", "+release-keys")
89 def GetApkCerts(tf_zip):
91 for line in tf_zip.read("META/apkcerts.txt").split("\n"):
94 m = re.match(r'^name="(.*)"\s+certificate="(.*)\.x509\.pem"\s+'
95 r'private_key="\2\.pk8"$', line)
97 raise SigningError("failed to parse line from apkcerts.txt:\n" + line)
98 certmap[m.group(1)] = OPTIONS.key_map.get(m.group(2), m.group(2))
99 for apk, cert in OPTIONS.extra_apks.iteritems():
100 certmap[apk] = OPTIONS.key_map.get(cert, cert)
104 def CheckAllApksSigned(input_tf_zip, apk_key_map):
105 """Check that all the APKs we want to sign have keys specified, and
106 error out if they don't."""
108 for info in input_tf_zip.infolist():
109 if info.filename.endswith(".apk"):
110 name = os.path.basename(info.filename)
111 if name not in apk_key_map:
112 unknown_apks.append(name)
114 print "ERROR: no key specified for:\n\n ",
115 print "\n ".join(unknown_apks)
116 print "\nUse '-e <apkname>=' to specify a key (which may be an"
117 print "empty string to not sign this apk)."
121 def SharedUserForApk(data):
122 tmp = tempfile.NamedTemporaryFile()
126 p = common.Run(["aapt", "dump", "xmltree", tmp.name, "AndroidManifest.xml"],
127 stdout=subprocess.PIPE)
128 data, _ = p.communicate()
129 if p.returncode != 0:
130 raise ExternalError("failed to run aapt dump")
131 lines = data.split("\n")
133 m = re.match(r'^\s*A: android:sharedUserId\([0-9a-fx]*\)="([^"]*)" .*$', i)
139 def CheckSharedUserIdsConsistent(input_tf_zip, apk_key_map):
140 """Check that all packages that request the same shared user id are
141 going to be signed with the same key."""
143 shared_user_apks = {}
144 maxlen = len("(unknown key)")
146 for info in input_tf_zip.infolist():
147 if info.filename.endswith(".apk"):
148 data = input_tf_zip.read(info.filename)
150 name = os.path.basename(info.filename)
151 shared_user = SharedUserForApk(data)
152 key = apk_key_map[name]
153 maxlen = max(maxlen, len(key))
155 if shared_user is not None:
156 shared_user_apks.setdefault(
157 shared_user, {}).setdefault(key, []).append(name)
160 for k, v in shared_user_apks.iteritems():
161 # each shared user should have exactly one key used for all the
162 # apks that want that user.
164 errors.append((k, v))
166 if not errors: return
168 print "ERROR: shared user inconsistency. All apks wanting to use"
169 print " a given shared user must be signed with the same key."
172 for user, keys in errors:
173 print 'shared user id "%s":' % (user,)
174 for key, apps in keys.iteritems():
175 print ' %-*s %s' % (maxlen, key or "(unknown key)", apps[0])
177 print (' ' * (maxlen+5)) + a
183 def SignApk(data, keyname, pw):
184 unsigned = tempfile.NamedTemporaryFile()
188 signed = tempfile.NamedTemporaryFile()
190 common.SignFile(unsigned.name, signed.name, keyname, pw, align=4)
199 def SignApks(input_tf_zip, output_tf_zip, apk_key_map, key_passwords):
200 maxsize = max([len(os.path.basename(i.filename))
201 for i in input_tf_zip.infolist()
202 if i.filename.endswith('.apk')])
204 for info in input_tf_zip.infolist():
205 data = input_tf_zip.read(info.filename)
206 out_info = copy.copy(info)
207 if info.filename.endswith(".apk"):
208 name = os.path.basename(info.filename)
209 key = apk_key_map[name]
211 print " signing: %-*s (%s)" % (maxsize, name, key)
212 signed_data = SignApk(data, key, key_passwords[key])
213 output_tf_zip.writestr(out_info, signed_data)
215 # an APK we're not supposed to sign.
216 print "NOT signing: %s" % (name,)
217 output_tf_zip.writestr(out_info, data)
218 elif info.filename in ("SYSTEM/build.prop",
219 "RECOVERY/RAMDISK/default.prop"):
220 print "rewriting %s:" % (info.filename,)
221 new_data = RewriteProps(data)
222 output_tf_zip.writestr(out_info, new_data)
224 # a non-APK file; copy it verbatim
225 output_tf_zip.writestr(out_info, data)
228 def RewriteProps(data):
230 for line in data.split("\n"):
233 if line and line[0] != '#':
234 key, value = line.split("=", 1)
235 if key == "ro.build.fingerprint":
236 pieces = line.split("/")
237 tags = set(pieces[-1].split(","))
238 for ch in OPTIONS.tag_changes:
243 line = "/".join(pieces[:-1] + [",".join(sorted(tags))])
244 elif key == "ro.build.description":
245 pieces = line.split(" ")
246 assert len(pieces) == 5
247 tags = set(pieces[-1].split(","))
248 for ch in OPTIONS.tag_changes:
253 line = " ".join(pieces[:-1] + [",".join(sorted(tags))])
254 if line != original_line:
255 print " replace: ", original_line
256 print " with: ", line
258 return "\n".join(output) + "\n"
261 def ReplaceOtaKeys(input_tf_zip, output_tf_zip):
263 keylist = input_tf_zip.read("META/otakeys.txt").split()
265 raise ExternalError("can't read META/otakeys.txt from input")
269 m = re.match(r"^(.*)\.x509\.pem$", k)
271 raise ExternalError("can't parse \"%s\" from META/otakeys.txt" % (k,))
273 mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
276 print "using:\n ", "\n ".join(mapped_keys)
277 print "for OTA package verification"
280 OPTIONS.key_map["build/target/product/security/testkey"] + ".x509.pem")
281 print "META/otakeys.txt has no keys; using", mapped_keys[0]
283 # recovery uses a version of the key that has been slightly
284 # predigested (by DumpPublicKey.java) and put in res/keys.
286 p = common.Run(["java", "-jar",
287 os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")]
289 stdout=subprocess.PIPE)
290 data, _ = p.communicate()
291 if p.returncode != 0:
292 raise ExternalError("failed to run dumpkeys")
293 common.ZipWriteStr(output_tf_zip, "RECOVERY/RAMDISK/res/keys", data)
295 # SystemUpdateActivity uses the x509.pem version of the keys, but
296 # put into a zipfile system/etc/security/otacerts.zip.
298 tempfile = cStringIO.StringIO()
299 certs_zip = zipfile.ZipFile(tempfile, "w")
300 for k in mapped_keys:
303 common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
309 def option_handler(o, a):
310 if o in ("-s", "--signapk_jar"):
311 OPTIONS.signapk_jar = a
312 elif o in ("-e", "--extra_apks"):
313 names, key = a.split("=")
314 names = names.split(",")
316 OPTIONS.extra_apks[n] = key
317 elif o in ("-d", "--default_key_mappings"):
318 OPTIONS.key_map.update({
319 "build/target/product/security/testkey": "%s/releasekey" % (a,),
320 "build/target/product/security/media": "%s/media" % (a,),
321 "build/target/product/security/shared": "%s/shared" % (a,),
322 "build/target/product/security/platform": "%s/platform" % (a,),
324 elif o in ("-k", "--key_mapping"):
326 OPTIONS.key_map[s] = d
327 elif o in ("-o", "--replace_ota_keys"):
328 OPTIONS.replace_ota_keys = True
329 elif o in ("-t", "--tag_changes"):
331 for i in a.split(","):
333 if not i or i[0] not in "-+":
334 raise ValueError("Bad tag change '%s'" % (i,))
335 new.append(i[0] + i[1:].strip())
336 OPTIONS.tag_changes = tuple(new)
341 args = common.ParseOptions(argv, __doc__,
342 extra_opts="s:e:d:k:ot:",
343 extra_long_opts=["signapk_jar=",
345 "default_key_mappings=",
349 extra_option_handler=option_handler)
352 common.Usage(__doc__)
355 input_zip = zipfile.ZipFile(args[0], "r")
356 output_zip = zipfile.ZipFile(args[1], "w")
358 apk_key_map = GetApkCerts(input_zip)
359 CheckAllApksSigned(input_zip, apk_key_map)
360 CheckSharedUserIdsConsistent(input_zip, apk_key_map)
362 key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
363 SignApks(input_zip, output_zip, apk_key_map, key_passwords)
365 if OPTIONS.replace_ota_keys:
366 ReplaceOtaKeys(input_zip, output_zip)
374 if __name__ == '__main__':
377 except common.ExternalError, e:
379 print " ERROR: %s" % (e,)