This repository has been archived by the owner on Mar 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
vulncode_db.py
334 lines (292 loc) · 13.1 KB
/
vulncode_db.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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sqlakeyset # type: ignore
from sqlakeyset.columns import OC # type: ignore
from app.vulnerability.views.vulnerability import VulnerabilityView
from app.vulnerability.views.details import VulnerabilityDetails
from flask import request
from flask_sqlalchemy import Pagination # type: ignore
from sqlakeyset import get_page
from sqlakeyset.results import Paging # type: ignore
from sqlalchemy import func, desc, or_, asc, exc
from sqlalchemy.orm import class_mapper, Mapper
from data.database import DEFAULT_DATABASE
from data.models.nvd import default_nvd_view_options
from data.models import (Description, Nvd, Vulnerability,
RepositoryFileComments, User, RepositoryFileMarkers)
from lib.utils import parse_pagination_param
db = DEFAULT_DATABASE
def custom_value_from_thing(thing, desc, ocol):
"""
Replacement function for the sqlakeyset value_from_thing method.
This function supports auto aliasing as is required when sorting by
columns that appear in subqueries.
:param thing:
:param desc:
:param ocol:
:return:
"""
entity = desc['entity']
expr = desc['expr']
try:
is_a_table = entity == expr
except exc.ArgumentError:
is_a_table = False
if isinstance(expr, Mapper) and expr.class_ == entity:
# Is a table mapper. Just treat as a table.
is_a_table = True
if type(is_a_table) == bool and is_a_table: # is a table
mapper = class_mapper(desc['type'])
base_elem = ocol.element.base_columns
if not base_elem:
base_elem = ocol.element
elif len(base_elem) == 1:
base_elem = next(iter(base_elem))
else:
raise ValueError("Multiple columns")
# If the OCOL is a hybrid attribute it won't belong to one table.
if not hasattr(base_elem, 'table'):
raise ValueError
order_column_table = base_elem.table.name
if entity.__table__.name == order_column_table:
prop = mapper.get_property_by_column(base_elem)
return getattr(thing, prop.key)
else:
raise ValueError
# is an attribute
if hasattr(expr, 'info'):
mapper = expr.parent
tname = mapper.local_table.description
if ocol.table_name == tname and ocol.name == expr.name:
return thing
else:
raise ValueError
import re
ocol_quoted_full_name = re.sub('[()]', '', ocol.quoted_full_name)
# is an attribute with label
if ocol_quoted_full_name == OC(expr).full_name:
return thing
else:
raise ValueError
class VulncodeDB:
#
# def getEntriesWithPatch(self):
# cve_entries = select([Nvd, Vulnerability]).select_from(
# outerjoin(Nvd, Vulnerability)).apply_labels() #.order_by(desc(Vulnerability.date_created))
#
#
# # TODO: find performant way to simulate "union" or to deduplicate the
# # entries from both data sets... This still takes ~800ms :/...
# query_union = db.session.query(Nvd, Vulnerability).select_entity_from(
# vcdb_entries.union_all(cve_entries))
# #
# #cve_entries = db.session.query(Nvd, Vulnerability).outerjoin(Vulnerability)
# #query_union = vcdb_entries.union(cve_entries)
#
# #entry = query_union[0]
#
# #entry = entries[0]
#
# #entries = Nvd.get_all_by_link_regex(cfg.PATCH_REGEX)
# return query_union
# @measure_execution_time('Vulncode-DB Constructor')
def __init__(self):
self.keyword = None
# TODO: Look into neabling this once public contributions are enabled.
# self.top_contributors = []
# self.fetch_top_contributors()
has_annotations_col = Vulnerability.has_annotations
vcdb_entries = db.session.query(Vulnerability, Nvd,
has_annotations_col)
vcdb_entries = vcdb_entries.outerjoin(
Nvd, Vulnerability.cve_id == Nvd.cve_id)
vcdb_entries = vcdb_entries.options(default_nvd_view_options)
vcdb_entries = vcdb_entries.from_self()
vcdb_entries = vcdb_entries.order_by(desc(has_annotations_col),
asc(Vulnerability.date_created),
desc(Vulnerability.id))
self.vcdb_entries = vcdb_entries
nvd_entries = db.session.query(Nvd)
nvd_entries = nvd_entries.outerjoin(Vulnerability,
Nvd.cve_id == Vulnerability.cve_id)
nvd_entries = nvd_entries.options(default_nvd_view_options)
nvd_entries = nvd_entries.filter(Vulnerability.cve_id.is_(None))
nvd_entries = nvd_entries.order_by(desc(Nvd.published_date),
desc(Nvd.id))
self.nvd_entries = nvd_entries
self.keyword = request.args.get("keyword", None, type=str)
apply_filter = None
if self.keyword:
# TODO: Make the filtering work with fulltext search as well.
if VulnerabilityDetails.is_cve_id(self.keyword):
apply_filter = or_(False, Nvd.cve_id == self.keyword)
elif VulnerabilityDetails.is_vcdb_id(self.keyword):
apply_filter = or_(False, Vulnerability.id == self.keyword)
else:
escaped_keyword = self.keyword.replace("%", "")
# escaped_keyword = re.sub('[\W]+', ' ', self.keyword)
# Attention: We can't use FullText search here because of some buggy
# Mysql 5.7 behavior (using FullText on Join results seems is doing bad
# things. We might need to apply the filter before joining below.
# apply_filter = or_(
# FullTextSearch(escaped_keyword, Nvd, FullTextMode.BOOLEAN),
# FullTextSearch(escaped_keyword, Vulnerability, FullTextMode.BOOLEAN))
apply_filter = or_(
Nvd.descriptions.any(
Description.value.like("%" + escaped_keyword + "%")),
Vulnerability.comment.like("%" + escaped_keyword + "%"),
)
# TODO: add product search support.
# apply_filter = or_(apply_filter, Cpe.product == keyword)
if apply_filter is not None:
self.vcdb_entries = self.vcdb_entries.filter(apply_filter)
self.nvd_entries = self.nvd_entries.filter(apply_filter)
per_page = 7
vcdb_bookmarked_page = parse_pagination_param("vcdb_p")
# Replace a sqlakeyset function to support our use case. TODO: File a PR for this?
sqlakeyset.paging.value_from_thing = custom_value_from_thing
self.vcdb_pagination = get_page(self.vcdb_entries,
per_page,
page=vcdb_bookmarked_page)
self.vcdb_pagination = VulnViewTypesetPaginationObjectWrapper(
self.vcdb_pagination.paging)
num_vuln_entries = db.session.query(func.count(
Vulnerability.id)).scalar()
self.vcdb_pagination.set_total(num_vuln_entries)
nvd_bookmarked_page = parse_pagination_param("nvd_p")
self.nvd_pagination = get_page(self.nvd_entries,
per_page,
page=nvd_bookmarked_page)
self.nvd_pagination = VulnViewTypesetPaginationObjectWrapper(
self.nvd_pagination.paging)
num_nvd_entries = db.session.query(func.count(Nvd.id)).scalar()
num_unique_nvd_estimate = num_nvd_entries - num_vuln_entries
self.nvd_pagination.set_total(num_unique_nvd_estimate)
# @measure_execution_time('TOP CONTRIB')
def fetch_top_contributors(self):
# TODO: count number of contributions to vulnerabilities instead of single annotations
num_comments = self.get_annotation_query(RepositoryFileComments)
num_markers = self.get_annotation_query(RepositoryFileMarkers)
num_both = num_comments.c.count + num_markers.c.count
self.top_contributors = (db.session.query(
User,
func.coalesce(num_comments.c.count, 0).label("num_comments"),
func.coalesce(num_markers.c.count, 0).label("num_markers"),
).outerjoin(
num_comments, num_comments.c.creator_id == User.id).outerjoin(
num_markers, num_markers.c.creator_id == User.id).filter(
num_both > 0).order_by(num_both.desc()).limit(10).all())
@staticmethod
def get_annotation_query(model):
return (db.session.query(
model.creator_id.label("creator_id"),
func.count(1).label("count")).filter_by(active=True).group_by(
model.creator_id).subquery())
# @measure_execution_time('NEW 1')
# def _new_method(self):
# files_with_comments = select(
# [distinct(RepositoryFileComments.repository_file_id)])
# commits_with_comments = db.session.query(
# distinct(RepositoryFiles.commit_id)).filter(
# RepositoryFiles.id.in_(files_with_comments))
# base_query = Vulnerability.query.join(Vulnerability.commits)
# self.annotated_entries = base_query.filter(
# VulnerabilityGitCommits.id.in_(commits_with_comments)).all()
# #self.empty_entries = base_query.filter(
# #~VulnerabilityGitCommits.id.in_(commits_with_comments)).all()
# @measure_execution_time('NEW 2')
# def _new_method2(self):
# base_query = Vulnerability.query.join(
# Vulnerability.commits, VulnerabilityGitCommits.repository_files,
# RepositoryFiles.comments)
# # print base_query.having(func.count(RepositoryFileComments.id) > 0)
# self.annotated_entries = base_query.having(
# func.count(RepositoryFileComments.id) > 0).all()
# self.empty_entries = base_query.having(
# func.count(RepositoryFileComments.id) == 0).all()
# @measure_execution_time('OLD')
# def _old_method(self):
# self.annotated_entries = []
# self.empty_entries = []
# all_entries = Vulnerability.query.all()
#
# for entry in all_entries:
# master_commit = entry.commits[0]
# if master_commit.num_comments > 0:
# self.annotated_entries.append(entry)
# else:
# self.empty_entries.append(entry)
def wrap_entries(target_entries):
"""
Wraps all Vulnerability/Nvd entries into the VulnerabilityView class.
:return:
"""
new_entries = []
if not target_entries:
return
first_element = target_entries[0]
if isinstance(first_element, Nvd):
for nvd in target_entries:
vuln_view = VulnerabilityView(None, nvd, preview=True)
new_entries.append(vuln_view)
elif isinstance(first_element, Vulnerability):
for vulnerability in target_entries:
vuln_view = VulnerabilityView(vulnerability, None, preview=True)
new_entries.append(vuln_view)
else:
for columns in target_entries:
vulnerability = columns[0]
nvd = columns[1]
if len(columns) > 2 and type(columns[2]) is bool:
annotation_exists = columns[2]
vulnerability.set_has_annotations(annotation_exists)
vuln_view = VulnerabilityView(vulnerability, nvd, preview=True)
new_entries.append(vuln_view)
del target_entries[:]
target_entries.extend(new_entries)
class VulnViewTypesetPaginationObjectWrapper(Paging):
"""
An sqlakeyset Paging object wrapper class which wraps Vuln/Nvd rows
inside a VulnView.
"""
def __init__(self, paginationObject):
"""
:param paginationObject: A Flask SQLalchemy Pagination object.
"""
self.__class__ = type(
paginationObject.__class__.__name__,
(self.__class__, paginationObject.__class__),
{},
)
self.__dict__ = paginationObject.__dict__
self.total = 0
wrap_entries(self.rows)
def set_total(self, new_total):
self.total = new_total
class VulnViewSqlalchemyPaginationObjectWrapper(Pagination):
"""
A Flask SQLAlchemy Pagination object wrapper class which wraps Vuln/Nvd rows
inside a VulnView.
"""
def __init__(self, paginationObject):
"""
:param paginationObject: A Flask SQLalchemy Pagination object.
"""
self.__class__ = type(
paginationObject.__class__.__name__,
(self.__class__, paginationObject.__class__),
{},
)
self.__dict__ = paginationObject.__dict__
wrap_entries(self.items)