chiark / gitweb /
Merge branch 'mr/verify_ca_certs_v2' into 'master'
[fdroidserver.git] / fdroidserver / publish.py
1 #!/usr/bin/env python3
2 #
3 # publish.py - part of the FDroid server tools
4 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16 #
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import sys
21 import os
22 import re
23 import shutil
24 import glob
25 import hashlib
26 from argparse import ArgumentParser
27 import logging
28
29 from . import common
30 from . import metadata
31 from .common import FDroidPopen, SdkToolsPopen
32 from .exception import BuildException
33
34 config = None
35 options = None
36
37
38 def main():
39
40     global config, options
41
42     # Parse command line...
43     parser = ArgumentParser(usage="%(prog)s [options] "
44                             "[APPID[:VERCODE] [APPID[:VERCODE] ...]]")
45     common.setup_global_opts(parser)
46     parser.add_argument("appid", nargs='*', help="app-id with optional versionCode in the form APPID[:VERCODE]")
47     metadata.add_metadata_arguments(parser)
48     options = parser.parse_args()
49     metadata.warnings_action = options.W
50
51     config = common.read_config(options)
52
53     if not ('jarsigner' in config and 'keytool' in config):
54         logging.critical('Java JDK not found! Install in standard location or set java_paths!')
55         sys.exit(1)
56
57     log_dir = 'logs'
58     if not os.path.isdir(log_dir):
59         logging.info("Creating log directory")
60         os.makedirs(log_dir)
61
62     tmp_dir = 'tmp'
63     if not os.path.isdir(tmp_dir):
64         logging.info("Creating temporary directory")
65         os.makedirs(tmp_dir)
66
67     output_dir = 'repo'
68     if not os.path.isdir(output_dir):
69         logging.info("Creating output directory")
70         os.makedirs(output_dir)
71
72     unsigned_dir = 'unsigned'
73     if not os.path.isdir(unsigned_dir):
74         logging.warning("No unsigned directory - nothing to do")
75         sys.exit(1)
76
77     if not os.path.exists(config['keystore']):
78         logging.error("Config error - missing '{0}'".format(config['keystore']))
79         sys.exit(1)
80
81     # It was suggested at
82     #    https://dev.guardianproject.info/projects/bazaar/wiki/FDroid_Audit
83     # that a package could be crafted, such that it would use the same signing
84     # key as an existing app. While it may be theoretically possible for such a
85     # colliding package ID to be generated, it seems virtually impossible that
86     # the colliding ID would be something that would be a) a valid package ID,
87     # and b) a sane-looking ID that would make its way into the repo.
88     # Nonetheless, to be sure, before publishing we check that there are no
89     # collisions, and refuse to do any publishing if that's the case...
90     allapps = metadata.read_metadata()
91     vercodes = common.read_pkg_args(options.appid, True)
92     allaliases = []
93     for appid in allapps:
94         m = hashlib.md5()
95         m.update(appid.encode('utf-8'))
96         keyalias = m.hexdigest()[:8]
97         if keyalias in allaliases:
98             logging.error("There is a keyalias collision - publishing halted")
99             sys.exit(1)
100         allaliases.append(keyalias)
101     logging.info("{0} apps, {0} key aliases".format(len(allapps),
102                                                     len(allaliases)))
103
104     # Process any APKs or ZIPs that are waiting to be signed...
105     for apkfile in sorted(glob.glob(os.path.join(unsigned_dir, '*.apk'))
106                           + glob.glob(os.path.join(unsigned_dir, '*.zip'))):
107
108         appid, vercode = common.publishednameinfo(apkfile)
109         apkfilename = os.path.basename(apkfile)
110         if vercodes and appid not in vercodes:
111             continue
112         if appid in vercodes and vercodes[appid]:
113             if vercode not in vercodes[appid]:
114                 continue
115         logging.info("Processing " + apkfile)
116
117         # There ought to be valid metadata for this app, otherwise why are we
118         # trying to publish it?
119         if appid not in allapps:
120             logging.error("Unexpected {0} found in unsigned directory"
121                           .format(apkfilename))
122             sys.exit(1)
123         app = allapps[appid]
124
125         if app.Binaries:
126
127             # It's an app where we build from source, and verify the apk
128             # contents against a developer's binary, and then publish their
129             # version if everything checks out.
130             # The binary should already have been retrieved during the build
131             # process.
132             srcapk = re.sub(r'.apk$', '.binary.apk', apkfile)
133
134             # Compare our unsigned one with the downloaded one...
135             compare_result = common.verify_apks(srcapk, apkfile, tmp_dir)
136             if compare_result:
137                 logging.error("...verification failed - publish skipped : "
138                               + compare_result)
139                 continue
140
141             # Success! So move the downloaded file to the repo, and remove
142             # our built version.
143             shutil.move(srcapk, os.path.join(output_dir, apkfilename))
144             os.remove(apkfile)
145
146         elif apkfile.endswith('.zip'):
147
148             # OTA ZIPs built by fdroid do not need to be signed by jarsigner,
149             # just to be moved into place in the repo
150             shutil.move(apkfile, os.path.join(output_dir, apkfilename))
151
152         else:
153
154             # It's a 'normal' app, i.e. we sign and publish it...
155
156             # Figure out the key alias name we'll use. Only the first 8
157             # characters are significant, so we'll use the first 8 from
158             # the MD5 of the app's ID and hope there are no collisions.
159             # If a collision does occur later, we're going to have to
160             # come up with a new alogrithm, AND rename all existing keys
161             # in the keystore!
162             if appid in config['keyaliases']:
163                 # For this particular app, the key alias is overridden...
164                 keyalias = config['keyaliases'][appid]
165                 if keyalias.startswith('@'):
166                     m = hashlib.md5()
167                     m.update(keyalias[1:].encode('utf-8'))
168                     keyalias = m.hexdigest()[:8]
169             else:
170                 m = hashlib.md5()
171                 m.update(appid.encode('utf-8'))
172                 keyalias = m.hexdigest()[:8]
173             logging.info("Key alias: " + keyalias)
174
175             # See if we already have a key for this application, and
176             # if not generate one...
177             env_vars = {
178                 'FDROID_KEY_STORE_PASS': config['keystorepass'],
179                 'FDROID_KEY_PASS': config['keypass'],
180             }
181             p = FDroidPopen([config['keytool'], '-list',
182                              '-alias', keyalias, '-keystore', config['keystore'],
183                              '-storepass:env', 'FDROID_KEY_STORE_PASS'], envs=env_vars)
184             if p.returncode != 0:
185                 logging.info("Key does not exist - generating...")
186                 p = FDroidPopen([config['keytool'], '-genkey',
187                                  '-keystore', config['keystore'],
188                                  '-alias', keyalias,
189                                  '-keyalg', 'RSA', '-keysize', '2048',
190                                  '-validity', '10000',
191                                  '-storepass:env', 'FDROID_KEY_STORE_PASS',
192                                  '-keypass:env', 'FDROID_KEY_PASS',
193                                  '-dname', config['keydname']], envs=env_vars)
194                 if p.returncode != 0:
195                     raise BuildException("Failed to generate key")
196
197             # Sign the application...
198             p = FDroidPopen([config['jarsigner'], '-keystore', config['keystore'],
199                              '-storepass:env', 'FDROID_KEY_STORE_PASS',
200                              '-keypass:env', 'FDROID_KEY_PASS', '-sigalg',
201                              'SHA1withRSA', '-digestalg', 'SHA1',
202                              apkfile, keyalias], envs=env_vars)
203             if p.returncode != 0:
204                 raise BuildException("Failed to sign application")
205
206             # Zipalign it...
207             p = SdkToolsPopen(['zipalign', '-v', '4', apkfile,
208                                os.path.join(output_dir, apkfilename)])
209             if p.returncode != 0:
210                 raise BuildException("Failed to align application")
211             os.remove(apkfile)
212
213         # Move the source tarball into the output directory...
214         tarfilename = apkfilename[:-4] + '_src.tar.gz'
215         tarfile = os.path.join(unsigned_dir, tarfilename)
216         if os.path.exists(tarfile):
217             shutil.move(tarfile, os.path.join(output_dir, tarfilename))
218
219         logging.info('Published ' + apkfilename)
220
221
222 if __name__ == "__main__":
223     main()