sign_target_files_apks.py revision f6a53aa5f24878ad9098409ed3d3f41bb5c63fb5
1#!/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  -e  (--extra_apks)  <name,name,...=key>
24      Add extra APK name/key pairs as though they appeared in
25      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.
29
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
39        build/target/product/security/testkey   ==>  $dir/releasekey
40        build/target/product/security/media     ==>  $dir/media
41        build/target/product/security/shared    ==>  $dir/shared
42        build/target/product/security/platform  ==>  $dir/platform
43
44      -d and -k options are added to the set of mappings in the order
45      in which they appear on the command line.
46
47  -o  (--replace_ota_keys)
48      Replace the certificate (public key) used by OTA package
49      verification with the one specified in the input target_files
50      zip (in the META/otakeys.txt file).  Key remapping (-k and -d)
51      is performed on this key.
52
53  -t  (--tag_changes)  <+tag>,<-tag>,...
54      Comma-separated list of changes to make to the set of tags (in
55      the last component of the build fingerprint).  Prefix each with
56      '+' or '-' to indicate whether that tag should be added or
57      removed.  Changes are processed in the order they appear.
58      Default value is "-test-keys,+release-keys".
59
60"""
61
62import sys
63
64if sys.hexversion < 0x02040000:
65  print >> sys.stderr, "Python 2.4 or newer is required."
66  sys.exit(1)
67
68import cStringIO
69import copy
70import os
71import re
72import subprocess
73import tempfile
74import zipfile
75
76import common
77
78OPTIONS = common.OPTIONS
79
80OPTIONS.extra_apks = {}
81OPTIONS.key_map = {}
82OPTIONS.replace_ota_keys = False
83OPTIONS.tag_changes = ("-test-keys", "+release-keys")
84
85def GetApkCerts(tf_zip):
86  certmap = common.ReadApkCerts(tf_zip)
87
88  # apply the key remapping to the contents of the file
89  for apk, cert in certmap.iteritems():
90    certmap[apk] = OPTIONS.key_map.get(cert, cert)
91
92  # apply all the -e options, overriding anything in the file
93  for apk, cert in OPTIONS.extra_apks.iteritems():
94    certmap[apk] = OPTIONS.key_map.get(cert, cert)
95
96  return certmap
97
98
99def CheckAllApksSigned(input_tf_zip, apk_key_map):
100  """Check that all the APKs we want to sign have keys specified, and
101  error out if they don't."""
102  unknown_apks = []
103  for info in input_tf_zip.infolist():
104    if info.filename.endswith(".apk"):
105      name = os.path.basename(info.filename)
106      if name not in apk_key_map:
107        unknown_apks.append(name)
108  if unknown_apks:
109    print "ERROR: no key specified for:\n\n ",
110    print "\n  ".join(unknown_apks)
111    print "\nUse '-e <apkname>=' to specify a key (which may be an"
112    print "empty string to not sign this apk)."
113    sys.exit(1)
114
115
116def SignApk(data, keyname, pw):
117  unsigned = tempfile.NamedTemporaryFile()
118  unsigned.write(data)
119  unsigned.flush()
120
121  signed = tempfile.NamedTemporaryFile()
122
123  common.SignFile(unsigned.name, signed.name, keyname, pw, align=4)
124
125  data = signed.read()
126  unsigned.close()
127  signed.close()
128
129  return data
130
131
132def SignApks(input_tf_zip, output_tf_zip, apk_key_map, key_passwords):
133  maxsize = max([len(os.path.basename(i.filename))
134                 for i in input_tf_zip.infolist()
135                 if i.filename.endswith('.apk')])
136
137  for info in input_tf_zip.infolist():
138    data = input_tf_zip.read(info.filename)
139    out_info = copy.copy(info)
140    if info.filename.endswith(".apk"):
141      name = os.path.basename(info.filename)
142      key = apk_key_map[name]
143      if key not in common.SPECIAL_CERT_STRINGS:
144        print "    signing: %-*s (%s)" % (maxsize, name, key)
145        signed_data = SignApk(data, key, key_passwords[key])
146        output_tf_zip.writestr(out_info, signed_data)
147      else:
148        # an APK we're not supposed to sign.
149        print "NOT signing: %s" % (name,)
150        output_tf_zip.writestr(out_info, data)
151    elif info.filename in ("SYSTEM/build.prop",
152                           "RECOVERY/RAMDISK/default.prop"):
153      print "rewriting %s:" % (info.filename,)
154      new_data = RewriteProps(data)
155      output_tf_zip.writestr(out_info, new_data)
156    else:
157      # a non-APK file; copy it verbatim
158      output_tf_zip.writestr(out_info, data)
159
160
161def RewriteProps(data):
162  output = []
163  for line in data.split("\n"):
164    line = line.strip()
165    original_line = line
166    if line and line[0] != '#':
167      key, value = line.split("=", 1)
168      if key == "ro.build.fingerprint":
169        pieces = line.split("/")
170        tags = set(pieces[-1].split(","))
171        for ch in OPTIONS.tag_changes:
172          if ch[0] == "-":
173            tags.discard(ch[1:])
174          elif ch[0] == "+":
175            tags.add(ch[1:])
176        line = "/".join(pieces[:-1] + [",".join(sorted(tags))])
177      elif key == "ro.build.description":
178        pieces = line.split(" ")
179        assert len(pieces) == 5
180        tags = set(pieces[-1].split(","))
181        for ch in OPTIONS.tag_changes:
182          if ch[0] == "-":
183            tags.discard(ch[1:])
184          elif ch[0] == "+":
185            tags.add(ch[1:])
186        line = " ".join(pieces[:-1] + [",".join(sorted(tags))])
187    if line != original_line:
188      print "  replace: ", original_line
189      print "     with: ", line
190    output.append(line)
191  return "\n".join(output) + "\n"
192
193
194def ReplaceOtaKeys(input_tf_zip, output_tf_zip):
195  try:
196    keylist = input_tf_zip.read("META/otakeys.txt").split()
197  except KeyError:
198    raise ExternalError("can't read META/otakeys.txt from input")
199
200  mapped_keys = []
201  for k in keylist:
202    m = re.match(r"^(.*)\.x509\.pem$", k)
203    if not m:
204      raise ExternalError("can't parse \"%s\" from META/otakeys.txt" % (k,))
205    k = m.group(1)
206    mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem")
207
208  if mapped_keys:
209    print "using:\n   ", "\n   ".join(mapped_keys)
210    print "for OTA package verification"
211  else:
212    mapped_keys.append(
213        OPTIONS.key_map["build/target/product/security/testkey"] + ".x509.pem")
214    print "META/otakeys.txt has no keys; using", mapped_keys[0]
215
216  # recovery uses a version of the key that has been slightly
217  # predigested (by DumpPublicKey.java) and put in res/keys.
218
219  p = common.Run(["java", "-jar",
220                  os.path.join(OPTIONS.search_path, "framework", "dumpkey.jar")]
221                 + mapped_keys,
222                 stdout=subprocess.PIPE)
223  data, _ = p.communicate()
224  if p.returncode != 0:
225    raise ExternalError("failed to run dumpkeys")
226  common.ZipWriteStr(output_tf_zip, "RECOVERY/RAMDISK/res/keys", data)
227
228  # SystemUpdateActivity uses the x509.pem version of the keys, but
229  # put into a zipfile system/etc/security/otacerts.zip.
230
231  tempfile = cStringIO.StringIO()
232  certs_zip = zipfile.ZipFile(tempfile, "w")
233  for k in mapped_keys:
234    certs_zip.write(k)
235  certs_zip.close()
236  common.ZipWriteStr(output_tf_zip, "SYSTEM/etc/security/otacerts.zip",
237                     tempfile.getvalue())
238
239
240def main(argv):
241
242  def option_handler(o, a):
243    if o in ("-e", "--extra_apks"):
244      names, key = a.split("=")
245      names = names.split(",")
246      for n in names:
247        OPTIONS.extra_apks[n] = key
248    elif o in ("-d", "--default_key_mappings"):
249      OPTIONS.key_map.update({
250          "build/target/product/security/testkey": "%s/releasekey" % (a,),
251          "build/target/product/security/media": "%s/media" % (a,),
252          "build/target/product/security/shared": "%s/shared" % (a,),
253          "build/target/product/security/platform": "%s/platform" % (a,),
254          })
255    elif o in ("-k", "--key_mapping"):
256      s, d = a.split("=")
257      OPTIONS.key_map[s] = d
258    elif o in ("-o", "--replace_ota_keys"):
259      OPTIONS.replace_ota_keys = True
260    elif o in ("-t", "--tag_changes"):
261      new = []
262      for i in a.split(","):
263        i = i.strip()
264        if not i or i[0] not in "-+":
265          raise ValueError("Bad tag change '%s'" % (i,))
266        new.append(i[0] + i[1:].strip())
267      OPTIONS.tag_changes = tuple(new)
268    else:
269      return False
270    return True
271
272  args = common.ParseOptions(argv, __doc__,
273                             extra_opts="e:d:k:ot:",
274                             extra_long_opts=["extra_apks=",
275                                              "default_key_mappings=",
276                                              "key_mapping=",
277                                              "replace_ota_keys",
278                                              "tag_changes="],
279                             extra_option_handler=option_handler)
280
281  if len(args) != 2:
282    common.Usage(__doc__)
283    sys.exit(1)
284
285  input_zip = zipfile.ZipFile(args[0], "r")
286  output_zip = zipfile.ZipFile(args[1], "w")
287
288  apk_key_map = GetApkCerts(input_zip)
289  CheckAllApksSigned(input_zip, apk_key_map)
290
291  key_passwords = common.GetKeyPasswords(set(apk_key_map.values()))
292  SignApks(input_zip, output_zip, apk_key_map, key_passwords)
293
294  if OPTIONS.replace_ota_keys:
295    ReplaceOtaKeys(input_zip, output_zip)
296
297  input_zip.close()
298  output_zip.close()
299
300  print "done."
301
302
303if __name__ == '__main__':
304  try:
305    main(sys.argv[1:])
306  except common.ExternalError, e:
307    print
308    print "   ERROR: %s" % (e,)
309    print
310    sys.exit(1)
311