forked from intel/cve-bin-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_scanner.py
195 lines (176 loc) · 7.38 KB
/
test_scanner.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
# pylint: disable=too-many-public-methods, too-many-arguments, fixme
"""
CVE-bin-tool tests
"""
import importlib
import os
import shutil
import sys
import tempfile
import unittest
import pytest
from cve_bin_tool.cvedb import CVEDB
from cve_bin_tool.version_scanner import VersionScanner
from .test_data import __all__ as all_test_name
from .utils import download_file, LONG_TESTS
BINARIES_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), "binaries")
# load test data
test_data = list(
map(lambda x: importlib.import_module(f"test.test_data.{x}"), all_test_name)
)
mapping_test_data = map(lambda x: x.mapping_test_data, test_data)
package_test_data = map(lambda x: x.package_test_data, test_data)
class TestScanner:
"""Runs a series of tests against our "faked" binaries.
The faked binaries are very small c files containing the same string signatures we use
in the cve-bin-tool. They should trigger results as if they contained the library and
version specified in the file name.
At this time, the tests work only in python3.
"""
@classmethod
def setup_class(cls):
cls.cvedb = CVEDB()
if os.getenv("UPDATE_DB") == "1":
cls.cvedb.get_cvelist_if_stale()
else:
print("Skip NVD database updates.")
# Instantiate a scanner
cls.scanner = VersionScanner(should_extract=True)
# temp dir for mapping tests
cls.mapping_test_dir = tempfile.mkdtemp(prefix="mapping-test-")
# temp dir for tests that require downloads
cls.package_test_dir = tempfile.mkdtemp(prefix="package_test-")
@classmethod
def teardown_class(cls):
shutil.rmtree(cls.package_test_dir)
shutil.rmtree(cls.mapping_test_dir)
def test_false_positive(self):
self.scanner.all_cves = []
with tempfile.NamedTemporaryFile(
"w+b",
suffix="-test-false-positive.out",
dir=self.mapping_test_dir,
delete=False,
) as f:
common_signatures = [
# common strings generated by a compiler
b"\x7f\x45\x4c\x46\x02\x01\x01\x03\n",
b"GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0\n",
b"GNU C17 8.1.0 -mtune=core2 -march=nocona -g -g -g -O2 -O2 -O2 -fno-ident -fbuilding-libgcc -fno-stack-protector\n",
b"../../../../../src/gcca-8.1.0/libgcc/libgcc2.c\n",
rb"C:\mingw810\x86_64-810-posix-seh-rt_v6-rev0\build\gcca-8.1.0\x86_64-w64-mingw32\libgcc\n",
b"GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0\n",
# bare version strings.
b"1_0",
b"1_2_3",
b"1.4",
b"1.2.3",
b"6.7a",
b"8.9.10-11",
b"1-2",
b"1-2-4",
b"1.2.3-rc.1",
]
f.writelines(common_signatures)
filename = f.name
for params in self.scanner.scan_file(
os.path.join(self.mapping_test_dir, filename)
):
if params:
pytest.fail(msg=f"Checker has detected false positive: {params}")
@pytest.mark.parametrize(
"product, version, version_strings",
(
(d["product"], d["version"], d["version_strings"])
for list_data in mapping_test_data
for d in list_data
),
)
def test_version_mapping(self, product, version, version_strings):
"""Helper function to scan a binary and check that it contains
certain cves for a version and doesn't contain others."""
# Run the scan
version_strings = list(map(lambda s: f"{s}\n".encode("ascii"), version_strings))
# first filename will test "is" and second will test "contains"
filenames = [
f"-{product}-{version}.out",
f"{'.'.join(list(product))}-{version}.out",
]
for filename in filenames:
with tempfile.NamedTemporaryFile(
"w+b", suffix=filename, dir=self.mapping_test_dir, delete=False
) as f:
f.write(b"\x7f\x45\x4c\x46\x02\x01\x01\x03\n")
f.writelines(version_strings)
filename = f.name
list_products = set()
list_versions = set()
expected_path = os.path.join(self.mapping_test_dir, filename)
for scan_info in self.scanner.recursive_scan(expected_path):
if scan_info:
product_info, file_path = scan_info
list_products.add(product_info.product)
list_versions.add(product_info.version)
assert file_path == expected_path
assert product in list_products
assert version in list_versions
@pytest.mark.parametrize(
"url, package_name, product, version",
(
(d["url"], d["package_name"], d["product"], d["version"])
for list_data in package_test_data
for d in list_data
),
)
@unittest.skipUnless(LONG_TESTS() > 0, "Skipping long tests")
def test_version_in_package(self, url, package_name, product, version):
"""Helper function to get a file (presumed to be a real copy
of a library, probably from a Linux distribution) and run a
scan on it. Any test using this should likely be listed as a
long test."""
# get file
tempfile = os.path.join(self.package_test_dir, package_name)
download_file(url + package_name, tempfile)
# new scanner for the new test.
# self.scanner = VersionScanner(self.cve_scanner, should_extract=True)
# run the tests
list_products = set()
list_versions = set()
for scan_info in self.scanner.recursive_scan(tempfile):
if scan_info:
product_info, file_path = scan_info
list_products.add(product_info.product)
list_versions.add(product_info.version)
# Make sure the product and version are in the results
assert product in list_products
assert version in list_versions
def test_does_not_scan_symlinks(self):
""" Test that the scanner doesn't scan symlinks """
if sys.platform.startswith("linux"):
# we can only do this in linux since symlink is privilege operation in windows
os.symlink("non-existant-file", "non-existant-link")
try:
with pytest.raises(StopIteration):
next(
self.scanner.scan_file(
os.path.join(self.mapping_test_dir, "non-existant-link")
)
)
finally:
os.unlink("non-existant-link")
def test_cannot_open_file(self, caplog):
""" Test behaviour when file cannot be opened """
with pytest.raises(StopIteration):
next(
self.scanner.scan_file(
os.path.join(self.mapping_test_dir, "non-existant-file")
)
)
assert str.find("Invalid file", caplog.text)
def test_clean_file_path(self):
filepath = (
"/tmp/cve-bin-tool/dhtei34fd/file_name.extracted/usr/bin/vulnerable_file"
)
expected_path = "/usr/bin/vulnerable_file"
cleaned_path = self.scanner.clean_file_path(filepath)
assert expected_path == cleaned_path