chiark / gitweb /
whitelist some open-source firebase libs
[fdroidserver.git] / fdroidserver / scanner.py
1 #!/usr/bin/env python3
2 #
3 # scanner.py - part of the FDroid server tools
4 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU Affero General Public License for more details.
15 #
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 import os
20 import re
21 import traceback
22 from argparse import ArgumentParser
23 import logging
24
25 from . import _
26 from . import common
27 from . import metadata
28 from .exception import BuildException, VCSException
29
30 config = None
31 options = None
32
33
34 def get_gradle_compile_commands(build):
35     compileCommands = ['compile', 'releaseCompile']
36     if build.gradle and build.gradle != ['yes']:
37         compileCommands += [flavor + 'Compile' for flavor in build.gradle]
38         compileCommands += [flavor + 'ReleaseCompile' for flavor in build.gradle]
39
40     return [re.compile(r'\s*' + c, re.IGNORECASE) for c in compileCommands]
41
42
43 def scan_source(build_dir, build):
44     """Scan the source code in the given directory (and all subdirectories)
45     and return the number of fatal problems encountered
46     """
47
48     count = 0
49
50     # Common known non-free blobs (always lower case):
51     usual_suspects = {
52         exp: re.compile(r'.*' + exp, re.IGNORECASE) for exp in [
53             r'flurryagent',
54             r'paypal.*mpl',
55             r'google.*analytics',
56             r'admob.*sdk.*android',
57             r'google.*ad.*view',
58             r'google.*admob',
59             r'google.*play.*services',
60             r'crittercism',
61             r'heyzap',
62             r'jpct.*ae',
63             r'youtube.*android.*player.*api',
64             r'bugsense',
65             r'crashlytics',
66             r'ouya.*sdk',
67             r'libspen23',
68             r'firebase',
69         ]
70     }
71
72     whitelisted = [
73         'firebase-jobdispatcher',  # https://github.com/firebase/firebase-jobdispatcher-android/blob/master/LICENSE
74         'com.firebaseui',          # https://github.com/firebase/FirebaseUI-Android/blob/master/LICENSE
75         'geofire-android'          # https://github.com/firebase/geofire-java/blob/master/LICENSE
76     ]
77
78     def is_whitelisted(s):
79         return any(wl in s for wl in whitelisted)
80
81     def suspects_found(s):
82         for n, r in usual_suspects.items():
83             if r.match(s) and not is_whitelisted(s):
84                 yield n
85
86     gradle_mavenrepo = re.compile(r'maven *{ *(url)? *[\'"]?([^ \'"]*)[\'"]?')
87
88     allowed_repos = [re.compile(r'^https?://' + re.escape(repo) + r'/*') for repo in [
89         'repo1.maven.org/maven2',  # mavenCentral()
90         'jcenter.bintray.com',     # jcenter()
91         'jitpack.io',
92         'repo.maven.apache.org/maven2',
93         'oss.jfrog.org/artifactory/oss-snapshot-local',
94         'oss.sonatype.org/content/repositories/snapshots',
95         'oss.sonatype.org/content/repositories/releases',
96         'oss.sonatype.org/content/groups/public',
97         'clojars.org/repo',  # Clojure free software libs
98         's3.amazonaws.com/repo.commonsware.com',  # CommonsWare
99         'plugins.gradle.org/m2',  # Gradle plugin repo
100         'maven.google.com',  # Google Maven Repo, https://developer.android.com/studio/build/dependencies.html#google-maven
101         ]
102     ]
103
104     scanignore = common.getpaths_map(build_dir, build.scanignore)
105     scandelete = common.getpaths_map(build_dir, build.scandelete)
106
107     scanignore_worked = set()
108     scandelete_worked = set()
109
110     def toignore(path_in_build_dir):
111         for k, paths in scanignore.items():
112             for p in paths:
113                 if path_in_build_dir.startswith(p):
114                     scanignore_worked.add(k)
115                     return True
116         return False
117
118     def todelete(path_in_build_dir):
119         for k, paths in scandelete.items():
120             for p in paths:
121                 if path_in_build_dir.startswith(p):
122                     scandelete_worked.add(k)
123                     return True
124         return False
125
126     def ignoreproblem(what, path_in_build_dir):
127         logging.info('Ignoring %s at %s' % (what, path_in_build_dir))
128         return 0
129
130     def removeproblem(what, path_in_build_dir, filepath):
131         logging.info('Removing %s at %s' % (what, path_in_build_dir))
132         os.remove(filepath)
133         return 0
134
135     def warnproblem(what, path_in_build_dir):
136         if toignore(path_in_build_dir):
137             return
138         logging.warn('Found %s at %s' % (what, path_in_build_dir))
139
140     def handleproblem(what, path_in_build_dir, filepath):
141         if toignore(path_in_build_dir):
142             return ignoreproblem(what, path_in_build_dir)
143         if todelete(path_in_build_dir):
144             return removeproblem(what, path_in_build_dir, filepath)
145         logging.error('Found %s at %s' % (what, path_in_build_dir))
146         return 1
147
148     def is_executable(path):
149         return os.path.exists(path) and os.access(path, os.X_OK)
150
151     textchars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7f})
152
153     def is_binary(path):
154         d = None
155         with open(path, 'rb') as f:
156             d = f.read(1024)
157         return bool(d.translate(None, textchars))
158
159     # False positives patterns for files that are binary and executable.
160     safe_paths = [re.compile(r) for r in [
161         r".*/drawable[^/]*/.*\.png$",  # png drawables
162         r".*/mipmap[^/]*/.*\.png$",    # png mipmaps
163         ]
164     ]
165
166     def safe_path(path):
167         for sp in safe_paths:
168             if sp.match(path):
169                 return True
170         return False
171
172     gradle_compile_commands = get_gradle_compile_commands(build)
173
174     def is_used_by_gradle(line):
175         return any(command.match(line) for command in gradle_compile_commands)
176
177     # Iterate through all files in the source code
178     for root, dirs, files in os.walk(build_dir, topdown=True):
179
180         # It's topdown, so checking the basename is enough
181         for ignoredir in ('.hg', '.git', '.svn', '.bzr'):
182             if ignoredir in dirs:
183                 dirs.remove(ignoredir)
184
185         for curfile in files:
186
187             if curfile in ['.DS_Store']:
188                 continue
189
190             # Path (relative) to the file
191             filepath = os.path.join(root, curfile)
192
193             if os.path.islink(filepath):
194                 continue
195
196             path_in_build_dir = os.path.relpath(filepath, build_dir)
197             _ignored, ext = common.get_extension(path_in_build_dir)
198
199             if ext == 'so':
200                 count += handleproblem('shared library', path_in_build_dir, filepath)
201             elif ext == 'a':
202                 count += handleproblem('static library', path_in_build_dir, filepath)
203             elif ext == 'class':
204                 count += handleproblem('Java compiled class', path_in_build_dir, filepath)
205             elif ext == 'apk':
206                 removeproblem('APK file', path_in_build_dir, filepath)
207
208             elif ext == 'jar':
209                 for name in suspects_found(curfile):
210                     count += handleproblem('usual suspect \'%s\'' % name, path_in_build_dir, filepath)
211                 if curfile == 'gradle-wrapper.jar':
212                     removeproblem('gradle-wrapper.jar', path_in_build_dir, filepath)
213                 else:
214                     warnproblem('JAR file', path_in_build_dir)
215
216             elif ext == 'aar':
217                 warnproblem('AAR file', path_in_build_dir)
218
219             elif ext == 'java':
220                 if not os.path.isfile(filepath):
221                     continue
222                 with open(filepath, 'r', encoding='utf8', errors='replace') as f:
223                     for line in f:
224                         if 'DexClassLoader' in line:
225                             count += handleproblem('DexClassLoader', path_in_build_dir, filepath)
226                             break
227
228             elif ext == 'gradle':
229                 if not os.path.isfile(filepath):
230                     continue
231                 with open(filepath, 'r', encoding='utf8', errors='replace') as f:
232                     lines = f.readlines()
233                 for i, line in enumerate(lines):
234                     if is_used_by_gradle(line):
235                         for name in suspects_found(line):
236                             count += handleproblem('usual suspect \'%s\' at line %d' % (name, i + 1), path_in_build_dir, filepath)
237                 noncomment_lines = [l for l in lines if not common.gradle_comment.match(l)]
238                 joined = re.sub(r'[\n\r\s]+', ' ', ' '.join(noncomment_lines))
239                 for m in gradle_mavenrepo.finditer(joined):
240                     url = m.group(2)
241                     if not any(r.match(url) for r in allowed_repos):
242                         count += handleproblem('unknown maven repo \'%s\'' % url, path_in_build_dir, filepath)
243
244             elif ext in ['', 'bin', 'out', 'exe']:
245                 if is_binary(filepath):
246                     count += handleproblem('binary', path_in_build_dir, filepath)
247
248             elif is_executable(filepath):
249                 if is_binary(filepath) and not safe_path(path_in_build_dir):
250                     warnproblem('possible binary', path_in_build_dir)
251
252     for p in scanignore:
253         if p not in scanignore_worked:
254             logging.error('Unused scanignore path: %s' % p)
255             count += 1
256
257     for p in scandelete:
258         if p not in scandelete_worked:
259             logging.error('Unused scandelete path: %s' % p)
260             count += 1
261
262     return count
263
264
265 def main():
266
267     global config, options
268
269     # Parse command line...
270     parser = ArgumentParser(usage="%(prog)s [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]")
271     common.setup_global_opts(parser)
272     parser.add_argument("appid", nargs='*', help=_("applicationId with optional versionCode in the form APPID[:VERCODE]"))
273     metadata.add_metadata_arguments(parser)
274     options = parser.parse_args()
275     metadata.warnings_action = options.W
276
277     config = common.read_config(options)
278
279     # Read all app and srclib metadata
280     allapps = metadata.read_metadata()
281     apps = common.read_app_args(options.appid, allapps, True)
282
283     probcount = 0
284
285     build_dir = 'build'
286     if not os.path.isdir(build_dir):
287         logging.info("Creating build directory")
288         os.makedirs(build_dir)
289     srclib_dir = os.path.join(build_dir, 'srclib')
290     extlib_dir = os.path.join(build_dir, 'extlib')
291
292     for appid, app in apps.items():
293
294         if app.Disabled:
295             logging.info(_("Skipping {appid}: disabled").format(appid=appid))
296             continue
297         if not app.builds:
298             logging.info(_("Skipping {appid}: no builds specified").format(appid=appid))
299             continue
300
301         logging.info(_("Processing {appid}").format(appid=appid))
302
303         try:
304
305             if app.RepoType == 'srclib':
306                 build_dir = os.path.join('build', 'srclib', app.Repo)
307             else:
308                 build_dir = os.path.join('build', appid)
309
310             # Set up vcs interface and make sure we have the latest code...
311             vcs = common.getvcs(app.RepoType, app.Repo, build_dir)
312
313             for build in app.builds:
314
315                 if build.disable:
316                     logging.info("...skipping version %s - %s" % (
317                         build.versionName, build.get('disable', build.commit[1:])))
318                 else:
319                     logging.info("...scanning version " + build.versionName)
320
321                     # Prepare the source code...
322                     common.prepare_source(vcs, app, build,
323                                           build_dir, srclib_dir,
324                                           extlib_dir, False)
325
326                     # Do the scan...
327                     count = scan_source(build_dir, build)
328                     if count > 0:
329                         logging.warn('Scanner found %d problems in %s (%s)' % (
330                             count, appid, build.versionCode))
331                         probcount += count
332
333         except BuildException as be:
334             logging.warn("Could not scan app %s due to BuildException: %s" % (
335                 appid, be))
336             probcount += 1
337         except VCSException as vcse:
338             logging.warn("VCS error while scanning app %s: %s" % (appid, vcse))
339             probcount += 1
340         except Exception:
341             logging.warn("Could not scan app %s due to unknown error: %s" % (
342                 appid, traceback.format_exc()))
343             probcount += 1
344
345     logging.info(_("Finished"))
346     print(_("%d problems found") % probcount)
347
348
349 if __name__ == "__main__":
350     main()