Skip to content

Commit 2b01f12

Browse files
committed
add Snyk DataSource
- closes #834 Signed-off-by: Keshav Priyadarshi <git@keshav.space>
1 parent 78dd5ae commit 2b01f12

2 files changed

Lines changed: 183 additions & 1 deletion

File tree

vulntotal/datasources/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
# Visit https://github.com/nexB/vulnerablecode/ for support and download.
2323

2424

25-
DATASOURCE_REGISTRY = []
25+
from vulntotal.datasources import snyk
26+
27+
DATASOURCE_REGISTRY = [
28+
snyk.SnykDataSource,
29+
]
2630

2731
DATASOURCE_REGISTRY = {x.__module__.split(".")[-1]: x for x in DATASOURCE_REGISTRY}

vulntotal/datasources/snyk.py

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
#
2+
# Copyright (c) nexB Inc. and others. All rights reserved.
3+
# http://nexb.com and https://github.com/nexB/vulnerablecode/
4+
# The VulnTotal software is licensed under the Apache License version 2.0.
5+
# Data generated with VulnTotal require an acknowledgment.
6+
#
7+
# You may not use this software except in compliance with the License.
8+
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
9+
# Unless required by applicable law or agreed to in writing, software distributed
10+
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11+
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
12+
# specific language governing permissions and limitations under the License.
13+
#
14+
# When you publish or redistribute any data created with VulnTotal or any VulnTotal
15+
# derivative work, you must accompany this data with the following acknowledgment:
16+
#
17+
# Generated with VulnTotal and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
18+
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
19+
# VulnTotal should be considered or used as legal advice. Consult an Attorney
20+
# for any legal advice.
21+
# VulnTotal is a free software tool from nexB Inc. and others.
22+
# Visit https://github.com/nexB/vulnerablecode/ for support and download.
23+
24+
import json
25+
import logging
26+
from typing import Iterable
27+
from urllib.parse import quote
28+
29+
import requests
30+
from bs4 import BeautifulSoup
31+
from packageurl import PackageURL
32+
33+
from vulntotal.validator import DataSource
34+
from vulntotal.validator import VendorData
35+
from vulntotal.vulntotal_utils import snky_constraints_satisfied
36+
37+
logger = logging.getLogger(__name__)
38+
39+
40+
class SnykDataSource(DataSource):
41+
spdx_license_expression = "TODO"
42+
license_url = "TODO"
43+
44+
def fetch(self, url):
45+
response = requests.get(url)
46+
if not response.status_code == 200:
47+
logger.error(f"Error while fetching {url}")
48+
return
49+
if response.headers["content-type"] == "application/json, charset=utf-8":
50+
return response.json()
51+
return response.text
52+
53+
def datasource_advisory(self, purl) -> Iterable[VendorData]:
54+
package_advisory_url = generate_package_advisory_url(purl)
55+
package_advisories_list = self.fetch(package_advisory_url)
56+
self._raw_dump.append(package_advisories_list)
57+
if package_advisories_list:
58+
advisories = extract_html_json_advisories(package_advisories_list)
59+
for snyk_id, affected in advisories.items():
60+
if "*" in affected or is_purl_in_affected(purl.version, affected):
61+
advisory_payload = generate_advisory_payload(snyk_id)
62+
advisory_html = self.fetch(advisory_payload)
63+
self._raw_dump.append(advisory_html)
64+
if advisory_html:
65+
yield parse_html_advisory(advisory_html, snyk_id, affected)
66+
67+
@classmethod
68+
def supported_ecosystem(cls):
69+
return {
70+
"cocoapods": "cocoapods",
71+
"composer": "composer",
72+
"golang": "golang",
73+
"hex": "hex",
74+
"linux": "linux",
75+
"maven": "maven",
76+
"npm": "npm",
77+
"nuget": "nuget",
78+
"pypi": "pip",
79+
"rubygems": "rubygems",
80+
# any purl.type not in supported_ecosystem shall implicitly be treated as unmanaged type
81+
"unmanaged": "unmanaged",
82+
}
83+
84+
85+
def generate_package_advisory_url(purl):
86+
url_package_advisories = "https://security.snyk.io/package/{ecosystem}/{package}"
87+
88+
# Pseudo API, unfortunately gives only 30 vulnerability per package, but this is the best we have for unmanaged packages
89+
url_unmanaged_package_advisories = (
90+
"https://security.snyk.io/api/listing?search={package}&type=unmanaged"
91+
)
92+
supported_ecosystem = SnykDataSource.supported_ecosystem()
93+
94+
if purl.type == "unmanaged" or purl.type not in supported_ecosystem:
95+
return url_unmanaged_package_advisories.format(
96+
package=purl.name if not purl.namespace else f"{purl.namespace}/{purl.name}",
97+
)
98+
99+
purl_name = purl.name
100+
if purl.type == "maven":
101+
if not purl.namespace:
102+
logger.error(f"Invalid Maven PURL {str(purl)}")
103+
return
104+
purl_name = quote(f"{purl.namespace}:{purl.name}", safe="")
105+
106+
elif purl.type in ("golang", "composer"):
107+
if purl.namespace:
108+
purl_name = quote(f"{purl.namespace}/{purl.name}", safe="")
109+
110+
elif purl.type == "linux":
111+
distro = purl.qualifiers["distro"]
112+
purl_name = f"{distro}/{purl.name}"
113+
114+
return url_package_advisories.format(
115+
ecosystem=supported_ecosystem[purl.type],
116+
package=purl_name,
117+
)
118+
119+
120+
def extract_html_json_advisories(package_advisories):
121+
vulnerablity = {}
122+
123+
# If advisories are json and is obtained through pseudo API
124+
if isinstance(package_advisories, dict):
125+
if package_advisories["status"] == "ok":
126+
for vuln in package_advisories["vulnerabilities"]:
127+
vulnerablity[vuln["id"]] = vuln["semver"]["vulnerable"]
128+
else:
129+
soup = BeautifulSoup(package_advisories, "html.parser")
130+
vulns_table = soup.find("tbody", class_="vue--table__tbody")
131+
if vulns_table:
132+
vulns_rows = vulns_table.find_all("tr", class_="vue--table__row")
133+
for row in vulns_rows:
134+
anchor = row.find(class_="vue--anchor")
135+
ranges = row.find_all(
136+
"span", class_="vue--chip vulnerable-versions__chip vue--chip--default"
137+
)
138+
affected_versions = [vers.text.strip() for vers in ranges]
139+
vulnerablity[anchor["href"].rsplit("/", 1)[-1]] = affected_versions
140+
return vulnerablity
141+
142+
143+
def parse_html_advisory(advisory_html, snyk_id, affected) -> VendorData:
144+
aliases = []
145+
fixed_versions = []
146+
147+
advisory_soup = BeautifulSoup(advisory_html, "html.parser")
148+
cve_span = advisory_soup.find("span", class_="cve")
149+
if cve_span:
150+
cve_anchor = cve_span.find("a", class_="vue--anchor")
151+
aliases.append(cve_anchor["id"])
152+
153+
how_to_fix = advisory_soup.find(
154+
"div", class_="vue--block vuln-page__instruction-block vue--block--instruction"
155+
)
156+
if how_to_fix:
157+
fixed = how_to_fix.find("p").text.split(" ")
158+
if "Upgrade" in fixed:
159+
lower = fixed.index("version") if "version" in fixed else fixed.index("versions")
160+
upper = fixed.index("or")
161+
fixed_versions = "".join(fixed[lower + 1 : upper]).split(",")
162+
aliases.append(snyk_id)
163+
return VendorData(
164+
aliases=aliases,
165+
affected_versions=affected,
166+
fixed_versions=fixed_versions,
167+
)
168+
169+
170+
def is_purl_in_affected(version, affected):
171+
for affected_range in affected:
172+
if snky_constraints_satisfied(affected_range, version):
173+
return True
174+
return False
175+
176+
177+
def generate_advisory_payload(snyk_id):
178+
return f"https://security.snyk.io/vuln/{snyk_id}"

0 commit comments

Comments
 (0)