-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathdetector_runner.py
529 lines (475 loc) · 17.7 KB
/
detector_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# Copyright 2023 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
r"""The main module to run Vanir Detector.
Usage:
./detector_runner [flags] scanner_name scannerarg1 scannerarg2 ...
For example, to scan /test/source against all signatures in /vanir/sigs.json:
./detector_runner \
--vulnerability_file_name=/vanir/sigs.json \
offline_directory_scanner /test/source
"""
import collections
import datetime
import functools
import inspect
import itertools
import json
import os
import sys
import textwrap
from typing import Mapping, Sequence, Type, TypeVar
from absl import app
from absl import flags
from absl import logging
import jinja2
import requests
from vanir import detector_common_flags
from vanir import osv_client
from vanir import reporter
from vanir.scanners import scanner_base
# Simply importing the scanners will register them as subclasses of the
# abstract extractor class and therefore available for use.
# pylint: disable=unused-import,g-bad-import-order
from vanir.scanners import android_kernel_scanner
from vanir.scanners import offline_directory_scanner
from vanir.scanners import package_scanner
from vanir.scanners import repo_scanner
# pylint: enable=unused-import,g-bad-import-order
VanirScanner = TypeVar('VanirScanner', bound=scanner_base.ScannerBase)
flags.declare_key_flag('osv_id_ignore_list')
flags.declare_key_flag('cve_id_ignore_list')
flags.declare_key_flag('android_min_severity_level')
flags.declare_key_flag('android_spl')
flags.declare_key_flag('sign_target_path_filter')
flags.declare_key_flag('sign_target_arch')
flags.declare_key_flag('vulnerability_file_name')
flags.declare_key_flag('target_selection_strategy')
flags.declare_key_flag('ignore_scan_path')
_REPORT_FILE_NAME_PREFIX = flags.DEFINE_string(
'report_file_name_prefix',
None,
'The output report file name prefix. If not '
'specified "/tmp/vanir/report-<current datetime>" will be used.',
)
_MINIMUM_NUMBER_OF_FILES = flags.DEFINE_integer(
'minimum_number_of_files',
10,
'The minimum number of files expected to exist in the target system. If the'
' target system contains less files than this theshold, detector will fail.'
' This is just a safety knob for preventing mistakes of scanning a wrong'
' target. If you intend to scan directory containing few files, please'
' update this flag.',
)
_HTML_REPORT_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Vanir Detector Report {{ report_file_name }}</title>
<style>
body {
font-family: Roboto, sans-serif;
}
table {
border-collapse: collapse;
border: 2px solid black;
}
th, td {
border: 1px solid gray;
word-break: keep-all;
padding: 5px;
vertical-align: top;
}
h3 {
padding: 0.3em;
background-color: lightgray;
}
.expand-toggle {
cursor: pointer;
}
.expand-toggle.collapsed:before {
content: "▸ ";
}
.expand-toggle:before {
content: "▾ ";
}
.expand-toggle.collapsed + * {
display: none;
}
</style>
<script>
function toggle(element) {
element.classList.toggle("collapsed");
}
</script>
</head>
<body>
<h1>Vanir Detector Report {{ report_file_name }}</h1>
<h3 onclick="toggle(this);" class="expand-toggle collapsed">Options</h3>
<pre style="white-space: pre-wrap;">{{ options }}</pre>
<h3 onclick="toggle(this);" class="expand-toggle collapsed">
Coverage
({{ covered_cves|length }} CVE{{ 's' if covered_cves|length > 1 else '' }})
</h3>
<table>
<tr>
<th>Covered CVEs</th>
<td>
<pre>{% for cve in covered_cves %}<nobr>{{ '%-15s' | format(cve) | replace(' ',' ')}}</nobr> <wbr>{% endfor %}
</pre>
</td>
</tr>
<tr>
<th>Unpatched CVEs</th>
<td>
<pre>{% for cve in unpatched_cves %}<nobr>{{ '%-15s' | format(cve) | replace(' ',' ')}}</nobr> <wbr>{% endfor %}
</pre>
</td>
</tr>
</table>
<h3 onclick="toggle(this);" class="expand-toggle">
Missing Patches in Target Files
(in {{ target_missing_patches|length }}
vuln{{ 's' if target_missing_patches|length > 1 else '' }})
</h3>
<table>
{% for osv_id, details in target_missing_patches.items()|sort %}
<tr>
<td>{{osv_id}}</td>
<td>
{% for summary in details['summaries']|sort %}{{summary}}<br>
{% endfor %}
{% if details['osv_url'] == 'Not published.' %}
OSV: {{details['osv_url']}}<br>
{% else %}
OSV: <a href=\"{{details['osv_url']}}\">{{details['osv_url']}}</a><br>
{% endif %}
CVE: {% for cve_id in details['cve_ids'] %}{{cve_id}} {% endfor %}<br>
</td>
</tr>
{% endfor %}
</table>
<h3 onclick="toggle(this);" class="expand-toggle">
Missing Patches in Non-target Files
(in {{ non_target_missing_patches|length }}
vuln{{ 's' if non_target_missing_patches|length > 1 else '' }})
</h3>
<table>
{% for osv_id, details in non_target_missing_patches.items()|sort %}
<tr>
<td>{{osv_id}}</td>
<td>
{% for summary in details['summaries']|sort %}{{summary}}<br>
{% endfor %}
{% if details['osv_url'] == 'Not published.' %}
OSV: {{details['osv_url']}}<br>
{% else %}
OSV: <a href=\"{{details['osv_url']}}\">{{details['osv_url']}}</a><br>
{% endif %}
CVE: {% for cve_id in details['cve_ids'] %}{{cve_id}} {% endfor %}<br>
</td>
</tr>
{% endfor %}
</table>
{% if errors %}
<h3 onclick="toggle(this);" class="expand-toggle">Errors ({{ errors|length }})</h3>
<table>
{% for error in errors|sort %}
<tr><td>{{ error|e }}</td></tr>
{% endfor %}
</table>
{% endif %}
<h3 onclick="toggle(this);" class="expand-toggle collapsed">Scan metadata and stats</h3>
<table>
{% for key, value in metadata.items()|sort %}
<tr><td>{{key}}</td><td>{{value|escape|replace('\n', '<br />')}}</td></tr>
{% endfor %}
</table>
</body>
</html>
"""
_CMDLINE_ARGS_TYPES = (
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.VAR_POSITIONAL)
def _get_all_scanners() -> Mapping[str, Type[VanirScanner]]:
"""Return all known scanners that can be run from the command line.
This covers all scanners that do not require keyword-only arguments.
Returns:
A map from scanner name to scanner class for all supported scanners.
"""
scanner_map = {}
scanners = scanner_base.ScannerBase.__subclasses__()
while scanners:
scanner = scanners.pop()
scanners += scanner.__subclasses__()
scanner_params = inspect.signature(scanner.__init__).parameters.values()
unsupported_params = (arg for arg in scanner_params
if arg.kind is inspect.Parameter.KEYWORD_ONLY
and arg.default is inspect.Parameter.empty)
if any(unsupported_params):
continue
scanner_name = scanner.name()
if scanner_name in scanner_map:
raise ValueError(
f'Found more than one scanner with the same name "{scanner_name}": '
f'\n{scanner_map.get(scanner_name)}'
f'\n{scanner}'
)
scanner_map[scanner_name] = scanner
return scanner_map
def _get_scanner_usage_str(scanner: Type[VanirScanner]) -> str:
"""Returns commandline usage instruction string for the given scanner."""
all_args = inspect.signature(scanner.__init__).parameters.values()
scanner_args = [arg for arg in all_args if arg.name != 'self'
and arg.kind in _CMDLINE_ARGS_TYPES]
arg_strs = []
for arg in scanner_args:
if arg.kind is inspect.Parameter.VAR_POSITIONAL:
if arg.default is inspect.Parameter.empty:
arg_strs.append(f'{arg.name} [{arg.name}...]')
else:
arg_strs.append(f'[{arg.name}...]')
elif arg.default is inspect.Parameter.empty:
arg_strs.append(f'{arg.name}')
else:
arg_strs.append(f'[{arg.name}]')
init_doc = (
textwrap.indent(inspect.cleandoc(scanner.__init__.__doc__), ' ')
if scanner.__init__.__doc__ else '')
return (f'Usage for {scanner.name()}:\n'
f' detector_runner.py {scanner.name()} {" ".join(arg_strs)}\n'
f'{init_doc}').strip()
def _is_valid_scanner_args(
scanner: Type[VanirScanner], given_args: Sequence[str]) -> bool:
"""Returns whether the given args pass validity check for the scanner."""
all_args = inspect.signature(scanner.__init__).parameters.values()
scanner_args = [arg for arg in all_args if arg.name != 'self'
and arg.kind in _CMDLINE_ARGS_TYPES]
num_required_args = len(
[1 for arg in scanner_args if (arg.default is inspect.Parameter.empty)])
has_vararg = any(1 for arg in scanner_args
if arg.kind is inspect.Parameter.VAR_POSITIONAL)
# Check to see if number of args is valid for the given scanner
if len(given_args) < num_required_args:
return False
if len(given_args) > len(scanner_args) and not has_vararg:
return False
return True
@functools.cache
def _get_public_osv_url(osv_id: str) -> str:
"""Returns OSV URL for the given |osv_id| if available from public OSV."""
try:
vuln_info = osv_client.OsvClient().get_vuln(osv_id)
except requests.RequestException:
logging.error('Failed to connect to OSV. Assuming the vuln exists.')
return osv_client.get_osv_url(osv_id)
if 'code' in vuln_info:
logging.debug(
'Failed to get %s (code: %s, reason: %s)',
osv_id,
vuln_info['code'],
vuln_info.get('message', ''),
)
return 'Not published.'
return osv_client.get_osv_url(osv_id)
def _generate_json_report(
report_file_name: str,
report_book: reporter.ReportBook,
covered_cves: Sequence[str],
) -> None:
"""Generates a JSON report based on the findings.
Args:
report_file_name: a JSON report file name to create.
report_book: a report book instance containing all reports.
covered_cves: a sequence of CVEs covered by this run.
Returns:
None
"""
json_report = collections.OrderedDict()
missing_patches = []
for osv_id in report_book.unpatched_vulnerabilities:
report_group = report_book.get_report_group(osv_id)
if not report_group:
continue
details = []
missing_patches.append({
'ID': osv_id,
'CVE': report_group.cve_ids,
'OSV': _get_public_osv_url(osv_id),
'details': details,
})
for report in report_group.reports:
unpatched_code = report.unpatched_file
if report.unpatched_function_name:
unpatched_code += '::' + report.unpatched_function_name
details.append({
'unpatched_code': unpatched_code,
'patch': report.signature_source,
'is_non_target_match': report.is_non_target_match,
'matched_signature': report.signature_id,
})
json_report['options'] = ' '.join(sys.argv[1:])
json_report['covered_cves'] = covered_cves
json_report['missing_patches'] = missing_patches
with open(report_file_name, 'w') as report_file:
json.dump(json_report, report_file, indent=4)
def _generate_html_report(
report_file_name: str,
report_book: reporter.ReportBook,
covered_cves: Sequence[str],
stats: scanner_base.ScannedFileStats,
) -> None:
"""Generates a HTML file summarizing the report in a human-readable format.
Args:
report_file_name: a HTML report file name to create.
report_book: a report book instance containing all reports.
covered_cves: a sequence of CVEs covered by this run.
stats: |ScannedFileStats| object with scan result stats.
Returns:
None
"""
env = jinja2.Environment()
template = env.from_string(_HTML_REPORT_TEMPLATE)
target_missing_patches = collections.defaultdict(
lambda: collections.defaultdict(set))
non_target_missing_patches = collections.defaultdict(
lambda: collections.defaultdict(set))
for osv_id in report_book.unpatched_vulnerabilities:
report_groups = report_book.get_report_group(osv_id)
if not report_groups:
continue
target_match_summaries = set()
non_target_match_summaries = set()
for report in report_groups.reports:
summary = report.get_simple_report(
include_patch_source=True, use_html_link_for_patch_source=True)
if report.is_non_target_match:
non_target_match_summaries.add(summary)
else:
target_match_summaries.add(summary)
cve_ids = report_groups.cve_ids
if target_match_summaries:
target_missing_patches[osv_id]['summaries'] = target_match_summaries
target_missing_patches[osv_id]['osv_url'] = _get_public_osv_url(osv_id)
target_missing_patches[osv_id]['cve_ids'] = cve_ids if cve_ids else []
if non_target_match_summaries:
non_target_missing_patches[osv_id]['summaries'] = (
non_target_match_summaries)
non_target_missing_patches[osv_id]['osv_url'] = _get_public_osv_url(
osv_id)
non_target_missing_patches[osv_id]['cve_ids'] = cve_ids if cve_ids else []
metadata = {
**(stats.scan_metadata or {}),
'analyzed_files': stats.analyzed_files,
'skipped_files': stats.skipped_files}
html_report = template.render(
report_file_name=report_file_name,
covered_cves=covered_cves,
unpatched_cves=report_book.unpatched_cves,
target_missing_patches=target_missing_patches,
non_target_missing_patches=non_target_missing_patches,
options=' '.join(sys.argv[1:]),
metadata=metadata,
errors=stats.errors,
)
with open(report_file_name, 'w') as f:
f.write(html_report)
def main(argv: Sequence[str]) -> None:
scanners = _get_all_scanners()
scanners_list_str = '\n\n'.join(
f'- {scanner.name()}: {scanner.__doc__ if scanner.__doc__ else ""}'
for scanner in scanners.values())
if len(argv) <= 1:
raise app.UsageError(
f'Scanner is not specified. Known scanners:\n{scanners_list_str}')
scanner_name = argv[1]
if scanner_name not in scanners:
raise app.UsageError(
f'{scanner_name} is not a valid scanner. Known scanners:\n'
f'{scanners_list_str}')
scanner_class = scanners[scanner_name]
scanner_args = argv[2:]
if not _is_valid_scanner_args(scanner_class, scanner_args):
raise app.UsageError(_get_scanner_usage_str(scanner_class))
if not flags.FLAGS['verbosity'].present:
# If verbosity was not explicitly set, use default INFO verbosity.
# This is needed because app.run() overwrites the verbosity.
flags.FLAGS.verbosity = logging.INFO
logging.use_python_logging(quiet=True)
# Check if output file can be generated before start scanning.
output_file_name_prefix = _REPORT_FILE_NAME_PREFIX.value
if not output_file_name_prefix:
output_file_name_prefix = (
'/tmp/vanir/report-%s'
% datetime.datetime.now().strftime('%Y%m%d%H%M%S')
)
directory = os.path.dirname(os.path.realpath(output_file_name_prefix))
os.makedirs(directory, exist_ok=True)
json_output_file_name = output_file_name_prefix + '.json'
html_output_file_name = output_file_name_prefix + '.html'
for output_file_name in [json_output_file_name, html_output_file_name]:
report_file = open(output_file_name, 'w')
report_file.close()
scanner = scanner_class(*scanner_args)
findings, stats, vuln_manager = scanner.scan(
strategy=flags.FLAGS['target_selection_strategy'].value,
override_vuln_manager=(
detector_common_flags.generate_vuln_manager_from_flags()
),
extra_vulnerability_filters=(
detector_common_flags.generate_vulnerability_filters_from_flags()
),
)
finding_filters = (
[scanner_base.ShortFunctionFilter()]
+ list(detector_common_flags.generate_finding_filters_from_flags())
)
findings = scanner_base.ShortFunctionFilter().filter(findings)
for finding_filter in finding_filters:
findings = finding_filter.filter(findings)
report_book = reporter.ReportBook(
reporter.generate_reports(findings), vuln_manager
)
unpatched_cves = report_book.unpatched_cves
signatures = vuln_manager.signatures
covered_cves = itertools.chain.from_iterable(
[vuln_manager.sign_id_to_cve_ids(sign.signature_id)
for sign in signatures]
)
covered_cves = sorted(set(covered_cves))
# Generate a machine-readable JSON report.
_generate_json_report(json_output_file_name, report_book, covered_cves)
# Generate a human-readable HTML report.
_generate_html_report(html_output_file_name, report_book, covered_cves, stats)
# Generate a console output.
scanned_files = stats.analyzed_files + stats.skipped_files
if scanned_files < _MINIMUM_NUMBER_OF_FILES.value:
logging.error(
'The scanned target directory contains only %s file(s) supported by'
' Vanir. Please confirm that this is intended.\n',
scanned_files,
)
elif stats.analyzed_files < _MINIMUM_NUMBER_OF_FILES.value:
logging.error(
'The scanned target directory contains only %s file(s) analyzed by'
' Vanir (%s file(s) were skipped). Please confirm that this is'
' intended. This might happen when a wrong |target_root| is passed.',
stats.analyzed_files,
stats.skipped_files,
)
message = (
f'Scanned {stats.analyzed_files} source files '
f'(skipped {stats.skipped_files} source files likely unaffected by '
'known vulnerabilities).\n'
f'Found {len(unpatched_cves)} potentially unpatched vulnerabilities: '
f'{", ".join(unpatched_cves)}\n'
f'Detailed report:\n - {html_output_file_name}\n'
f' - {json_output_file_name}'
)
print(message)
if __name__ == '__main__':
app.run(main)