-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
CveDB.java
1809 lines (1718 loc) · 79.9 KB
/
CveDB.java
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2018 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.nvdcve;
//CSOFF: AvoidStarImport
import com.google.common.io.Resources;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.github.jeremylong.openvulnerability.client.nvd.Config;
import io.github.jeremylong.openvulnerability.client.nvd.CpeMatch;
import org.apache.commons.collections.map.ReferenceMap;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.JDBCType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;
import org.anarres.jdiagnostics.DefaultQuery;
import static org.apache.commons.collections.map.AbstractReferenceMap.HARD;
import static org.apache.commons.collections.map.AbstractReferenceMap.SOFT;
import org.owasp.dependencycheck.analyzer.exception.LambdaExceptionWrapper;
import org.owasp.dependencycheck.analyzer.exception.UnexpectedAnalysisException;
import io.github.jeremylong.openvulnerability.client.nvd.DefCveItem;
import static org.owasp.dependencycheck.data.nvdcve.CveDB.PreparedStatementCveDb.*;
import org.owasp.dependencycheck.data.update.cpe.CpeEcosystemCache;
import org.owasp.dependencycheck.data.update.cpe.CpePlus;
import io.github.jeremylong.openvulnerability.client.nvd.CvssV2;
import io.github.jeremylong.openvulnerability.client.nvd.CvssV2Data;
import io.github.jeremylong.openvulnerability.client.nvd.CvssV3;
import io.github.jeremylong.openvulnerability.client.nvd.CvssV3Data;
import io.github.jeremylong.openvulnerability.client.nvd.LangString;
import io.github.jeremylong.openvulnerability.client.nvd.Node;
import io.github.jeremylong.openvulnerability.client.nvd.Reference;
import io.github.jeremylong.openvulnerability.client.nvd.Weakness;
import org.owasp.dependencycheck.dependency.VulnerableSoftwareBuilder;
import us.springett.parsers.cpe.Cpe;
import us.springett.parsers.cpe.CpeBuilder;
import us.springett.parsers.cpe.CpeParser;
import us.springett.parsers.cpe.exceptions.CpeParsingException;
import us.springett.parsers.cpe.exceptions.CpeValidationException;
/**
* The database holding information about the NVD CVE data. This class is safe
* to be accessed from multiple threads in parallel, however internally only one
* connection will be used.
*
* @author Jeremy Long
*/
@ThreadSafe
public final class CveDB implements AutoCloseable {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CveDB.class);
/**
* Resource location for SQL file containing updates to the ecosystem cache.
*/
public static final String DB_ECOSYSTEM_CACHE = "data/dbEcosystemCacheUpdates.sql";
/**
* The database connection manager.
*/
private final DatabaseManager databaseManager;
/**
* The bundle of statements used when accessing the database.
*/
private ResourceBundle statementBundle;
/**
* Database properties object containing the 'properties' from the database
* table.
*/
private DatabaseProperties databaseProperties;
/**
* The filter for 2.3 CPEs in the CVEs - we don't import unless we get a
* match.
*/
private final String cpeStartsWithFilter;
/**
* Cache for CVE lookup; used to speed up the vulnerability search process.
*/
@SuppressWarnings("unchecked")
private final Map<String, List<Vulnerability>> vulnerabilitiesForCpeCache = Collections.synchronizedMap(new ReferenceMap(HARD, SOFT));
/**
* The configured settings
*/
private final Settings settings;
/**
* Utility to extract information from
* {@linkplain org.owasp.dependencycheck.data.nvd.json.DefCveItem}.
*/
private final CveItemOperator cveItemConverter;
/**
* Flag indicating if the database is Oracle.
*/
private boolean isOracle = false;
/**
* Flag indicating if the database is H2.
*/
private boolean isH2 = false;
/**
* Updates the EcoSystem Cache.
*
* @return The number of records updated by the DB_ECOSYSTEM_CACHE update
* script.
*/
public int updateEcosystemCache() {
LOGGER.debug("Updating the ecosystem cache");
int updateCount = 0;
try {
final URL url = Resources.getResource(DB_ECOSYSTEM_CACHE);
final List<String> sql = Resources.readLines(url, StandardCharsets.UTF_8);
try (Connection conn = databaseManager.getConnection(); Statement statement = conn.createStatement()) {
for (String single : sql) {
updateCount += statement.executeUpdate(single);
}
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to update the ecosystem cache", ex);
}
} catch (IOException ex) {
throw new DatabaseException("Unable to update the ecosystem cache", ex);
} catch (LinkageError ex) {
LOGGER.debug(new DefaultQuery(ex).call().toString());
}
return updateCount;
}
/**
* The enumeration value names must match the keys of the statements in the
* statement bundles "dbStatements*.properties".
*/
enum PreparedStatementCveDb {
/**
* Key for SQL Statement.
*/
CLEANUP_ORPHANS,
/**
* Key for update ecosystem.
*/
UPDATE_ECOSYSTEM,
/**
* Key for update ecosystem.
*/
UPDATE_ECOSYSTEM2,
/**
* Key for SQL Statement.
*/
COUNT_CPE,
/**
* Key for SQL Statement.
*/
DELETE_VULNERABILITY,
/**
* Key for SQL Statement.
*/
INSERT_PROPERTY,
/**
* Key for SQL Statement.
*/
INSERT_CWE,
/**
* Key for SQL Statement.
*/
INSERT_REFERENCE,
/**
* Key for SQL Statement.
*/
INSERT_SOFTWARE,
/**
* Key for SQL Statement.
*/
MERGE_PROPERTY,
/**
* Key for SQL Statement.
*/
SELECT_CPE_ENTRIES,
/**
* Key for SQL Statement.
*/
SELECT_CVE_FROM_SOFTWARE,
/**
* Key for SQL Statement.
*/
SELECT_PROPERTIES,
/**
* Key for SQL Statement.
*/
SELECT_VULNERABILITY_CWE,
/**
* Key for SQL Statement.
*/
SELECT_REFERENCES,
/**
* Key for SQL Statement.
*/
SELECT_SOFTWARE,
/**
* Key for SQL Statement.
*/
SELECT_VENDOR_PRODUCT_LIST,
/**
* Key for SQL Statement.
*/
SELECT_VENDOR_PRODUCT_LIST_FOR_NODE,
/**
* Key for SQL Statement.
*/
SELECT_VULNERABILITY,
/**
* Key for SQL Statement.
*/
UPDATE_PROPERTY,
/**
* Key for SQL Statement.
*/
UPDATE_VULNERABILITY,
/**
* Key for SQL Statement.
*/
SELECT_CPE_ECOSYSTEM,
/**
* Key for SQL Statement.
*/
MERGE_CPE_ECOSYSTEM,
/**
* Key for SQL Statement.
*/
DELETE_UNUSED_DICT_CPE,
/**
* Key for SQL Statement.
*/
ADD_DICT_CPE,
/**
* Key for SQL Statement.
*/
SELECT_KNOWN_EXPLOITED_VULNERABILITIES,
/**
* Key for SQL Statement.
*/
MERGE_KNOWN_EXPLOITED
}
/**
* Creates a new CveDB object and opens the database connection. Note, the
* connection must be closed by the caller by calling the close method.
*
* @param settings the configured settings
* @throws DatabaseException thrown if there is an exception opening the
* database.
*/
public CveDB(Settings settings) throws DatabaseException {
this.settings = settings;
this.cpeStartsWithFilter = settings.getString(Settings.KEYS.CVE_CPE_STARTS_WITH_FILTER, "cpe:2.3:a:");
this.cveItemConverter = new CveItemOperator(cpeStartsWithFilter);
databaseManager = new DatabaseManager(settings);
statementBundle = databaseManager.getSqlStatements();
isOracle = databaseManager.isOracle();
isH2 = databaseManager.isH2Connection();
}
/**
* Opens the database connection pool.
*/
public void open() {
databaseManager.open();
databaseProperties = new DatabaseProperties(this);
}
/**
* Closes the database connection. Close should be called on this object
* when it is done being used.
*/
@Override
public void close() {
if (isOpen()) {
LOGGER.debug("Closing database");
clearCache();
LOGGER.debug("Cache cleared");
try {
databaseManager.close();
LOGGER.debug("Connection closed");
} catch (Throwable ex) {
LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
}
releaseResources();
LOGGER.debug("Resources released");
databaseManager.cleanup();
}
}
/**
* Releases the resources used by CveDB.
*/
private void releaseResources() {
statementBundle = null;
databaseProperties = null;
}
/**
* Returns whether the database connection is open or closed.
*
* @return whether the database connection is open or closed
*/
public boolean isOpen() {
return databaseManager.isOpen();
}
/**
* Creates a prepared statement from the given key. The SQL is stored in a
* properties file and the key is used to lookup the specific query.
*
* @param connection the database connection
* @param key the key to select the prepared statement from the properties
* file
* @param parameter the first parameter to pass into the statement
* @return the prepared statement
* @throws DatabaseException throw if there is an error generating the
* prepared statement
*/
private PreparedStatement getPreparedStatement(Connection connection, PreparedStatementCveDb key, String parameter)
throws DatabaseException, SQLException {
final PreparedStatement preparedStatement = getPreparedStatement(connection, key);
preparedStatement.setString(1, parameter);
return preparedStatement;
}
/**
* Creates a prepared statement from the given key. The SQL is stored in a
* properties file and the key is used to lookup the specific query.
*
* @param connection the database connection
* @param key the key to select the prepared statement from the properties
* file
* @param parameter the first parameter to pass into the statement
* @return the prepared statement
* @throws DatabaseException throw if there is an error generating the
* prepared statement
*/
private PreparedStatement getPreparedStatement(Connection connection, PreparedStatementCveDb key, int parameter)
throws DatabaseException, SQLException {
final PreparedStatement preparedStatement = getPreparedStatement(connection, key);
preparedStatement.setInt(1, parameter);
return preparedStatement;
}
/**
* Creates a prepared statement from the given key. The SQL is stored in a
* properties file and the key is used to lookup the specific query.
*
* @param connection the database connection
* @param key the key to select the prepared statement from the properties
* file
* @return the prepared statement
* @throws DatabaseException throw if there is an error generating the
* prepared statement
*/
private PreparedStatement getPreparedStatement(Connection connection, PreparedStatementCveDb key) throws DatabaseException {
PreparedStatement preparedStatement = null;
try {
final String statementString = statementBundle.getString(key.name());
if (isOracle && key == UPDATE_VULNERABILITY) {
preparedStatement = connection.prepareCall(statementString);
// } else if (key == INSERT_CPE) {
// final String[] returnedColumns = {"id"};
// preparedStatement = connection.prepareStatement(statementString, returnedColumns);
} else {
preparedStatement = connection.prepareStatement(statementString);
}
if (isOracle) {
// Oracle has a default fetch-size of 10; MariaDB, MySQL, SQLServer and PostgreSQL by default cache the full
// resultset at the client https://venkatsadasivam.com/2009/02/01/jdbc-performance-tuning-with-optimal-fetch-size/
preparedStatement.setFetchSize(10_000);
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
} catch (MissingResourceException ex) {
if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
throw new DatabaseException(ex);
}
}
return preparedStatement;
}
/**
* Cleans up the object and ensures that "close" has been called.
*
* @throws Throwable thrown if there is a problem
*/
@Override
@SuppressWarnings("FinalizeDeclaration")
protected void finalize() throws Throwable {
LOGGER.debug("Entering finalize");
close();
super.finalize();
}
/**
* Get the value of databaseProperties.
*
* @return the value of databaseProperties
*/
public DatabaseProperties getDatabaseProperties() {
return databaseProperties;
}
/**
* Used within the unit tests to reload the database properties.
*
* @return the database properties
*/
DatabaseProperties reloadProperties() {
databaseProperties = new DatabaseProperties(this);
return databaseProperties;
}
/**
* Searches the CPE entries in the database and retrieves all entries for a
* given vendor and product combination. The returned list will include all
* versions of the product that are registered in the NVD CVE data.
*
* @param vendor the identified vendor name of the dependency being analyzed
* @param product the identified name of the product of the dependency being
* analyzed
* @return a set of vulnerable software
*/
public Set<CpePlus> getCPEs(String vendor, String product) {
final Set<CpePlus> cpe = new HashSet<>();
try (Connection conn = databaseManager.getConnection(); PreparedStatement ps = getPreparedStatement(conn, SELECT_CPE_ENTRIES)) {
//part, vendor, product, version, update_version, edition,
//lang, sw_edition, target_sw, target_hw, other, ecosystem
ps.setString(1, vendor);
ps.setString(2, product);
try (ResultSet rs = ps.executeQuery()) {
final CpeBuilder builder = new CpeBuilder();
while (rs.next()) {
final Cpe entry = builder
.part(rs.getString(1))
.vendor(rs.getString(2))
.product(rs.getString(3))
.version(rs.getString(4))
.update(rs.getString(5))
.edition(rs.getString(6))
.language(rs.getString(7))
.swEdition(rs.getString(8))
.targetSw(rs.getString(9))
.targetHw(rs.getString(10))
.other(rs.getString(11)).build();
final CpePlus plus = new CpePlus(entry, rs.getString(12));
cpe.add(plus);
}
}
} catch (SQLException | CpeParsingException | CpeValidationException ex) {
LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
LOGGER.debug("", ex);
}
return cpe;
}
/**
* Returns the entire list of vendor/product combinations.
*
* @return the entire list of vendor/product combinations
* @throws DatabaseException thrown when there is an error retrieving the
* data from the DB
*/
public Set<Pair<String, String>> getVendorProductList() throws DatabaseException {
final Set<Pair<String, String>> data = new HashSet<>();
try (Connection conn = databaseManager.getConnection();
PreparedStatement ps = getPreparedStatement(conn, SELECT_VENDOR_PRODUCT_LIST);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
data.add(new Pair<>(rs.getString(1), rs.getString(2)));
}
} catch (SQLException ex) {
final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
throw new DatabaseException(msg, ex);
}
return data;
}
/**
* Returns the entire list of vendor/product combinations filtered for just
* Node JS related products.
*
* @return the list of vendor/product combinations that are known to be
* related to Node JS
* @throws DatabaseException thrown when there is an error retrieving the
* data from the DB
*/
public Set<Pair<String, String>> getVendorProductListForNode() throws DatabaseException {
final Set<Pair<String, String>> data = new HashSet<>();
try (Connection conn = databaseManager.getConnection();
PreparedStatement ps = getPreparedStatement(conn, SELECT_VENDOR_PRODUCT_LIST_FOR_NODE);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
data.add(new Pair<>(rs.getString(1), rs.getString(2)));
}
} catch (SQLException ex) {
final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
throw new DatabaseException(msg, ex);
}
return data;
}
/**
* Returns a set of properties.
*
* @return the properties from the database
*/
public Properties getProperties() {
final Properties prop = new Properties();
try (Connection conn = databaseManager.getConnection();
PreparedStatement ps = getPreparedStatement(conn, SELECT_PROPERTIES);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
prop.setProperty(rs.getString(1), rs.getString(2));
}
} catch (SQLException ex) {
LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
LOGGER.debug("", ex);
}
return prop;
}
/**
* Saves a property to the database.
*
* @param key the property key
* @param value the property value
*/
public void saveProperty(String key, String value) {
clearCache();
try (Connection conn = databaseManager.getConnection(); PreparedStatement mergeProperty = getPreparedStatement(conn, MERGE_PROPERTY)) {
if (mergeProperty != null) {
mergeProperty.setString(1, key);
mergeProperty.setString(2, value);
mergeProperty.execute();
} else {
// No Merge statement, so doing an Update/Insert...
try (PreparedStatement updateProperty = getPreparedStatement(conn, UPDATE_PROPERTY)) {
updateProperty.setString(1, value);
updateProperty.setString(2, key);
if (updateProperty.executeUpdate() == 0) {
try (PreparedStatement insertProperty = getPreparedStatement(conn, INSERT_PROPERTY)) {
insertProperty.setString(1, key);
insertProperty.setString(2, value);
insertProperty.executeUpdate();
}
}
}
}
} catch (SQLException ex) {
LOGGER.warn("Unable to save property '{}' with a value of '{}' to the database", key, value);
LOGGER.debug("", ex);
}
}
/**
* Clears cache. Should be called whenever something is modified. While this
* is not the optimal cache eviction strategy, this is good enough for
* typical usage (update DB and then only read) and it is easier to maintain
* the code.
* <p>
* It should be also called when DB is closed.
* </p>
*/
private void clearCache() {
vulnerabilitiesForCpeCache.clear();
}
/**
* Retrieves the vulnerabilities associated with the specified CPE.
*
* @param cpe the CPE to retrieve vulnerabilities for
* @return a list of Vulnerabilities
* @throws DatabaseException thrown if there is an exception retrieving data
*/
public List<Vulnerability> getVulnerabilities(Cpe cpe) throws DatabaseException {
final List<Vulnerability> cachedVulnerabilities = vulnerabilitiesForCpeCache.get(cpe.toCpe23FS());
if (cachedVulnerabilities != null) {
LOGGER.debug("Cache hit for {}", cpe.toCpe23FS());
return cachedVulnerabilities;
} else {
LOGGER.debug("Cache miss for {}", cpe.toCpe23FS());
}
final List<Vulnerability> vulnerabilities = new ArrayList<>();
try (Connection conn = databaseManager.getConnection(); PreparedStatement ps = getPreparedStatement(conn, SELECT_CVE_FROM_SOFTWARE)) {
ps.setString(1, cpe.getVendor());
ps.setString(2, cpe.getProduct());
try (ResultSet rs = ps.executeQuery()) {
String currentCVE = "";
final Set<VulnerableSoftware> vulnSoftware = new HashSet<>();
final VulnerableSoftwareBuilder vulnerableSoftwareBuilder = new VulnerableSoftwareBuilder();
while (rs.next()) {
final String cveId = rs.getString(1);
if (currentCVE.isEmpty()) {
//first loop we don't have the cveId
currentCVE = cveId;
}
if (!vulnSoftware.isEmpty() && !currentCVE.equals(cveId)) { //check for match and add
final VulnerableSoftware matchedCPE = getMatchingSoftware(cpe, vulnSoftware);
if (matchedCPE != null) {
final Vulnerability v = getVulnerability(currentCVE, conn);
if (v != null) {
v.setMatchedVulnerableSoftware(matchedCPE);
v.setSource(Vulnerability.Source.NVD);
vulnerabilities.add(v);
}
}
vulnSoftware.clear();
currentCVE = cveId;
}
// 1 cve, 2 part, 3 vendor, 4 product, 5 version, 6 update_version, 7 edition,
// 8 lang, 9 sw_edition, 10 target_sw, 11 target_hw, 12 other, 13 versionEndExcluding,
//14 versionEndIncluding, 15 versionStartExcluding, 16 versionStartIncluding, 17 vulnerable
final VulnerableSoftware vs;
try {
vs = vulnerableSoftwareBuilder.part(rs.getString(2)).vendor(rs.getString(3))
.product(rs.getString(4)).version(rs.getString(5)).update(rs.getString(6))
.edition(rs.getString(7)).language(rs.getString(8)).swEdition(rs.getString(9))
.targetSw(rs.getString(10)).targetHw(rs.getString(11)).other(rs.getString(12))
.versionEndExcluding(rs.getString(13)).versionEndIncluding(rs.getString(14))
.versionStartExcluding(rs.getString(15)).versionStartIncluding(rs.getString(16))
.vulnerable(rs.getBoolean(17)).build();
} catch (CpeParsingException | CpeValidationException ex) {
throw new DatabaseException("Database contains an invalid Vulnerable Software Entry", ex);
}
vulnSoftware.add(vs);
}
//remember to process the last set of CVE/CPE entries
final VulnerableSoftware matchedCPE = getMatchingSoftware(cpe, vulnSoftware);
if (matchedCPE != null) {
final Vulnerability v = getVulnerability(currentCVE, conn);
if (v != null) {
v.setMatchedVulnerableSoftware(matchedCPE);
v.setSource(Vulnerability.Source.NVD);
vulnerabilities.add(v);
}
}
}
} catch (SQLException ex) {
throw new DatabaseException("Exception retrieving vulnerability for " + cpe.toCpe23FS(), ex);
}
vulnerabilitiesForCpeCache.put(cpe.toCpe23FS(), vulnerabilities);
return vulnerabilities;
}
/**
* Gets a vulnerability for the provided CVE.
*
* @param cve the CVE to lookup
* @return a vulnerability object
* @throws DatabaseException if an exception occurs
*/
public Vulnerability getVulnerability(String cve) throws DatabaseException {
try (Connection conn = databaseManager.getConnection()) {
return getVulnerability(cve, conn);
} catch (SQLException ex) {
throw new DatabaseException("Error retrieving " + cve, ex);
}
}
/**
* Gets a vulnerability for the provided CVE.
*
* @param cve the CVE to lookup
* @param conn already active database connection
* @return a vulnerability object
* @throws DatabaseException if an exception occurs
*/
public Vulnerability getVulnerability(String cve, Connection conn) throws DatabaseException {
final int cveId;
final VulnerableSoftwareBuilder vulnerableSoftwareBuilder = new VulnerableSoftwareBuilder();
Vulnerability vuln = null;
try {
try (PreparedStatement psV = getPreparedStatement(conn, SELECT_VULNERABILITY, cve); ResultSet rsV = psV.executeQuery()) {
if (rsV.next()) {
//1.id, 2.description,
cveId = rsV.getInt(1);
vuln = new Vulnerability();
vuln.setSource(Vulnerability.Source.NVD);
vuln.setName(cve);
vuln.setDescription(rsV.getString(2));
//3.v2Severity, 4.v2ExploitabilityScore, 5.v2ImpactScore, 6.v2AcInsufInfo, 7.v2ObtainAllPrivilege,
//8.v2ObtainUserPrivilege, 9.v2ObtainOtherPrivilege, 10.v2UserInteractionRequired, 11.v2Score,
//12.v2AccessVector, 13.v2AccessComplexity, 14.v2Authentication, 15.v2ConfidentialityImpact,
//16.v2IntegrityImpact, 17.v2AvailabilityImpact, 18.v2Version,
if (rsV.getObject(11) != null) {
final CvssV2Data.AccessVectorType accessVector = CvssV2Data.AccessVectorType.fromValue(rsV.getString(12));
final CvssV2Data.AccessComplexityType accessComplexity = CvssV2Data.AccessComplexityType.fromValue(rsV.getString(13));
final CvssV2Data.AuthenticationType authentication = CvssV2Data.AuthenticationType.fromValue(rsV.getString(14));
final CvssV2Data.CiaType confidentialityImpact = CvssV2Data.CiaType.fromValue(rsV.getString(15));
final CvssV2Data.CiaType integrityImpact = CvssV2Data.CiaType.fromValue(rsV.getString(16));
final CvssV2Data.CiaType availabilityImpact = CvssV2Data.CiaType.fromValue(rsV.getString(17));
final String vector = String.format("/AV:%s/AC:%s/Au:%s/C:%s/I:%s/A:%s",
accessVector == null ? "" : accessVector.value().substring(0, 1),
accessComplexity == null ? "" : accessComplexity.value().substring(0, 1),
authentication == null ? "" : authentication.value().substring(0, 1),
confidentialityImpact == null ? "" : confidentialityImpact.value().substring(0, 1),
integrityImpact == null ? "" : integrityImpact.value().substring(0, 1),
availabilityImpact == null ? "" : availabilityImpact.value().substring(0, 1));
//some older test data may not correctly have the version set.
String cveVersion = "2.0";
if (rsV.getString(18) != null) {
cveVersion = rsV.getString(18);
}
final CvssV2Data cvssData = new CvssV2Data(cveVersion, vector, accessVector,
accessComplexity, authentication, confidentialityImpact,
integrityImpact, availabilityImpact, rsV.getDouble(11), rsV.getString(3),
null, null, null, null, null, null, null, null, null, null);
final CvssV2 cvss = new CvssV2(null, CvssV2.Type.PRIMARY, cvssData, rsV.getString(3),
rsV.getDouble(4), rsV.getDouble(5), rsV.getBoolean(6), rsV.getBoolean(7),
rsV.getBoolean(8), rsV.getBoolean(9), rsV.getBoolean(10));
vuln.setCvssV2(cvss);
}
//19.v3ExploitabilityScore, 20.v3ImpactScore, 21.v3AttackVector, 22.v3AttackComplexity, 23.v3PrivilegesRequired,
//24.v3UserInteraction, 25.v3Scope, 26.v3ConfidentialityImpact, 27.v3IntegrityImpact, 28.v3AvailabilityImpact,
//29.v3BaseScore, 30.v3BaseSeverity, 31.v3Version
if (rsV.getObject(21) != null) {
//some older test data may not correctly have the version set.
String cveVersion = "3.1";
if (rsV.getString(31) != null) {
cveVersion = rsV.getString(31);
}
final CvssV3Data.Version version = CvssV3Data.Version.fromValue(cveVersion);
final CvssV3Data.AttackVectorType attackVector = CvssV3Data.AttackVectorType.fromValue(rsV.getString(21));
final CvssV3Data.AttackComplexityType attackComplexity = CvssV3Data.AttackComplexityType.fromValue(rsV.getString(22));
final CvssV3Data.PrivilegesRequiredType privilegesRequired = CvssV3Data.PrivilegesRequiredType.fromValue(rsV.getString(23));
final CvssV3Data.UserInteractionType userInteraction = CvssV3Data.UserInteractionType.fromValue(rsV.getString(24));
final CvssV3Data.ScopeType scope = CvssV3Data.ScopeType.fromValue(rsV.getString(25));
final CvssV3Data.CiaType confidentialityImpact = CvssV3Data.CiaType.fromValue(rsV.getString(26));
final CvssV3Data.CiaType integrityImpact = CvssV3Data.CiaType.fromValue(rsV.getString(27));
final CvssV3Data.CiaType availabilityImpact = CvssV3Data.CiaType.fromValue(rsV.getString(28));
final CvssV3Data.SeverityType baseSeverity = CvssV3Data.SeverityType.fromValue(rsV.getString(30));
final String vector = String.format("CVSS:%s/AV:%s/AC:%s/PR:%s/UI:%s/S:%s/C:%s/I:%s/A:%s",
version == null ? "" : version,
attackVector == null ? "" : attackVector.value().substring(0, 1),
attackComplexity == null ? "" : attackComplexity.value().substring(0, 1),
privilegesRequired == null ? "" : privilegesRequired.value().substring(0, 1),
userInteraction == null ? "" : userInteraction.value().substring(0, 1),
scope == null ? "" : scope.value().substring(0, 1),
confidentialityImpact == null ? "" : confidentialityImpact.value().substring(0, 1),
integrityImpact == null ? "" : integrityImpact.value().substring(0, 1),
availabilityImpact == null ? "" : availabilityImpact.value().substring(0, 1));
final CvssV3Data cvssData = new CvssV3Data(version, vector, attackVector, attackComplexity, privilegesRequired,
userInteraction, scope, confidentialityImpact, integrityImpact, availabilityImpact,
rsV.getDouble(29), baseSeverity, CvssV3Data.ExploitCodeMaturityType.PROOF_OF_CONCEPT,
CvssV3Data.RemediationLevelType.NOT_DEFINED, CvssV3Data.ConfidenceType.REASONABLE, 0.0,
CvssV3Data.SeverityType.MEDIUM, CvssV3Data.CiaRequirementType.NOT_DEFINED,
CvssV3Data.CiaRequirementType.NOT_DEFINED, CvssV3Data.CiaRequirementType.NOT_DEFINED,
CvssV3Data.ModifiedAttackVectorType.ADJACENT_NETWORK, CvssV3Data.ModifiedAttackComplexityType.NOT_DEFINED,
CvssV3Data.ModifiedPrivilegesRequiredType.NOT_DEFINED, CvssV3Data.ModifiedUserInteractionType.NOT_DEFINED,
CvssV3Data.ModifiedScopeType.NOT_DEFINED, CvssV3Data.ModifiedCiaType.NOT_DEFINED,
CvssV3Data.ModifiedCiaType.NOT_DEFINED, CvssV3Data.ModifiedCiaType.NOT_DEFINED, 1.0,
CvssV3Data.SeverityType.NONE);
final CvssV3 cvss = new CvssV3(null, null, cvssData, rsV.getDouble(19), rsV.getDouble(20));
vuln.setCvssV3(cvss);
}
} else {
LOGGER.debug(cve + " does not exist in the database");
return null;
}
}
try (PreparedStatement psCWE = getPreparedStatement(conn, SELECT_VULNERABILITY_CWE, cveId); ResultSet rsC = psCWE.executeQuery()) {
while (rsC.next()) {
vuln.addCwe(rsC.getString(1));
}
}
try (PreparedStatement psR = getPreparedStatement(conn, SELECT_REFERENCES, cveId); ResultSet rsR = psR.executeQuery()) {
while (rsR.next()) {
vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3));
}
}
try (PreparedStatement psS = getPreparedStatement(conn, SELECT_SOFTWARE, cveId); ResultSet rsS = psS.executeQuery()) {
//1 part, 2 vendor, 3 product, 4 version, 5 update_version, 6 edition, 7 lang,
//8 sw_edition, 9 target_sw, 10 target_hw, 11 other, 12 versionEndExcluding,
//13 versionEndIncluding, 14 versionStartExcluding, 15 versionStartIncluding, 16 vulnerable
while (rsS.next()) {
vulnerableSoftwareBuilder.part(rsS.getString(1))
.vendor(rsS.getString(2))
.product(rsS.getString(3))
.version(rsS.getString(4))
.update(rsS.getString(5))
.edition(rsS.getString(6))
.language(rsS.getString(7))
.swEdition(rsS.getString(8))
.targetSw(rsS.getString(9))
.targetHw(rsS.getString(10))
.other(rsS.getString(11))
.versionEndExcluding(rsS.getString(12))
.versionEndIncluding(rsS.getString(13))
.versionStartExcluding(rsS.getString(14))
.versionStartIncluding(rsS.getString(15))
.vulnerable(rsS.getBoolean(16));
vuln.addVulnerableSoftware(vulnerableSoftwareBuilder.build());
}
}
} catch (SQLException ex) {
throw new DatabaseException("Error retrieving " + cve, ex);
} catch (CpeParsingException | CpeValidationException ex) {
throw new DatabaseException("The database contains an invalid Vulnerable Software Entry", ex);
}
return vuln;
}
/**
* Updates the vulnerability within the database. If the vulnerability does
* not exist it will be added.
*
* @param cve the vulnerability from the NVD CVE Data Feed to add to the
* database
* @param baseEcosystem the ecosystem the CVE belongs to; this is based off
* of things like the CVE description
* @throws DatabaseException is thrown if the database
*/
public void updateVulnerability(DefCveItem cve, String baseEcosystem) {
clearCache();
final String cveId = cve.getCve().getId();
try {
if (cve.getCve().getVulnStatus().toUpperCase().startsWith("REJECT")) {
deleteVulnerability(cveId);
} else {
if (cveItemConverter.testCveCpeStartWithFilter(cve)) {
final String description = cveItemConverter.extractDescription(cve);
final int vulnerabilityId = updateOrInsertVulnerability(cve, description);
updateVulnerabilityInsertCwe(vulnerabilityId, cve);
updateVulnerabilityInsertReferences(vulnerabilityId, cve);
final List<VulnerableSoftware> software = parseCpes(cve);
updateVulnerabilityInsertSoftware(vulnerabilityId, cveId, software, baseEcosystem);
}
}
} catch (SQLException ex) {
final String msg = String.format("Error updating '%s'", cveId);
LOGGER.debug(msg, ex);
throw new DatabaseException(msg, ex);
} catch (CpeValidationException ex) {
final String msg = String.format("Error parsing CPE entry from '%s'", cveId);
LOGGER.debug(msg, ex);
throw new DatabaseException(msg, ex);
}
}
private void loadCpeEcosystemCache() {
final Map<Pair<String, String>, String> map = new HashMap<>();
try (Connection conn = databaseManager.getConnection();
PreparedStatement ps = getPreparedStatement(conn, SELECT_CPE_ECOSYSTEM);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
final Pair<String, String> key = new Pair<>(rs.getString(1), rs.getString(2));
final String value = rs.getString(3);
map.put(key, value);
}
} catch (SQLException ex) {
final String msg = String.format("Error loading the Cpe Ecosystem Cache: %s", ex.getMessage());
LOGGER.debug(msg, ex);
throw new DatabaseException(msg, ex);
}
CpeEcosystemCache.setCache(map);
}
private void saveCpeEcosystemCache() {
final Map<Pair<String, String>, String> map = CpeEcosystemCache.getChanged();
if (map != null && !map.isEmpty()) {
try (Connection conn = databaseManager.getConnection(); PreparedStatement ps = getPreparedStatement(conn, MERGE_CPE_ECOSYSTEM)) {
for (Map.Entry<Pair<String, String>, String> entry : map.entrySet()) {
ps.setString(1, entry.getKey().getLeft());
ps.setString(2, entry.getKey().getRight());
ps.setString(3, entry.getValue());
if (isBatchInsertEnabled()) {
ps.addBatch();
} else {
ps.execute();
}
}
if (isBatchInsertEnabled()) {
ps.executeBatch();
}
} catch (SQLException ex) {
final String msg = String.format("Error saving the Cpe Ecosystem Cache: %s", ex.getMessage());
LOGGER.debug(msg, ex);
throw new DatabaseException(msg, ex);
}
}
}
/**
* Used when updating a vulnerability - this method inserts the
* vulnerability entry itself.
*
* @param cve the CVE data
* @param description the description of the CVE entry
* @return the vulnerability ID
*/
private int updateOrInsertVulnerability(DefCveItem cve, String description) {
if (CpeEcosystemCache.isEmpty()) {
loadCpeEcosystemCache();
}
final int vulnerabilityId;
try (Connection conn = databaseManager.getConnection(); PreparedStatement callUpdate = getPreparedStatement(conn, UPDATE_VULNERABILITY)) {
// String 1.cve, String 2.description, String 3.v2Severity, Float 4.v2ExploitabilityScore,
// Float 5.v2ImpactScore, Boolean 6.v2AcInsufInfo, Boolean 7.v2ObtainAllPrivilege,
// Boolean 8.v2ObtainUserPrivilege, Boolean 9.v2ObtainOtherPrivilege, Boolean 10.v2UserInteractionRequired,
// Float 11.v2Score, String 12.v2AccessVector, String 13.v2AccessComplexity,
// String 14.v2Authentication, String 15.v2ConfidentialityImpact, String 16.v2IntegrityImpact,
// String 17.v2AvailabilityImpact, String 18.v2Version, Float 19.v3ExploitabilityScore,
// Float 20.v3ImpactScore, String 21.v3AttackVector, String 22.v3AttackComplexity,
// String 23.v3PrivilegesRequired, String 24.v3UserInteraction, String 25.v3Scope,
// String 26.v3ConfidentialityImpact, String 27.v3IntegrityImpact, String 28.v3AvailabilityImpact,
// Float 29.v3BaseScore, String 30.v3BaseSeverity, String 31.v3Version
callUpdate.setString(1, cve.getCve().getId());
callUpdate.setString(2, description);
Optional<CvssV2> optCvssv2 = null;
if (cve.getCve().getMetrics() != null && cve.getCve().getMetrics().getCvssMetricV2() != null) {
optCvssv2 = cve.getCve().getMetrics().getCvssMetricV2().stream().sorted(Comparator.comparing(CvssV2::getType)).findFirst();
}
if (optCvssv2 != null && optCvssv2.isPresent()) {
final CvssV2 cvssv2 = optCvssv2.get();
setUpdateColumn(callUpdate, 3, cvssv2.getBaseSeverity());
setUpdateColumn(callUpdate, 4, cvssv2.getExploitabilityScore());
setUpdateColumn(callUpdate, 5, cvssv2.getImpactScore());
setUpdateColumn(callUpdate, 6, cvssv2.getAcInsufInfo());
setUpdateColumn(callUpdate, 7, cvssv2.getObtainAllPrivilege());
setUpdateColumn(callUpdate, 8, cvssv2.getObtainUserPrivilege());
setUpdateColumn(callUpdate, 9, cvssv2.getObtainOtherPrivilege());
setUpdateColumn(callUpdate, 10, cvssv2.getUserInteractionRequired());
setUpdateColumn(callUpdate, 11, cvssv2.getCvssData().getBaseScore());
setUpdateColumn(callUpdate, 12, cvssv2.getCvssData().getAccessVector());
setUpdateColumn(callUpdate, 13, cvssv2.getCvssData().getAccessComplexity());
setUpdateColumn(callUpdate, 14, cvssv2.getCvssData().getAuthentication());
setUpdateColumn(callUpdate, 15, cvssv2.getCvssData().getConfidentialityImpact());
setUpdateColumn(callUpdate, 16, cvssv2.getCvssData().getIntegrityImpact());
setUpdateColumn(callUpdate, 17, cvssv2.getCvssData().getAvailabilityImpact());
setUpdateColumn(callUpdate, 18, cvssv2.getCvssData().getVersion());
} else {
callUpdate.setNull(3, java.sql.Types.VARCHAR);
callUpdate.setNull(4, java.sql.Types.DOUBLE);
callUpdate.setNull(5, java.sql.Types.DOUBLE);
callUpdate.setNull(6, java.sql.Types.VARCHAR);
callUpdate.setNull(7, java.sql.Types.BOOLEAN);
callUpdate.setNull(8, java.sql.Types.BOOLEAN);
callUpdate.setNull(9, java.sql.Types.BOOLEAN);
callUpdate.setNull(10, java.sql.Types.BOOLEAN);
callUpdate.setNull(11, java.sql.Types.DOUBLE);
callUpdate.setNull(12, java.sql.Types.VARCHAR);
callUpdate.setNull(13, java.sql.Types.VARCHAR);
callUpdate.setNull(14, java.sql.Types.VARCHAR);
callUpdate.setNull(15, java.sql.Types.VARCHAR);
callUpdate.setNull(16, java.sql.Types.VARCHAR);
callUpdate.setNull(17, java.sql.Types.VARCHAR);
callUpdate.setNull(18, java.sql.Types.VARCHAR);
}
Optional<CvssV3> optCvssv30 = Optional.empty();
if (cve.getCve().getMetrics() != null && cve.getCve().getMetrics().getCvssMetricV30() != null) {
optCvssv30 = cve.getCve().getMetrics().getCvssMetricV30().stream().sorted(Comparator.comparing(CvssV3::getType)).findFirst();
}
Optional<CvssV3> optCvssv31 = Optional.empty();
if (cve.getCve().getMetrics() != null && cve.getCve().getMetrics().getCvssMetricV31() != null) {
optCvssv31 = cve.getCve().getMetrics().getCvssMetricV31().stream().sorted(Comparator.comparing(CvssV3::getType)).findFirst();