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