-
-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathdefault.py
More file actions
149 lines (129 loc) · 5.74 KB
/
default.py
File metadata and controls
149 lines (129 loc) · 5.74 KB
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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# VulnerableCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/aboutcode-org/vulnerablecode for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import logging
from typing import Iterable
from typing import List
from typing import Tuple
from django.db.models import Q
from django.db.models.query import QuerySet
from packageurl import PackageURL
from vulnerabilities.importer import AdvisoryData
from vulnerabilities.importer import AffectedPackage
from vulnerabilities.importer import Importer
from vulnerabilities.improver import MAX_CONFIDENCE
from vulnerabilities.improver import Improver
from vulnerabilities.improver import Inference
from vulnerabilities.models import Advisory
from vulnerabilities.utils import update_purl_version
logger = logging.getLogger(__name__)
class DefaultImprover(Improver):
"""
Generate a translation of Advisory data - returned by the importers - into
full confidence inferences. These are basic database relationships for
unstructured data present in the Advisory model without any other
information source.
"""
importer: Importer
@property
def interesting_advisories(self) -> QuerySet:
if hasattr(self, "importer"):
return (
Advisory.objects.filter(Q(created_by=self.importer.qualified_name))
.order_by("-date_collected")
.iterator()
)
return Advisory.objects.all().order_by("-date_collected").iterator()
def get_inferences(self, advisory_data: AdvisoryData) -> Iterable[Inference]:
if not advisory_data:
return []
if advisory_data.affected_packages:
for affected_package in advisory_data.affected_packages:
# To deal with multiple fixed versions in a single affected package
affected_purls, fixed_purls = get_exact_purls(affected_package)
if not fixed_purls:
yield Inference(
aliases=advisory_data.aliases,
confidence=MAX_CONFIDENCE,
summary=advisory_data.summary,
affected_purls=affected_purls,
fixed_purl=None,
references=advisory_data.references,
weaknesses=advisory_data.weaknesses,
)
else:
for fixed_purl in fixed_purls or []:
yield Inference(
aliases=advisory_data.aliases,
confidence=MAX_CONFIDENCE,
summary=advisory_data.summary,
affected_purls=affected_purls,
fixed_purl=fixed_purl,
references=advisory_data.references,
weaknesses=advisory_data.weaknesses,
)
else:
yield Inference.from_advisory_data(
advisory_data, confidence=MAX_CONFIDENCE, fixed_purl=None
)
def get_exact_purls(affected_package: AffectedPackage) -> Tuple[List[PackageURL], PackageURL]:
"""
Return a list of affected purls and the fixed package found in the ``affected_package``
AffectedPackage disregarding any ranges.
Only exact version constraints (ie with an equality) are considered
For eg:
>>> purl = {"type": "turtle", "name": "green"}
>>> vers = "vers:npm/<1.0.0 | >=2.0.0 | <3.0.0"
>>> affected_package = AffectedPackage.from_dict({
... "package": purl,
... "affected_version_range": vers,
... "fixed_version": "5.0.0"
... })
>>> got = get_exact_purls(affected_package)
>>> expected = (
... [PackageURL(type='turtle', namespace=None, name='green', version='2.0.0', qualifiers={}, subpath=None)],
... [PackageURL(type='turtle', namespace=None, name='green', version='5.0.0', qualifiers={}, subpath=None)]
... )
>>> assert expected == got
"""
if not affected_package:
return [], []
try:
vr = affected_package.affected_version_range
# We need ``if c`` below because univers returns None as version
# in case of vers:nginx/*
# TODO: Revisit after https://github.com/nexB/univers/issues/33
affected_purls = []
fixed_versions = []
if vr:
range_versions = [c.version for c in vr.constraints if c]
# Any version that's not affected by a vulnerability is considered
# fixed.
fixed_versions = [c.version for c in vr.constraints if c and c.comparator == "!="]
resolved_versions = [v for v in range_versions if v and v in vr]
for version in resolved_versions:
affected_purl = update_purl_version(
purl=affected_package.package, version=str(version)
)
affected_purls.append(affected_purl)
if affected_package.fixed_version:
fixed_versions.append(affected_package.fixed_version)
fixed_purls = [
update_purl_version(purl=affected_package.package, version=str(version))
for version in fixed_versions
]
return affected_purls, fixed_purls
except Exception as e:
logger.error(f"Failed to get exact purls for: {affected_package!r} with error: {e!r}")
return [], []
class DefaultImporter(DefaultImprover):
def __init__(self, advisories) -> None:
self.advisories = advisories
@property
def interesting_advisories(self) -> QuerySet:
return self.advisories