Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 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 | """ |
| 18 | Signs all the APK files in a target-files zipfile, producing a new |
| 19 | target-files zip. |
| 20 | |
| 21 | Usage: 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 |
Doug Zongker | ad88c7c | 2009-04-14 12:34:27 -0700 | [diff] [blame] | 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. |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 33 | |
| 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 |
| 38 | mappings. |
| 39 | |
| 40 | -d (--default_key_mappings) <dir> |
| 41 | Set up the following key mappings: |
| 42 | |
| 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 |
| 47 | |
| 48 | -d and -k options are added to the set of mappings in the order |
| 49 | in which they appear on the command line. |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 50 | |
| 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. |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 56 | """ |
| 57 | |
| 58 | import sys |
| 59 | |
| 60 | if sys.hexversion < 0x02040000: |
| 61 | print >> sys.stderr, "Python 2.4 or newer is required." |
| 62 | sys.exit(1) |
| 63 | |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 64 | import cStringIO |
| 65 | import copy |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 66 | import os |
| 67 | import re |
| 68 | import subprocess |
| 69 | import tempfile |
| 70 | import zipfile |
| 71 | |
| 72 | import common |
| 73 | |
| 74 | OPTIONS = common.OPTIONS |
| 75 | |
| 76 | OPTIONS.extra_apks = {} |
| 77 | OPTIONS.key_map = {} |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 78 | OPTIONS.replace_ota_keys = False |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 79 | |
| 80 | def GetApkCerts(tf_zip): |
Doug Zongker | ad88c7c | 2009-04-14 12:34:27 -0700 | [diff] [blame] | 81 | certmap = {} |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 82 | for line in tf_zip.read("META/apkcerts.txt").split("\n"): |
| 83 | line = line.strip() |
| 84 | if not line: continue |
| 85 | m = re.match(r'^name="(.*)"\s+certificate="(.*)\.x509\.pem"\s+' |
| 86 | r'private_key="\2\.pk8"$', line) |
| 87 | if not m: |
| 88 | raise SigningError("failed to parse line from apkcerts.txt:\n" + line) |
| 89 | certmap[m.group(1)] = OPTIONS.key_map.get(m.group(2), m.group(2)) |
Doug Zongker | ad88c7c | 2009-04-14 12:34:27 -0700 | [diff] [blame] | 90 | for apk, cert in OPTIONS.extra_apks.iteritems(): |
| 91 | certmap[apk] = OPTIONS.key_map.get(cert, cert) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 92 | return certmap |
| 93 | |
| 94 | |
| 95 | def SignApk(data, keyname, pw): |
| 96 | unsigned = tempfile.NamedTemporaryFile() |
| 97 | unsigned.write(data) |
| 98 | unsigned.flush() |
| 99 | |
| 100 | signed = tempfile.NamedTemporaryFile() |
| 101 | |
| 102 | common.SignFile(unsigned.name, signed.name, keyname, pw, align=4) |
| 103 | |
| 104 | data = signed.read() |
| 105 | unsigned.close() |
| 106 | signed.close() |
| 107 | |
| 108 | return data |
| 109 | |
| 110 | |
| 111 | def SignApks(input_tf_zip, output_tf_zip): |
| 112 | apk_key_map = GetApkCerts(input_tf_zip) |
| 113 | |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 114 | maxsize = max([len(os.path.basename(i.filename)) |
| 115 | for i in input_tf_zip.infolist() |
| 116 | if i.filename.endswith('.apk')]) |
| 117 | |
Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 118 | # Check that all the APKs we want to sign have keys specified, and |
| 119 | # error out if they don't. Do this before prompting for key |
| 120 | # passwords in case we're going to fail anyway. |
| 121 | unknown_apks = [] |
| 122 | for info in input_tf_zip.infolist(): |
| 123 | if info.filename.endswith(".apk"): |
| 124 | name = os.path.basename(info.filename) |
| 125 | if name not in apk_key_map: |
| 126 | unknown_apks.append(name) |
| 127 | if unknown_apks: |
| 128 | print "ERROR: no key specified for:\n\n ", |
| 129 | print "\n ".join(unknown_apks) |
| 130 | print "\nUse '-e <apkname>=' to specify a key (which may be an" |
| 131 | print "empty string to not sign this apk)." |
| 132 | sys.exit(1) |
| 133 | |
| 134 | key_passwords = common.GetKeyPasswords(set(apk_key_map.values())) |
| 135 | |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 136 | for info in input_tf_zip.infolist(): |
| 137 | data = input_tf_zip.read(info.filename) |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 138 | out_info = copy.copy(info) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 139 | if info.filename.endswith(".apk"): |
| 140 | name = os.path.basename(info.filename) |
Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 141 | key = apk_key_map[name] |
| 142 | if key: |
| 143 | print " signing: %-*s (%s)" % (maxsize, name, key) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 144 | signed_data = SignApk(data, key, key_passwords[key]) |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 145 | output_tf_zip.writestr(out_info, signed_data) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 146 | else: |
| 147 | # an APK we're not supposed to sign. |
Doug Zongker | 43874f8 | 2009-04-14 14:05:15 -0700 | [diff] [blame] | 148 | print "NOT signing: %s" % (name,) |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 149 | output_tf_zip.writestr(out_info, data) |
| 150 | elif info.filename in ("SYSTEM/build.prop", |
| 151 | "RECOVERY/RAMDISK/default.prop"): |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 152 | # Change build fingerprint to reflect the fact that apps are signed. |
| 153 | m = re.search(r"ro\.build\.fingerprint=.*\b(test-keys)\b.*", data) |
| 154 | if not m: |
| 155 | print 'WARNING: ro.build.fingerprint does not contain "test-keys"' |
| 156 | else: |
| 157 | data = data[:m.start(1)] + "release-keys" + data[m.end(1):] |
| 158 | m = re.search(r"ro\.build\.description=.*\b(test-keys)\b.*", data) |
| 159 | if not m: |
| 160 | print 'WARNING: ro.build.description does not contain "test-keys"' |
| 161 | else: |
| 162 | data = data[:m.start(1)] + "release-keys" + data[m.end(1):] |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 163 | output_tf_zip.writestr(out_info, data) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 164 | else: |
| 165 | # a non-APK file; copy it verbatim |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 166 | output_tf_zip.writestr(out_info, data) |
| 167 | |
| 168 | |
| 169 | def ReplaceOtaKeys(input_tf_zip, output_tf_zip): |
| 170 | try: |
| 171 | keylist = input_tf_zip.read("META/otakeys.txt").split() |
| 172 | except KeyError: |
| 173 | raise ExternalError("can't read META/otakeys.txt from input") |
| 174 | |
| 175 | mapped_keys = [] |
| 176 | for k in keylist: |
| 177 | m = re.match(r"^(.*)\.x509\.pem$", k) |
| 178 | if not m: |
| 179 | raise ExternalError("can't parse \"%s\" from META/otakeys.txt" % (k,)) |
| 180 | k = m.group(1) |
| 181 | mapped_keys.append(OPTIONS.key_map.get(k, k) + ".x509.pem") |
| 182 | |
| 183 | print "using:\n ", "\n ".join(mapped_keys) |
| 184 | print "for OTA package verification" |
| 185 | |
| 186 | # recovery uses a version of the key that has been slightly |
| 187 | # predigested (by DumpPublicKey.java) and put in res/keys. |
| 188 | |
| 189 | p = common.Run(["java", "-jar", OPTIONS.dumpkey_jar] + mapped_keys, |
| 190 | stdout=subprocess.PIPE) |
| 191 | data, _ = p.communicate() |
| 192 | if p.returncode != 0: |
| 193 | raise ExternalError("failed to run dumpkeys") |
| 194 | output_tf_zip.writestr("RECOVERY/RAMDISK/res/keys", data) |
| 195 | |
| 196 | # SystemUpdateActivity uses the x509.pem version of the keys, but |
| 197 | # put into a zipfile system/etc/security/otacerts.zip. |
| 198 | |
| 199 | tempfile = cStringIO.StringIO() |
| 200 | certs_zip = zipfile.ZipFile(tempfile, "w") |
| 201 | for k in mapped_keys: |
| 202 | certs_zip.write(k) |
| 203 | certs_zip.close() |
| 204 | output_tf_zip.writestr("SYSTEM/etc/security/otacerts.zip", |
| 205 | tempfile.getvalue()) |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 206 | |
| 207 | |
| 208 | def main(argv): |
| 209 | |
| 210 | def option_handler(o, a): |
| 211 | if o in ("-s", "--signapk_jar"): |
| 212 | OPTIONS.signapk_jar = a |
| 213 | elif o in ("-e", "--extra_apks"): |
| 214 | names, key = a.split("=") |
| 215 | names = names.split(",") |
| 216 | for n in names: |
| 217 | OPTIONS.extra_apks[n] = key |
| 218 | elif o in ("-d", "--default_key_mappings"): |
| 219 | OPTIONS.key_map.update({ |
| 220 | "build/target/product/security/testkey": "%s/releasekey" % (a,), |
| 221 | "build/target/product/security/media": "%s/media" % (a,), |
| 222 | "build/target/product/security/shared": "%s/shared" % (a,), |
| 223 | "build/target/product/security/platform": "%s/platform" % (a,), |
| 224 | }) |
| 225 | elif o in ("-k", "--key_mapping"): |
| 226 | s, d = a.split("=") |
| 227 | OPTIONS.key_map[s] = d |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 228 | elif o in ("-o", "--replace_ota_keys"): |
| 229 | OPTIONS.replace_ota_keys = True |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 230 | else: |
| 231 | return False |
| 232 | return True |
| 233 | |
| 234 | args = common.ParseOptions(argv, __doc__, |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 235 | extra_opts="s:e:d:k:o", |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 236 | extra_long_opts=["signapk_jar=", |
| 237 | "extra_apks=", |
| 238 | "default_key_mappings=", |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 239 | "key_mapping=", |
| 240 | "replace_ota_keys"], |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 241 | extra_option_handler=option_handler) |
| 242 | |
| 243 | if len(args) != 2: |
| 244 | common.Usage(__doc__) |
| 245 | sys.exit(1) |
| 246 | |
| 247 | input_zip = zipfile.ZipFile(args[0], "r") |
| 248 | output_zip = zipfile.ZipFile(args[1], "w") |
| 249 | |
| 250 | SignApks(input_zip, output_zip) |
| 251 | |
Doug Zongker | 8e931bf | 2009-04-06 15:21:45 -0700 | [diff] [blame] | 252 | if OPTIONS.replace_ota_keys: |
| 253 | ReplaceOtaKeys(input_zip, output_zip) |
| 254 | |
Doug Zongker | eef3944 | 2009-04-02 12:14:19 -0700 | [diff] [blame] | 255 | input_zip.close() |
| 256 | output_zip.close() |
| 257 | |
| 258 | print "done." |
| 259 | |
| 260 | |
| 261 | if __name__ == '__main__': |
| 262 | try: |
| 263 | main(sys.argv[1:]) |
| 264 | except common.ExternalError, e: |
| 265 | print |
| 266 | print " ERROR: %s" % (e,) |
| 267 | print |
| 268 | sys.exit(1) |