Coverage Report - org.owasp.dependencycheck.data.nvdcve.CveDB
 
Classes in this File Line Coverage Branch Coverage Complexity
CveDB
44%
196/437
55%
73/132
5.391
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.nvdcve;
 19  
 
 20  
 import java.io.IOException;
 21  
 import java.io.UnsupportedEncodingException;
 22  
 import java.sql.CallableStatement;
 23  
 import java.sql.Connection;
 24  
 import java.sql.PreparedStatement;
 25  
 import java.sql.ResultSet;
 26  
 import java.sql.SQLException;
 27  
 import java.sql.Statement;
 28  
 import java.util.ArrayList;
 29  
 import java.util.HashMap;
 30  
 import java.util.HashSet;
 31  
 import java.util.List;
 32  
 import java.util.Map;
 33  
 import java.util.Map.Entry;
 34  
 import java.util.Properties;
 35  
 import java.util.ResourceBundle;
 36  
 import java.util.Set;
 37  
 import org.owasp.dependencycheck.data.cwe.CweDB;
 38  
 import org.owasp.dependencycheck.dependency.Reference;
 39  
 import org.owasp.dependencycheck.dependency.Vulnerability;
 40  
 import org.owasp.dependencycheck.dependency.VulnerableSoftware;
 41  
 import org.owasp.dependencycheck.utils.DBUtils;
 42  
 import org.owasp.dependencycheck.utils.DependencyVersion;
 43  
 import org.owasp.dependencycheck.utils.DependencyVersionUtil;
 44  
 import org.owasp.dependencycheck.utils.Pair;
 45  
 import org.owasp.dependencycheck.utils.Settings;
 46  
 import org.slf4j.Logger;
 47  
 import org.slf4j.LoggerFactory;
 48  
 
 49  
 /**
 50  
  * The database holding information about the NVD CVE data.
 51  
  *
 52  
  * @author Jeremy Long
 53  
  */
 54  
 public class CveDB {
 55  
 
 56  
     /**
 57  
      * The logger.
 58  
      */
 59  8
     private static final Logger LOGGER = LoggerFactory.getLogger(CveDB.class);
 60  
     /**
 61  
      * Database connection
 62  
      */
 63  
     private Connection conn;
 64  
     /**
 65  
      * The bundle of statements used when accessing the database.
 66  
      */
 67  48
     private ResourceBundle statementBundle = null;
 68  
 
 69  
     /**
 70  
      * Creates a new CveDB object and opens the database connection. Note, the connection must be closed by the caller by calling
 71  
      * the close method.
 72  
      *
 73  
      * @throws DatabaseException thrown if there is an exception opening the database.
 74  
      */
 75  
     public CveDB() throws DatabaseException {
 76  48
         super();
 77  48
         statementBundle = ResourceBundle.getBundle("data/dbStatements");
 78  
         try {
 79  48
             open();
 80  48
             databaseProperties = new DatabaseProperties(this);
 81  0
         } catch (DatabaseException ex) {
 82  0
             throw ex;
 83  48
         }
 84  48
     }
 85  
 
 86  
     /**
 87  
      * Returns the database connection.
 88  
      *
 89  
      * @return the database connection
 90  
      */
 91  
     protected Connection getConnection() {
 92  296
         return conn;
 93  
     }
 94  
 
 95  
     /**
 96  
      * Opens the database connection. If the database does not exist, it will create a new one.
 97  
      *
 98  
      * @throws DatabaseException thrown if there is an error opening the database connection
 99  
      */
 100  
     public final void open() throws DatabaseException {
 101  96
         if (!isOpen()) {
 102  48
             conn = ConnectionFactory.getConnection();
 103  
         }
 104  96
     }
 105  
 
 106  
     /**
 107  
      * Closes the DB4O database. Close should be called on this object when it is done being used.
 108  
      */
 109  
     public void close() {
 110  62
         if (conn != null) {
 111  
             try {
 112  48
                 conn.close();
 113  0
             } catch (SQLException ex) {
 114  0
                 LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
 115  0
                 LOGGER.debug("", ex);
 116  0
             } catch (Throwable ex) {
 117  0
                 LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
 118  0
                 LOGGER.debug("", ex);
 119  48
             }
 120  48
             conn = null;
 121  
         }
 122  62
     }
 123  
 
 124  
     /**
 125  
      * Returns whether the database connection is open or closed.
 126  
      *
 127  
      * @return whether the database connection is open or closed
 128  
      */
 129  
     public boolean isOpen() {
 130  96
         return conn != null;
 131  
     }
 132  
 
 133  
     /**
 134  
      * Commits all completed transactions.
 135  
      *
 136  
      * @throws SQLException thrown if a SQL Exception occurs
 137  
      */
 138  
     public void commit() throws SQLException {
 139  
         //temporary remove this as autocommit is on.
 140  
         //if (conn != null) {
 141  
         //    conn.commit();
 142  
         //}
 143  0
     }
 144  
 
 145  
     /**
 146  
      * Cleans up the object and ensures that "close" has been called.
 147  
      *
 148  
      * @throws Throwable thrown if there is a problem
 149  
      */
 150  
     @Override
 151  
     @SuppressWarnings("FinalizeDeclaration")
 152  
     protected void finalize() throws Throwable {
 153  14
         LOGGER.debug("Entering finalize");
 154  14
         close();
 155  14
         super.finalize();
 156  14
     }
 157  
     /**
 158  
      * Database properties object containing the 'properties' from the database table.
 159  
      */
 160  
     private DatabaseProperties databaseProperties;
 161  
 
 162  
     /**
 163  
      * Get the value of databaseProperties.
 164  
      *
 165  
      * @return the value of databaseProperties
 166  
      */
 167  
     public DatabaseProperties getDatabaseProperties() {
 168  24
         return databaseProperties;
 169  
     }
 170  
 
 171  
     /**
 172  
      * Searches the CPE entries in the database and retrieves all entries for a given vendor and product combination. The returned
 173  
      * list will include all versions of the product that are registered in the NVD CVE data.
 174  
      *
 175  
      * @param vendor the identified vendor name of the dependency being analyzed
 176  
      * @param product the identified name of the product of the dependency being analyzed
 177  
      * @return a set of vulnerable software
 178  
      */
 179  
     public Set<VulnerableSoftware> getCPEs(String vendor, String product) {
 180  24
         final Set<VulnerableSoftware> cpe = new HashSet<VulnerableSoftware>();
 181  24
         ResultSet rs = null;
 182  24
         PreparedStatement ps = null;
 183  
         try {
 184  24
             ps = getConnection().prepareStatement(statementBundle.getString("SELECT_CPE_ENTRIES"));
 185  24
             ps.setString(1, vendor);
 186  24
             ps.setString(2, product);
 187  24
             rs = ps.executeQuery();
 188  
 
 189  896
             while (rs.next()) {
 190  872
                 final VulnerableSoftware vs = new VulnerableSoftware();
 191  872
                 vs.setCpe(rs.getString(1));
 192  872
                 cpe.add(vs);
 193  872
             }
 194  0
         } catch (SQLException ex) {
 195  0
             LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
 196  0
             LOGGER.debug("", ex);
 197  
         } finally {
 198  24
             DBUtils.closeResultSet(rs);
 199  24
             DBUtils.closeStatement(ps);
 200  24
         }
 201  24
         return cpe;
 202  
     }
 203  
 
 204  
     /**
 205  
      * Returns the entire list of vendor/product combinations.
 206  
      *
 207  
      * @return the entire list of vendor/product combinations
 208  
      * @throws DatabaseException thrown when there is an error retrieving the data from the DB
 209  
      */
 210  
     public Set<Pair<String, String>> getVendorProductList() throws DatabaseException {
 211  8
         final Set<Pair<String, String>> data = new HashSet<Pair<String, String>>();
 212  8
         ResultSet rs = null;
 213  8
         PreparedStatement ps = null;
 214  
         try {
 215  8
             ps = getConnection().prepareStatement(statementBundle.getString("SELECT_VENDOR_PRODUCT_LIST"));
 216  8
             rs = ps.executeQuery();
 217  201186
             while (rs.next()) {
 218  201178
                 data.add(new Pair<String, String>(rs.getString(1), rs.getString(2)));
 219  
             }
 220  0
         } catch (SQLException ex) {
 221  0
             final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
 222  0
             throw new DatabaseException(msg, ex);
 223  
         } finally {
 224  8
             DBUtils.closeResultSet(rs);
 225  8
             DBUtils.closeStatement(ps);
 226  8
         }
 227  8
         return data;
 228  
     }
 229  
 
 230  
     /**
 231  
      * Returns a set of properties.
 232  
      *
 233  
      * @return the properties from the database
 234  
      */
 235  
     Properties getProperties() {
 236  48
         final Properties prop = new Properties();
 237  48
         PreparedStatement ps = null;
 238  48
         ResultSet rs = null;
 239  
         try {
 240  48
             ps = getConnection().prepareStatement(statementBundle.getString("SELECT_PROPERTIES"));
 241  48
             rs = ps.executeQuery();
 242  960
             while (rs.next()) {
 243  912
                 prop.setProperty(rs.getString(1), rs.getString(2));
 244  
             }
 245  0
         } catch (SQLException ex) {
 246  0
             LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
 247  0
             LOGGER.debug("", ex);
 248  
         } finally {
 249  48
             DBUtils.closeStatement(ps);
 250  48
             DBUtils.closeResultSet(rs);
 251  48
         }
 252  48
         return prop;
 253  
     }
 254  
 
 255  
     /**
 256  
      * Saves a set of properties to the database.
 257  
      *
 258  
      * @param props a collection of properties
 259  
      */
 260  
     void saveProperties(Properties props) {
 261  0
         PreparedStatement updateProperty = null;
 262  0
         PreparedStatement insertProperty = null;
 263  
         try {
 264  
             try {
 265  0
                 updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY"));
 266  0
                 insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY"));
 267  0
             } catch (SQLException ex) {
 268  0
                 LOGGER.warn("Unable to save properties to the database");
 269  0
                 LOGGER.debug("Unable to save properties to the database", ex);
 270  
                 return;
 271  0
             }
 272  0
             for (Entry<Object, Object> entry : props.entrySet()) {
 273  0
                 final String key = entry.getKey().toString();
 274  0
                 final String value = entry.getValue().toString();
 275  
                 try {
 276  0
                     updateProperty.setString(1, value);
 277  0
                     updateProperty.setString(2, key);
 278  0
                     if (updateProperty.executeUpdate() == 0) {
 279  0
                         insertProperty.setString(1, key);
 280  0
                         insertProperty.setString(2, value);
 281  
                     }
 282  0
                 } catch (SQLException ex) {
 283  0
                     LOGGER.warn("Unable to save property '{}' with a value of '{}' to the database", key, value);
 284  0
                     LOGGER.debug("", ex);
 285  0
                 }
 286  0
             }
 287  
         } finally {
 288  0
             DBUtils.closeStatement(updateProperty);
 289  0
             DBUtils.closeStatement(insertProperty);
 290  0
         }
 291  0
     }
 292  
 
 293  
     /**
 294  
      * Saves a property to the database.
 295  
      *
 296  
      * @param key the property key
 297  
      * @param value the property value
 298  
      */
 299  
     void saveProperty(String key, String value) {
 300  0
         PreparedStatement updateProperty = null;
 301  0
         PreparedStatement insertProperty = null;
 302  
         try {
 303  
             try {
 304  0
                 updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY"));
 305  0
             } catch (SQLException ex) {
 306  0
                 LOGGER.warn("Unable to save properties to the database");
 307  0
                 LOGGER.debug("Unable to save properties to the database", ex);
 308  
                 return;
 309  0
             }
 310  
             try {
 311  0
                 updateProperty.setString(1, value);
 312  0
                 updateProperty.setString(2, key);
 313  0
                 if (updateProperty.executeUpdate() == 0) {
 314  
                     try {
 315  0
                         insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY"));
 316  0
                     } catch (SQLException ex) {
 317  0
                         LOGGER.warn("Unable to save properties to the database");
 318  0
                         LOGGER.debug("Unable to save properties to the database", ex);
 319  
                         return;
 320  0
                     }
 321  0
                     insertProperty.setString(1, key);
 322  0
                     insertProperty.setString(2, value);
 323  0
                     insertProperty.execute();
 324  
                 }
 325  0
             } catch (SQLException ex) {
 326  0
                 LOGGER.warn("Unable to save property '{}' with a value of '{}' to the database", key, value);
 327  0
                 LOGGER.debug("", ex);
 328  0
             }
 329  
         } finally {
 330  0
             DBUtils.closeStatement(updateProperty);
 331  0
             DBUtils.closeStatement(insertProperty);
 332  0
         }
 333  0
     }
 334  
 
 335  
     /**
 336  
      * Retrieves the vulnerabilities associated with the specified CPE.
 337  
      *
 338  
      * @param cpeStr the CPE name
 339  
      * @return a list of Vulnerabilities
 340  
      * @throws DatabaseException thrown if there is an exception retrieving data
 341  
      */
 342  
     public List<Vulnerability> getVulnerabilities(String cpeStr) throws DatabaseException {
 343  24
         ResultSet rs = null;
 344  24
         final VulnerableSoftware cpe = new VulnerableSoftware();
 345  
         try {
 346  24
             cpe.parseName(cpeStr);
 347  0
         } catch (UnsupportedEncodingException ex) {
 348  0
             LOGGER.trace("", ex);
 349  24
         }
 350  24
         final DependencyVersion detectedVersion = parseDependencyVersion(cpe);
 351  24
         final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>();
 352  
 
 353  
         PreparedStatement ps;
 354  
         try {
 355  24
             ps = getConnection().prepareStatement(statementBundle.getString("SELECT_CVE_FROM_SOFTWARE"));
 356  24
             ps.setString(1, cpe.getVendor());
 357  24
             ps.setString(2, cpe.getProduct());
 358  24
             rs = ps.executeQuery();
 359  24
             String currentCVE = "";
 360  
 
 361  24
             final Map<String, Boolean> vulnSoftware = new HashMap<String, Boolean>();
 362  2256
             while (rs.next()) {
 363  2232
                 final String cveId = rs.getString(1);
 364  2232
                 if (!currentCVE.equals(cveId)) { //check for match and add
 365  80
                     final Entry<String, Boolean> matchedCPE = getMatchingSoftware(vulnSoftware, cpe.getVendor(), cpe.getProduct(), detectedVersion);
 366  80
                     if (matchedCPE != null) {
 367  48
                         final Vulnerability v = getVulnerability(currentCVE);
 368  48
                         v.setMatchedCPE(matchedCPE.getKey(), matchedCPE.getValue() ? "Y" : null);
 369  48
                         vulnerabilities.add(v);
 370  
                     }
 371  80
                     vulnSoftware.clear();
 372  80
                     currentCVE = cveId;
 373  
                 }
 374  
 
 375  2232
                 final String cpeId = rs.getString(2);
 376  2232
                 final String previous = rs.getString(3);
 377  2232
                 final Boolean p = previous != null && !previous.isEmpty();
 378  2232
                 vulnSoftware.put(cpeId, p);
 379  2232
             }
 380  
             //remember to process the last set of CVE/CPE entries
 381  24
             final Entry<String, Boolean> matchedCPE = getMatchingSoftware(vulnSoftware, cpe.getVendor(), cpe.getProduct(), detectedVersion);
 382  24
             if (matchedCPE != null) {
 383  16
                 final Vulnerability v = getVulnerability(currentCVE);
 384  16
                 v.setMatchedCPE(matchedCPE.getKey(), matchedCPE.getValue() ? "Y" : null);
 385  16
                 vulnerabilities.add(v);
 386  
             }
 387  24
             DBUtils.closeResultSet(rs);
 388  24
             DBUtils.closeStatement(ps);
 389  0
         } catch (SQLException ex) {
 390  0
             throw new DatabaseException("Exception retrieving vulnerability for " + cpeStr, ex);
 391  
         } finally {
 392  24
             DBUtils.closeResultSet(rs);
 393  24
         }
 394  24
         return vulnerabilities;
 395  
     }
 396  
 
 397  
     /**
 398  
      * Gets a vulnerability for the provided CVE.
 399  
      *
 400  
      * @param cve the CVE to lookup
 401  
      * @return a vulnerability object
 402  
      * @throws DatabaseException if an exception occurs
 403  
      */
 404  
     private Vulnerability getVulnerability(String cve) throws DatabaseException {
 405  64
         PreparedStatement psV = null;
 406  64
         PreparedStatement psR = null;
 407  64
         PreparedStatement psS = null;
 408  64
         ResultSet rsV = null;
 409  64
         ResultSet rsR = null;
 410  64
         ResultSet rsS = null;
 411  64
         Vulnerability vuln = null;
 412  
         try {
 413  64
             psV = getConnection().prepareStatement(statementBundle.getString("SELECT_VULNERABILITY"));
 414  64
             psV.setString(1, cve);
 415  64
             rsV = psV.executeQuery();
 416  64
             if (rsV.next()) {
 417  64
                 vuln = new Vulnerability();
 418  64
                 vuln.setName(cve);
 419  64
                 vuln.setDescription(rsV.getString(2));
 420  64
                 String cwe = rsV.getString(3);
 421  64
                 if (cwe != null) {
 422  64
                     final String name = CweDB.getCweName(cwe);
 423  64
                     if (name != null) {
 424  56
                         cwe += " " + name;
 425  
                     }
 426  
                 }
 427  64
                 final int cveId = rsV.getInt(1);
 428  64
                 vuln.setCwe(cwe);
 429  64
                 vuln.setCvssScore(rsV.getFloat(4));
 430  64
                 vuln.setCvssAccessVector(rsV.getString(5));
 431  64
                 vuln.setCvssAccessComplexity(rsV.getString(6));
 432  64
                 vuln.setCvssAuthentication(rsV.getString(7));
 433  64
                 vuln.setCvssConfidentialityImpact(rsV.getString(8));
 434  64
                 vuln.setCvssIntegrityImpact(rsV.getString(9));
 435  64
                 vuln.setCvssAvailabilityImpact(rsV.getString(10));
 436  
 
 437  64
                 psR = getConnection().prepareStatement(statementBundle.getString("SELECT_REFERENCES"));
 438  64
                 psR.setInt(1, cveId);
 439  64
                 rsR = psR.executeQuery();
 440  608
                 while (rsR.next()) {
 441  544
                     vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3));
 442  
                 }
 443  64
                 psS = getConnection().prepareStatement(statementBundle.getString("SELECT_SOFTWARE"));
 444  64
                 psS.setInt(1, cveId);
 445  64
                 rsS = psS.executeQuery();
 446  1952
                 while (rsS.next()) {
 447  1888
                     final String cpe = rsS.getString(1);
 448  1888
                     final String prevVersion = rsS.getString(2);
 449  1888
                     if (prevVersion == null) {
 450  1824
                         vuln.addVulnerableSoftware(cpe);
 451  
                     } else {
 452  64
                         vuln.addVulnerableSoftware(cpe, prevVersion);
 453  
                     }
 454  1888
                 }
 455  
             }
 456  0
         } catch (SQLException ex) {
 457  0
             throw new DatabaseException("Error retrieving " + cve, ex);
 458  
         } finally {
 459  64
             DBUtils.closeResultSet(rsV);
 460  64
             DBUtils.closeResultSet(rsR);
 461  64
             DBUtils.closeResultSet(rsS);
 462  64
             DBUtils.closeStatement(psV);
 463  64
             DBUtils.closeStatement(psR);
 464  64
             DBUtils.closeStatement(psS);
 465  64
         }
 466  64
         return vuln;
 467  
     }
 468  
 
 469  
     /**
 470  
      * Updates the vulnerability within the database. If the vulnerability does not exist it will be added.
 471  
      *
 472  
      * @param vuln the vulnerability to add to the database
 473  
      * @throws DatabaseException is thrown if the database
 474  
      */
 475  
     public void updateVulnerability(Vulnerability vuln) throws DatabaseException {
 476  0
         PreparedStatement selectVulnerabilityId = null;
 477  0
         PreparedStatement deleteVulnerability = null;
 478  0
         PreparedStatement deleteReferences = null;
 479  0
         PreparedStatement deleteSoftware = null;
 480  0
         PreparedStatement updateVulnerability = null;
 481  0
         PreparedStatement insertVulnerability = null;
 482  0
         PreparedStatement insertReference = null;
 483  0
         PreparedStatement selectCpeId = null;
 484  0
         PreparedStatement insertCpe = null;
 485  0
         PreparedStatement insertSoftware = null;
 486  
 
 487  
         try {
 488  0
             selectVulnerabilityId = getConnection().prepareStatement(statementBundle.getString("SELECT_VULNERABILITY_ID"));
 489  0
             deleteVulnerability = getConnection().prepareStatement(statementBundle.getString("DELETE_VULNERABILITY"));
 490  0
             deleteReferences = getConnection().prepareStatement(statementBundle.getString("DELETE_REFERENCE"));
 491  0
             deleteSoftware = getConnection().prepareStatement(statementBundle.getString("DELETE_SOFTWARE"));
 492  0
             updateVulnerability = getConnection().prepareStatement(statementBundle.getString("UPDATE_VULNERABILITY"));
 493  0
             String ids[] = {"id"};
 494  0
             insertVulnerability = getConnection().prepareStatement(statementBundle.getString("INSERT_VULNERABILITY"),
 495  
                     //Statement.RETURN_GENERATED_KEYS);
 496  
                     ids);
 497  0
             insertReference = getConnection().prepareStatement(statementBundle.getString("INSERT_REFERENCE"));
 498  0
             selectCpeId = getConnection().prepareStatement(statementBundle.getString("SELECT_CPE_ID"));
 499  0
             insertCpe = getConnection().prepareStatement(statementBundle.getString("INSERT_CPE"),
 500  
                     //Statement.RETURN_GENERATED_KEYS);
 501  
                     ids);
 502  0
             insertSoftware = getConnection().prepareStatement(statementBundle.getString("INSERT_SOFTWARE"));
 503  0
             int vulnerabilityId = 0;
 504  0
             selectVulnerabilityId.setString(1, vuln.getName());
 505  0
             ResultSet rs = selectVulnerabilityId.executeQuery();
 506  0
             if (rs.next()) {
 507  0
                 vulnerabilityId = rs.getInt(1);
 508  
                 // first delete any existing vulnerability info. We don't know what was updated. yes, slower but atm easier.
 509  0
                 deleteReferences.setInt(1, vulnerabilityId);
 510  0
                 deleteReferences.execute();
 511  0
                 deleteSoftware.setInt(1, vulnerabilityId);
 512  0
                 deleteSoftware.execute();
 513  
             }
 514  0
             DBUtils.closeResultSet(rs);
 515  0
             rs = null;
 516  0
             if (vulnerabilityId != 0) {
 517  0
                 if (vuln.getDescription().contains("** REJECT **")) {
 518  0
                     deleteVulnerability.setInt(1, vulnerabilityId);
 519  0
                     deleteVulnerability.executeUpdate();
 520  
                 } else {
 521  0
                     updateVulnerability.setString(1, vuln.getDescription());
 522  0
                     updateVulnerability.setString(2, vuln.getCwe());
 523  0
                     updateVulnerability.setFloat(3, vuln.getCvssScore());
 524  0
                     updateVulnerability.setString(4, vuln.getCvssAccessVector());
 525  0
                     updateVulnerability.setString(5, vuln.getCvssAccessComplexity());
 526  0
                     updateVulnerability.setString(6, vuln.getCvssAuthentication());
 527  0
                     updateVulnerability.setString(7, vuln.getCvssConfidentialityImpact());
 528  0
                     updateVulnerability.setString(8, vuln.getCvssIntegrityImpact());
 529  0
                     updateVulnerability.setString(9, vuln.getCvssAvailabilityImpact());
 530  0
                     updateVulnerability.setInt(10, vulnerabilityId);
 531  0
                     updateVulnerability.executeUpdate();
 532  
                 }
 533  
             } else {
 534  0
                 insertVulnerability.setString(1, vuln.getName());
 535  0
                 insertVulnerability.setString(2, vuln.getDescription());
 536  0
                 insertVulnerability.setString(3, vuln.getCwe());
 537  0
                 insertVulnerability.setFloat(4, vuln.getCvssScore());
 538  0
                 insertVulnerability.setString(5, vuln.getCvssAccessVector());
 539  0
                 insertVulnerability.setString(6, vuln.getCvssAccessComplexity());
 540  0
                 insertVulnerability.setString(7, vuln.getCvssAuthentication());
 541  0
                 insertVulnerability.setString(8, vuln.getCvssConfidentialityImpact());
 542  0
                 insertVulnerability.setString(9, vuln.getCvssIntegrityImpact());
 543  0
                 insertVulnerability.setString(10, vuln.getCvssAvailabilityImpact());
 544  0
                 insertVulnerability.execute();
 545  
                 try {
 546  0
                     rs = insertVulnerability.getGeneratedKeys();
 547  0
                     rs.next();
 548  0
                     vulnerabilityId = rs.getInt(1);
 549  0
                 } catch (SQLException ex) {
 550  0
                     final String msg = String.format("Unable to retrieve id for new vulnerability for '%s'", vuln.getName());
 551  0
                     throw new DatabaseException(msg, ex);
 552  
                 } finally {
 553  0
                     DBUtils.closeResultSet(rs);
 554  0
                     rs = null;
 555  0
                 }
 556  
             }
 557  0
             insertReference.setInt(1, vulnerabilityId);
 558  0
             for (Reference r : vuln.getReferences()) {
 559  0
                 insertReference.setString(2, r.getName());
 560  0
                 insertReference.setString(3, r.getUrl());
 561  0
                 insertReference.setString(4, r.getSource());
 562  0
                 insertReference.execute();
 563  0
             }
 564  0
             for (VulnerableSoftware s : vuln.getVulnerableSoftware()) {
 565  0
                 int cpeProductId = 0;
 566  0
                 selectCpeId.setString(1, s.getName());
 567  
                 try {
 568  0
                     rs = selectCpeId.executeQuery();
 569  0
                     if (rs.next()) {
 570  0
                         cpeProductId = rs.getInt(1);
 571  
                     }
 572  0
                 } catch (SQLException ex) {
 573  0
                     throw new DatabaseException("Unable to get primary key for new cpe: " + s.getName(), ex);
 574  
                 } finally {
 575  0
                     DBUtils.closeResultSet(rs);
 576  0
                     rs = null;
 577  0
                 }
 578  
 
 579  0
                 if (cpeProductId == 0) {
 580  0
                     insertCpe.setString(1, s.getName());
 581  0
                     insertCpe.setString(2, s.getVendor());
 582  0
                     insertCpe.setString(3, s.getProduct());
 583  0
                     insertCpe.executeUpdate();
 584  0
                     cpeProductId = DBUtils.getGeneratedKey(insertCpe);
 585  
                 }
 586  0
                 if (cpeProductId == 0) {
 587  0
                     throw new DatabaseException("Unable to retrieve cpeProductId - no data returned");
 588  
                 }
 589  
 
 590  0
                 insertSoftware.setInt(1, vulnerabilityId);
 591  0
                 insertSoftware.setInt(2, cpeProductId);
 592  0
                 if (s.getPreviousVersion() == null) {
 593  0
                     insertSoftware.setNull(3, java.sql.Types.VARCHAR);
 594  
                 } else {
 595  0
                     insertSoftware.setString(3, s.getPreviousVersion());
 596  
                 }
 597  0
                 insertSoftware.execute();
 598  0
             }
 599  
 
 600  0
         } catch (SQLException ex) {
 601  0
             final String msg = String.format("Error updating '%s'", vuln.getName());
 602  0
             LOGGER.debug("", ex);
 603  0
             throw new DatabaseException(msg, ex);
 604  
         } finally {
 605  0
             DBUtils.closeStatement(selectVulnerabilityId);
 606  0
             DBUtils.closeStatement(deleteReferences);
 607  0
             DBUtils.closeStatement(deleteSoftware);
 608  0
             DBUtils.closeStatement(updateVulnerability);
 609  0
             DBUtils.closeStatement(deleteVulnerability);
 610  0
             DBUtils.closeStatement(insertVulnerability);
 611  0
             DBUtils.closeStatement(insertReference);
 612  0
             DBUtils.closeStatement(selectCpeId);
 613  0
             DBUtils.closeStatement(insertCpe);
 614  0
             DBUtils.closeStatement(insertSoftware);
 615  0
         }
 616  0
     }
 617  
 
 618  
     /**
 619  
      * Checks to see if data exists so that analysis can be performed.
 620  
      *
 621  
      * @return <code>true</code> if data exists; otherwise <code>false</code>
 622  
      */
 623  
     public boolean dataExists() {
 624  8
         Statement cs = null;
 625  8
         ResultSet rs = null;
 626  
         try {
 627  8
             cs = conn.createStatement();
 628  8
             rs = cs.executeQuery("SELECT COUNT(*) records FROM cpeEntry");
 629  8
             if (rs.next()) {
 630  8
                 if (rs.getInt(1) > 0) {
 631  8
                     return true;
 632  
                 }
 633  
             }
 634  0
         } catch (SQLException ex) {
 635  
             String dd;
 636  
             try {
 637  0
                 dd = Settings.getDataDirectory().getAbsolutePath();
 638  0
             } catch (IOException ex1) {
 639  0
                 dd = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
 640  0
             }
 641  0
             LOGGER.error("Unable to access the local database.\n\nEnsure that '{}' is a writable directory. "
 642  
                     + "If the problem persist try deleting the files in '{}' and running {} again. If the problem continues, please "
 643  
                     + "create a log file (see documentation at http://jeremylong.github.io/DependencyCheck/) and open a ticket at "
 644  
                     + "https://github.com/jeremylong/DependencyCheck/issues and include the log file.\n\n",
 645  
                     dd, dd, Settings.getString(Settings.KEYS.APPLICATION_VAME));
 646  0
             LOGGER.debug("", ex);
 647  
         } finally {
 648  8
             DBUtils.closeResultSet(rs);
 649  8
             DBUtils.closeStatement(cs);
 650  0
         }
 651  0
         return false;
 652  
     }
 653  
 
 654  
     /**
 655  
      * It is possible that orphaned rows may be generated during database updates. This should be called after all updates have
 656  
      * been completed to ensure orphan entries are removed.
 657  
      */
 658  
     public void cleanupDatabase() {
 659  0
         PreparedStatement ps = null;
 660  
         try {
 661  0
             ps = getConnection().prepareStatement(statementBundle.getString("CLEANUP_ORPHANS"));
 662  0
             if (ps != null) {
 663  0
                 ps.executeUpdate();
 664  
             }
 665  0
         } catch (SQLException ex) {
 666  0
             LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
 667  0
             LOGGER.debug("", ex);
 668  
         } finally {
 669  0
             DBUtils.closeStatement(ps);
 670  0
         }
 671  0
     }
 672  
 
 673  
     /**
 674  
      * Determines if the given identifiedVersion is affected by the given cpeId and previous version flag. A non-null, non-empty
 675  
      * string passed to the previous version argument indicates that all previous versions are affected.
 676  
      *
 677  
      * @param vendor the vendor of the dependency being analyzed
 678  
      * @param product the product name of the dependency being analyzed
 679  
      * @param vulnerableSoftware a map of the vulnerable software with a boolean indicating if all previous versions are affected
 680  
      * @param identifiedVersion the identified version of the dependency being analyzed
 681  
      * @return true if the identified version is affected, otherwise false
 682  
      */
 683  
     Entry<String, Boolean> getMatchingSoftware(Map<String, Boolean> vulnerableSoftware, String vendor, String product,
 684  
             DependencyVersion identifiedVersion) {
 685  
 
 686  104
         final boolean isVersionTwoADifferentProduct = "apache".equals(vendor) && "struts".equals(product);
 687  
 
 688  104
         final Set<String> majorVersionsAffectingAllPrevious = new HashSet<String>();
 689  104
         final boolean matchesAnyPrevious = identifiedVersion == null || "-".equals(identifiedVersion.toString());
 690  104
         String majorVersionMatch = null;
 691  104
         for (Entry<String, Boolean> entry : vulnerableSoftware.entrySet()) {
 692  2232
             final DependencyVersion v = parseDependencyVersion(entry.getKey());
 693  2232
             if (v == null || "-".equals(v.toString())) { //all versions
 694  0
                 return entry;
 695  
             }
 696  2232
             if (entry.getValue()) {
 697  64
                 if (matchesAnyPrevious) {
 698  0
                     return entry;
 699  
                 }
 700  64
                 if (identifiedVersion != null && identifiedVersion.getVersionParts().get(0).equals(v.getVersionParts().get(0))) {
 701  48
                     majorVersionMatch = v.getVersionParts().get(0);
 702  
                 }
 703  64
                 majorVersionsAffectingAllPrevious.add(v.getVersionParts().get(0));
 704  
             }
 705  2232
         }
 706  104
         if (matchesAnyPrevious) {
 707  0
             return null;
 708  
         }
 709  
 
 710  104
         final boolean canSkipVersions = majorVersionMatch != null && majorVersionsAffectingAllPrevious.size() > 1;
 711  
         //yes, we are iterating over this twice. The first time we are skipping versions those that affect all versions
 712  
         //then later we process those that affect all versions. This could be done with sorting...
 713  104
         for (Entry<String, Boolean> entry : vulnerableSoftware.entrySet()) {
 714  1856
             if (!entry.getValue()) {
 715  1800
                 final DependencyVersion v = parseDependencyVersion(entry.getKey());
 716  
                 //this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this.
 717  1800
                 if (canSkipVersions && !majorVersionMatch.equals(v.getVersionParts().get(0))) {
 718  80
                     continue;
 719  
                 }
 720  
                 //this can't dereference a null 'identifiedVersion' because if it was null we would have exited
 721  
                 //in the above loop or just after loop (if matchesAnyPrevious return null).
 722  1720
                 if (identifiedVersion.equals(v)) {
 723  64
                     return entry;
 724  
                 }
 725  
             }
 726  1712
         }
 727  40
         for (Entry<String, Boolean> entry : vulnerableSoftware.entrySet()) {
 728  448
             if (entry.getValue()) {
 729  0
                 final DependencyVersion v = parseDependencyVersion(entry.getKey());
 730  
                 //this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this.
 731  0
                 if (canSkipVersions && !majorVersionMatch.equals(v.getVersionParts().get(0))) {
 732  0
                     continue;
 733  
                 }
 734  
                 //this can't dereference a null 'identifiedVersion' because if it was null we would have exited
 735  
                 //in the above loop or just after loop (if matchesAnyPrevious return null).
 736  0
                 if (entry.getValue() && identifiedVersion.compareTo(v) <= 0) {
 737  0
                     if (!(isVersionTwoADifferentProduct && !identifiedVersion.getVersionParts().get(0).equals(v.getVersionParts().get(0)))) {
 738  0
                         return entry;
 739  
                     }
 740  
                 }
 741  
             }
 742  448
         }
 743  40
         return null;
 744  
     }
 745  
 
 746  
     /**
 747  
      * Parses the version (including revision) from a CPE identifier. If no version is identified then a '-' is returned.
 748  
      *
 749  
      * @param cpeStr a cpe identifier
 750  
      * @return a dependency version
 751  
      */
 752  
     private DependencyVersion parseDependencyVersion(String cpeStr) {
 753  4032
         final VulnerableSoftware cpe = new VulnerableSoftware();
 754  
         try {
 755  4032
             cpe.parseName(cpeStr);
 756  0
         } catch (UnsupportedEncodingException ex) {
 757  
             //never going to happen.
 758  0
             LOGGER.trace("", ex);
 759  4032
         }
 760  4032
         return parseDependencyVersion(cpe);
 761  
     }
 762  
 
 763  
     /**
 764  
      * Takes a CPE and parses out the version number. If no version is identified then a '-' is returned.
 765  
      *
 766  
      * @param cpe a cpe object
 767  
      * @return a dependency version
 768  
      */
 769  
     private DependencyVersion parseDependencyVersion(VulnerableSoftware cpe) {
 770  
         DependencyVersion cpeVersion;
 771  4056
         if (cpe.getVersion() != null && !cpe.getVersion().isEmpty()) {
 772  
             String versionText;
 773  4056
             if (cpe.getUpdate() != null && !cpe.getUpdate().isEmpty()) {
 774  1040
                 versionText = String.format("%s.%s", cpe.getVersion(), cpe.getUpdate());
 775  
             } else {
 776  3016
                 versionText = cpe.getVersion();
 777  
             }
 778  4056
             cpeVersion = DependencyVersionUtil.parseVersion(versionText);
 779  4056
         } else {
 780  0
             cpeVersion = new DependencyVersion("-");
 781  
         }
 782  4056
         return cpeVersion;
 783  
     }
 784  
 
 785  
     /**
 786  
      * Deletes unused dictionary entries from the database.
 787  
      */
 788  
     public void deleteUnusedCpe() {
 789  0
         CallableStatement cs = null;
 790  
         try {
 791  0
             cs = getConnection().prepareCall(statementBundle.getString("DELETE_UNUSED_DICT_CPE"));
 792  0
             cs.executeUpdate();
 793  0
         } catch (SQLException ex) {
 794  0
             LOGGER.error("Unable to delete CPE dictionary entries", ex);
 795  
         } finally {
 796  0
             DBUtils.closeStatement(cs);
 797  0
         }
 798  0
     }
 799  
 
 800  
     /**
 801  
      * Merges CPE entries into the database.
 802  
      *
 803  
      * @param cpe the CPE identifier
 804  
      * @param vendor the CPE vendor
 805  
      * @param product the CPE product
 806  
      */
 807  
     public void addCpe(String cpe, String vendor, String product) {
 808  0
         PreparedStatement ps = null;
 809  
         try {
 810  0
             ps = getConnection().prepareCall(statementBundle.getString("ADD_DICT_CPE"));
 811  0
             ps.setString(1, cpe);
 812  0
             ps.setString(2, vendor);
 813  0
             ps.setString(3, product);
 814  0
             ps.executeUpdate();
 815  0
         } catch (SQLException ex) {
 816  0
             LOGGER.error("Unable to add CPE dictionary entry", ex);
 817  
         } finally {
 818  0
             DBUtils.closeStatement(ps);
 819  0
         }
 820  0
     }
 821  
 }