forked from DependencyTrack/dependency-track
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindingsSearchQueryManager.java
More file actions
405 lines (383 loc) · 21.7 KB
/
Copy pathFindingsSearchQueryManager.java
File metadata and controls
405 lines (383 loc) · 21.7 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
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
/*
* This file is part of Dependency-Track.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) OWASP Foundation. All Rights Reserved.
*/
package org.dependencytrack.persistence;
import alpine.persistence.OrderDirection;
import alpine.persistence.PaginatedResult;
import alpine.resources.AlpineRequest;
import alpine.server.util.DbUtil;
import com.github.packageurl.PackageURL;
import org.dependencytrack.model.Analysis;
import org.dependencytrack.model.Component;
import org.dependencytrack.model.Finding;
import org.dependencytrack.model.GroupedFinding;
import org.dependencytrack.model.RepositoryMetaComponent;
import org.dependencytrack.model.RepositoryType;
import org.dependencytrack.model.Vulnerability;
import org.dependencytrack.model.VulnerabilityAlias;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class FindingsSearchQueryManager extends QueryManager implements IQueryManager {
private static final Map<String, String> sortingAttributes = Map.ofEntries(
Map.entry("vulnerability.vulnId", "\"VULNERABILITY\".\"VULNID\""),
Map.entry("vulnerability.title", "\"VULNERABILITY\".\"TITLE\""),
Map.entry("vulnerability.severity", """
CASE WHEN "VULNERABILITY"."SEVERITY" = 'UNASSIGNED'
THEN 0
WHEN "VULNERABILITY"."SEVERITY" = 'LOW'
THEN 3
WHEN "VULNERABILITY"."SEVERITY" = 'MEDIUM'
THEN 6
WHEN "VULNERABILITY"."SEVERITY" = 'HIGH'
THEN 8
WHEN "VULNERABILITY"."SEVERITY" = 'CRITICAL'
THEN 10
ELSE CASE WHEN "VULNERABILITY"."CVSSV4SCORE" IS NOT NULL
THEN "VULNERABILITY"."CVSSV4SCORE"
WHEN "VULNERABILITY"."CVSSV3BASESCORE" IS NOT NULL
THEN "VULNERABILITY"."CVSSV3BASESCORE"
ELSE "VULNERABILITY"."CVSSV2BASESCORE"
END
END
"""),
Map.entry("attribution.analyzerIdentity", "\"FINDINGATTRIBUTION\".\"ANALYZERIDENTITY\""),
Map.entry("vulnerability.published", "\"VULNERABILITY\".\"PUBLISHED\""),
Map.entry("vulnerability.cvssV2BaseScore", "\"VULNERABILITY\".\"CVSSV2BASESCORE\""),
Map.entry("vulnerability.cvssV3BaseScore", "\"VULNERABILITY\".\"CVSSV3BASESCORE\""),
Map.entry("vulnerability.cvssV4Score", "\"VULNERABILITY\".\"CVSSV4SCORE\""),
Map.entry("component.projectName", "concat(\"PROJECT\".\"NAME\", ' ', \"PROJECT\".\"VERSION\")"),
Map.entry("component.name", "\"COMPONENT\".\"NAME\""),
Map.entry("component.version", "\"COMPONENT\".\"VERSION\""),
Map.entry("analysis.state", "\"ANALYSIS\".\"STATE\""),
Map.entry("analysis.isSuppressed", "\"ANALYSIS\".\"SUPPRESSED\""),
Map.entry("attribution.attributedOn", "\"FINDINGATTRIBUTION\".\"ATTRIBUTED_ON\""),
Map.entry("vulnerability.affectedProjectCount", "COUNT(DISTINCT \"PROJECT\".\"ID\")")
);
/**
* Constructs a new QueryManager.
* @param pm a PersistenceManager object
*/
FindingsSearchQueryManager(final PersistenceManager pm) {
super(pm);
}
/**
* Constructs a new QueryManager.
* @param pm a PersistenceManager object
* @param request an AlpineRequest object
*/
FindingsSearchQueryManager(final PersistenceManager pm, final AlpineRequest request) {
super(pm, request);
}
/**
* Returns a List of all Finding objects filtered by ACL and other optional filters.
* @param filters determines the filters to apply on the list of Finding objects
* @param showSuppressed determines if suppressed vulnerabilities should be included or not
* @param showInactive determines if inactive projects should be included or not
* @return a List of Finding objects
*/
public PaginatedResult getAllFindings(final Map<String, String> filters, final boolean showSuppressed, final boolean showInactive) {
StringBuilder queryFilter = new StringBuilder();
Map<String, Object> params = new HashMap<>();
if (!showInactive) {
queryFilter.append(" WHERE (\"PROJECT\".\"ACTIVE\" = :active OR \"PROJECT\".\"ACTIVE\" IS NULL)");
params.put("active", true);
}
if (!showSuppressed) {
if (queryFilter.isEmpty()) {
queryFilter.append(" WHERE ");
} else {
queryFilter.append(" AND ");
}
queryFilter.append("(\"ANALYSIS\".\"SUPPRESSED\" = :showSuppressed OR \"ANALYSIS\".\"SUPPRESSED\" IS NULL)");
params.put("showSuppressed", false);
}
processFilters(filters, queryFilter, params, false);
final var orderByFragments = new ArrayList<String>();
if (this.orderBy != null) {
orderByFragments.add("%s %s".formatted(
sortingAttributes.get(this.orderBy),
(this.orderDirection == OrderDirection.DESCENDING ? "DESC" : "ASC")));
}
orderByFragments.add("\"FINDINGATTRIBUTION\".\"ID\""); // Tie-breaker to ensure stable ordering.
final var orderByClause = " ORDER BY " + String.join(", ", orderByFragments);
final Query<Object[]> query = pm.newQuery(Query.SQL, Finding.QUERY_ALL_FINDINGS + queryFilter + orderByClause);
PaginatedResult result = new PaginatedResult();
query.setNamedParameters(params);
final List<Object[]> totalList = query.executeList();
result.setTotal(totalList.size());
final List<Object[]> list = totalList.subList(this.pagination.getOffset(), Math.min(this.pagination.getOffset() + this.pagination.getLimit(), totalList.size()));
final List<Finding> findings = new ArrayList<>();
for (final Object[] o : list) {
final Finding finding = new Finding(UUID.fromString((String) o[37]), o);
final Component component = getObjectByUuid(Component.class, (String) finding.getComponent().get("uuid"));
final Vulnerability vulnerability = getObjectByUuid(Vulnerability.class, (String) finding.getVulnerability().get("uuid"));
final Analysis analysis = getAnalysis(component, vulnerability);
final List<VulnerabilityAlias> aliases = detach(getVulnerabilityAliases(vulnerability));
aliases.forEach(alias -> alias.setUuid(null));
finding.getVulnerability().put("aliases", aliases);
// These are CLOB fields. Handle these here so that database-specific deserialization doesn't need to be performed (in Finding)
finding.getVulnerability().put("description", vulnerability.getDescription());
finding.getVulnerability().put("recommendation", vulnerability.getRecommendation());
finding.getVulnerability().put("references", vulnerability.getReferences());
finding.getVulnerability().put("cvssV2Vector", vulnerability.getCvssV2Vector());
finding.getVulnerability().put("cvssV3Vector", vulnerability.getCvssV3Vector());
finding.getVulnerability().put("cvssV4Vector", vulnerability.getCvssV4Vector());
finding.getVulnerability().put("owaspRRVector", vulnerability.getOwaspRRVector());
final PackageURL purl = component.getPurl();
if (purl != null) {
final RepositoryType type = RepositoryType.resolve(purl);
if (RepositoryType.UNSUPPORTED != type) {
final RepositoryMetaComponent repoMetaComponent = getRepositoryMetaComponent(type, purl.getNamespace(), purl.getName());
if (repoMetaComponent != null) {
finding.getComponent().put("latestVersion", repoMetaComponent.getLatestVersion());
}
}
}
findings.add(finding);
}
result.setObjects(findings);
return result;
}
/**
* Returns a List of all Finding objects filtered by ACL and other optional filters. The resulting list is grouped by vulnerability.
* @param filters determines the filters to apply on the list of Finding objects
* @param showInactive determines if inactive projects should be included or not
* @return a List of Finding objects
*/
public PaginatedResult getAllFindingsGroupedByVulnerability(final Map<String, String> filters, final boolean showInactive) {
StringBuilder queryFilter = new StringBuilder();
Map<String, Object> params = new HashMap<>();
if (!showInactive) {
queryFilter.append(" WHERE (\"PROJECT\".\"ACTIVE\" = :active OR \"PROJECT\".\"ACTIVE\" IS NULL)");
params.put("active", true);
}
processFilters(filters, queryFilter, params, true);
final var orderByFragments = new ArrayList<String>();
if (this.orderBy != null) {
orderByFragments.add("%s %s".formatted(
sortingAttributes.get(this.orderBy),
(this.orderDirection == OrderDirection.DESCENDING ? "DESC" : "ASC")));
}
if (!"vulnerability.vulnId".equals(this.orderBy)) {
orderByFragments.add(sortingAttributes.get("vulnerability.vulnId")); // Tie-breaker to ensure stable ordering.
}
final var orderByClause = " ORDER BY " + String.join(", ", orderByFragments);
final Query<Object[]> query = pm.newQuery(Query.SQL, GroupedFinding.QUERY + queryFilter + orderByClause);
PaginatedResult result = new PaginatedResult();
query.setNamedParameters(params);
final List<Object[]> totalList = query.executeList();
result.setTotal(totalList.size());
final List<Object[]> list = totalList.subList(this.pagination.getOffset(), Math.min(this.pagination.getOffset() + this.pagination.getLimit(), totalList.size()));
final List<GroupedFinding> findings = new ArrayList<>();
for (Object[] o : list) {
final GroupedFinding finding = new GroupedFinding(o);
findings.add(finding);
}
result.setObjects(findings);
return result;
}
private void processFilters(Map<String, String> filters, StringBuilder queryFilter, Map<String, Object> params, boolean isGroupedByVulnerabilities) {
for (String filter : filters.keySet()) {
switch (filter) {
case "severity" ->
processArrayFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"SEVERITY\"");
case "analysisStatus" ->
processArrayFilter(queryFilter, params, filter, filters.get(filter), "\"ANALYSIS\".\"STATE\"");
case "vendorResponse" ->
processArrayFilter(queryFilter, params, filter, filters.get(filter), "\"ANALYSIS\".\"RESPONSE\"");
case "publishDateFrom" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"PUBLISHED\"", true, true, false);
case "publishDateTo" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"PUBLISHED\"", false, true, false);
case "attributedOnDateFrom" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"FINDINGATTRIBUTION\".\"ATTRIBUTED_ON\"", true, true, false);
case "attributedOnDateTo" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"FINDINGATTRIBUTION\".\"ATTRIBUTED_ON\"", false, true, false);
case "textSearchField" ->
processInputFilter(queryFilter, params, filter, filters.get(filter), filters.get("textSearchInput"));
case "cvssv2From" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV2BASESCORE\"", true, false, false);
case "cvssv2To" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV2BASESCORE\"", false, false, false);
case "cvssv3From" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV3BASESCORE\"", true, false, false);
case "cvssv3To" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV3BASESCORE\"", false, false, false);
case "cvssv4From" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV4SCORE\"", true, false, false);
case "cvssv4To" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"CVSSV4SCORE\"", false, false, false);
case "epssFrom" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"EPSSSCORE\"", true, false, false);
case "epssTo" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"EPSSSCORE\"", false, false, false);
case "epssPercentileFrom" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"EPSSPERCENTILE\"", true, false, false);
case "epssPercentileTo" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "\"VULNERABILITY\".\"EPSSPERCENTILE\"", false, false, false);
}
}
preprocessACLs(queryFilter, params);
if (isGroupedByVulnerabilities) {
queryFilter.append("""
GROUP BY "VULNERABILITY"."ID"
, "VULNERABILITY"."SOURCE"
, "VULNERABILITY"."VULNID"
, "VULNERABILITY"."TITLE"
, "VULNERABILITY"."SEVERITY"
, "VULNERABILITY"."CVSSV2BASESCORE"
, "VULNERABILITY"."CVSSV2VECTOR"
, "VULNERABILITY"."CVSSV3BASESCORE"
, "VULNERABILITY"."CVSSV3VECTOR"
, "VULNERABILITY"."CVSSV4SCORE"
, "VULNERABILITY"."CVSSV4VECTOR"
, "VULNERABILITY"."EPSSSCORE"
, "VULNERABILITY"."EPSSPERCENTILE"
, "VULNERABILITY"."OWASPRRLIKELIHOODSCORE"
, "VULNERABILITY"."OWASPRRTECHNICALIMPACTSCORE"
, "VULNERABILITY"."OWASPRRBUSINESSIMPACTSCORE"
, "VULNERABILITY"."OWASPRRVECTOR"
, "FINDINGATTRIBUTION"."ANALYZERIDENTITY"
, "VULNERABILITY"."PUBLISHED"
, "VULNERABILITY"."CWES"
""");
StringBuilder aggregateFilter = new StringBuilder();
processAggregateFilters(filters, aggregateFilter, params);
queryFilter.append(aggregateFilter);
}
}
private void processAggregateFilters(Map<String, String> filters, StringBuilder queryFilter, Map<String, Object> params) {
for (String filter : filters.keySet()) {
switch (filter) {
case "occurrencesFrom" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "COUNT(DISTINCT \"PROJECT\".\"ID\")", true, false, true);
case "occurrencesTo" ->
processRangeFilter(queryFilter, params, filter, filters.get(filter), "COUNT(DISTINCT \"PROJECT\".\"ID\")", false, false, true);
}
}
}
private void processArrayFilter(StringBuilder queryFilter, Map<String, Object> params, String paramName, String filter, String column) {
if (filter != null && !filter.isEmpty()) {
if (queryFilter.isEmpty()) {
queryFilter.append(" WHERE (");
} else {
queryFilter.append(" AND (");
}
String[] filters = filter.split(",");
for (int i = 0, length = filters.length; i < length; i++) {
queryFilter.append(column).append(" = :").append(paramName).append(i);
params.put(paramName + i, filters[i].toUpperCase());
if (filters[i].equals("NOT_SET") && (paramName.equals("analysisStatus") || paramName.equals("vendorResponse"))) {
queryFilter.append(" OR ").append(column).append(" IS NULL");
}
if (i < length - 1) {
queryFilter.append(" OR ");
}
}
queryFilter.append(")");
}
}
private void processRangeFilter(StringBuilder queryFilter, Map<String, Object> params, String paramName, String filter, String column, boolean fromValue, boolean isDate, boolean isAggregateFilter) {
if (filter != null && !filter.isEmpty()) {
if (queryFilter.isEmpty()) {
queryFilter.append(isAggregateFilter ? " HAVING (" : " WHERE (");
} else {
queryFilter.append(" AND (");
}
String value = filter;
if (DbUtil.isPostgreSQL()) {
queryFilter.append(column).append(fromValue ? " >= " : " <= ");
if (isDate) {
queryFilter.append("TO_TIMESTAMP(:").append(paramName).append(", 'YYYY-MM-DD HH24:MI:SS')");
value += (fromValue ? " 00:00:00" : " 23:59:59");
} else {
queryFilter.append("CAST(:").append(paramName).append(" AS NUMERIC)");
}
} else {
queryFilter.append(column).append(fromValue ? " >= :" : " <= :").append(paramName);
if (isDate) {
value += (fromValue ? " 00:00:00" : " 23:59:59");
}
}
params.put(paramName, value);
queryFilter.append(")");
}
}
private void processAggregatedDateRangeFilter(StringBuilder queryFilter, Map<String, Object> params, String paramName, String filter, String column, boolean fromValue, boolean isMin) {
if (filter != null && !filter.isEmpty()) {
if (queryFilter.isEmpty()) {
queryFilter.append(" HAVING (");
} else {
queryFilter.append(isMin ? " AND (" : " OR ");
}
if (DbUtil.isPostgreSQL()) {
queryFilter.append(column).append(fromValue ? " >= " : " <= ");
queryFilter.append("TO_TIMESTAMP(:").append(paramName).append(", 'YYYY-MM-DD HH24:MI:SS')");
} else {
queryFilter.append(column).append(fromValue ? " >= :" : " <= :").append(paramName);
}
params.put(paramName, filter + (fromValue ? " 00:00:00" : " 23:59:59"));
if (!isMin) {
queryFilter.append(")");
}
}
}
private void processInputFilter(StringBuilder queryFilter, Map<String, Object> params, String paramName, String filter, String input) {
if (filter != null && !filter.isEmpty() && input != null && !input.isEmpty()) {
if (queryFilter.isEmpty()) {
queryFilter.append(" WHERE (");
} else {
queryFilter.append(" AND (");
}
String[] filters = filter.split(",");
for (int i = 0, length = filters.length; i < length; i++) {
switch (filters[i].toUpperCase()) {
case "VULNERABILITY_ID" -> queryFilter.append("\"VULNERABILITY\".\"VULNID\"");
case "VULNERABILITY_TITLE" -> queryFilter.append("\"VULNERABILITY\".\"TITLE\"");
case "COMPONENT_NAME" -> queryFilter.append("\"COMPONENT\".\"NAME\"");
case "COMPONENT_VERSION" -> queryFilter.append("\"COMPONENT\".\"VERSION\"");
case "PROJECT_NAME" ->
queryFilter.append("concat(\"PROJECT\".\"NAME\", ' ', \"PROJECT\".\"VERSION\")");
}
queryFilter.append(" LIKE :").append(paramName);
if (i < length - 1) {
queryFilter.append(" OR ");
}
}
if (filters.length > 0) {
params.put(paramName, "%" + input + "%");
}
queryFilter.append(")");
}
}
private void preprocessACLs(StringBuilder queryFilter, final Map<String, Object> params) {
if (queryFilter.isEmpty()) {
queryFilter.append(" WHERE ");
} else {
queryFilter.append(" AND ");
}
final Map.Entry<String, Map<String, Object>> projectAclConditionAndParams = getProjectAclSqlCondition();
queryFilter.append(projectAclConditionAndParams.getKey()).append(" ");
params.putAll(projectAclConditionAndParams.getValue());
}
}