Coverage Report - org.owasp.dependencycheck.data.nvdcve.CveDB
 
Classes in this File Line Coverage Branch Coverage Complexity
CveDB
47%
170/360
61%
55/90
4.5
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Dependency-check-core is free software: you can redistribute it and/or modify it
 5  
  * under the terms of the GNU General Public License as published by the Free
 6  
  * Software Foundation, either version 3 of the License, or (at your option) any
 7  
  * later version.
 8  
  *
 9  
  * Dependency-check-core is distributed in the hope that it will be useful, but
 10  
  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  
  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 12  
  * details.
 13  
  *
 14  
  * You should have received a copy of the GNU General Public License along with
 15  
  * dependency-check-core. If not, see http://www.gnu.org/licenses/.
 16  
  *
 17  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 18  
  */
 19  
 package org.owasp.dependencycheck.data.nvdcve;
 20  
 
 21  
 import java.io.UnsupportedEncodingException;
 22  
 import java.sql.Connection;
 23  
 import java.sql.PreparedStatement;
 24  
 import java.sql.ResultSet;
 25  
 import java.sql.SQLException;
 26  
 import java.sql.Statement;
 27  
 import java.util.ArrayList;
 28  
 import java.util.HashSet;
 29  
 import java.util.List;
 30  
 import java.util.Map.Entry;
 31  
 import java.util.Properties;
 32  
 import java.util.Set;
 33  
 import java.util.logging.Level;
 34  
 import java.util.logging.Logger;
 35  
 import org.owasp.dependencycheck.data.cwe.CweDB;
 36  
 import org.owasp.dependencycheck.dependency.Reference;
 37  
 import org.owasp.dependencycheck.dependency.Vulnerability;
 38  
 import org.owasp.dependencycheck.dependency.VulnerableSoftware;
 39  
 import org.owasp.dependencycheck.utils.DBUtils;
 40  
 import org.owasp.dependencycheck.utils.DependencyVersion;
 41  
 import org.owasp.dependencycheck.utils.DependencyVersionUtil;
 42  
 
 43  
 /**
 44  
  * The database holding information about the NVD CVE data.
 45  
  *
 46  
  * @author Jeremy Long <jeremy.long@owasp.org>
 47  
  */
 48  
 public class CveDB {
 49  
 
 50  
     /**
 51  
      * Database connection
 52  
      */
 53  
     private Connection conn;
 54  
 
 55  
     /**
 56  
      * Creates a new CveDB object and opens the database connection. Note, the connection must be closed by the caller
 57  
      * by calling the close method.
 58  
      *
 59  
      * @throws DatabaseException thrown if there is an exception opening the database.
 60  
      */
 61  
     public CveDB() throws DatabaseException {
 62  24
         super();
 63  
         try {
 64  24
             open();
 65  24
             databaseProperties = new DatabaseProperties(this);
 66  0
         } catch (DatabaseException ex) {
 67  0
             throw ex;
 68  24
         }
 69  24
     }
 70  
 
 71  
     /**
 72  
      * Returns the database connection.
 73  
      *
 74  
      * @return the database connection
 75  
      */
 76  
     protected Connection getConnection() {
 77  304
         return conn;
 78  
     }
 79  
 
 80  
     /**
 81  
      * Opens the database connection. If the database does not exist, it will create a new one.
 82  
      *
 83  
      * @throws DatabaseException thrown if there is an error opening the database connection
 84  
      */
 85  
     public final void open() throws DatabaseException {
 86  48
         conn = ConnectionFactory.getConnection();
 87  48
     }
 88  
 
 89  
     /**
 90  
      * Closes the DB4O database. Close should be called on this object when it is done being used.
 91  
      */
 92  
     public void close() {
 93  39
         if (conn != null) {
 94  
             try {
 95  24
                 conn.close();
 96  0
             } catch (SQLException ex) {
 97  0
                 final String msg = "There was an error attempting to close the CveDB, see the log for more details.";
 98  0
                 Logger.getLogger(DBUtils.class.getName()).log(Level.SEVERE, msg);
 99  0
                 Logger.getLogger(DBUtils.class.getName()).log(Level.FINE, null, ex);
 100  24
             }
 101  24
             conn = null;
 102  
         }
 103  39
     }
 104  
 
 105  
     /**
 106  
      * Returns whether the database connection is open or closed.
 107  
      *
 108  
      * @return whether the database connection is open or closed
 109  
      */
 110  
     public boolean isOpen() {
 111  0
         return conn != null;
 112  
     }
 113  
 
 114  
     /**
 115  
      * Commits all completed transactions.
 116  
      *
 117  
      * @throws SQLException thrown if a SQL Exception occurs
 118  
      */
 119  
     public void commit() throws SQLException {
 120  1
         if (conn != null) {
 121  
             //temporary remove this as autocommit is on.
 122  
             //conn.commit();
 123  
         }
 124  1
     }
 125  
 
 126  
     /**
 127  
      * Cleans up the object and ensures that "close" has been called.
 128  
      *
 129  
      * @throws Throwable thrown if there is a problem
 130  
      */
 131  
     @Override
 132  
     protected void finalize() throws Throwable {
 133  15
         close();
 134  15
         super.finalize();
 135  15
     }
 136  
     /**
 137  
      * Database properties object containing the 'properties' from the database table.
 138  
      */
 139  
     private DatabaseProperties databaseProperties;
 140  
 
 141  
     /**
 142  
      * Get the value of databaseProperties.
 143  
      *
 144  
      * @return the value of databaseProperties
 145  
      */
 146  
     public DatabaseProperties getDatabaseProperties() {
 147  4
         return databaseProperties;
 148  
     }
 149  
     //<editor-fold defaultstate="collapsed" desc="Constants to create, maintain, and retrieve data from the CVE Database">
 150  
     /**
 151  
      * SQL Statement to delete references by vulnerability ID.
 152  
      */
 153  
     private static final String DELETE_REFERENCE = "DELETE FROM reference WHERE cveid = ?";
 154  
     /**
 155  
      * SQL Statement to delete software by vulnerability ID.
 156  
      */
 157  
     private static final String DELETE_SOFTWARE = "DELETE FROM software WHERE cveid = ?";
 158  
     /**
 159  
      * SQL Statement to delete a vulnerability by CVE.
 160  
      */
 161  
     private static final String DELETE_VULNERABILITY = "DELETE FROM vulnerability WHERE id = ?";
 162  
     /**
 163  
      * SQL Statement to cleanup orphan entries. Yes, the db schema could be a little tighter, but what we have works
 164  
      * well to keep the data file size down a bit.
 165  
      */
 166  
     private static final String CLEANUP_ORPHANS = "DELETE FROM CpeEntry WHERE id not in (SELECT CPEEntryId FROM Software); ";
 167  
     /**
 168  
      * SQL Statement to insert a new reference.
 169  
      */
 170  
     private static final String INSERT_REFERENCE = "INSERT INTO reference (cveid, name, url, source) VALUES (?, ?, ?, ?)";
 171  
     /**
 172  
      * SQL Statement to insert a new software.
 173  
      */
 174  
     private static final String INSERT_SOFTWARE = "INSERT INTO software (cveid, cpeEntryId, previousVersion) VALUES (?, ?, ?)";
 175  
     /**
 176  
      * SQL Statement to insert a new cpe.
 177  
      */
 178  
     private static final String INSERT_CPE = "INSERT INTO cpeEntry (cpe, vendor, product) VALUES (?, ?, ?)";
 179  
     /**
 180  
      * SQL Statement to get a CPEProductID.
 181  
      */
 182  
     private static final String SELECT_CPE_ID = "SELECT id FROM cpeEntry WHERE cpe = ?";
 183  
     /**
 184  
      * SQL Statement to insert a new vulnerability.
 185  
      */
 186  
     private static final String INSERT_VULNERABILITY = "INSERT INTO vulnerability (cve, description, cwe, cvssScore, cvssAccessVector, "
 187  
             + "cvssAccessComplexity, cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact) "
 188  
             + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
 189  
     /**
 190  
      * SQL Statement to update a vulnerability.
 191  
      */
 192  
     private static final String UPDATE_VULNERABILITY = "UPDATE vulnerability SET description=?, cwe=?, cvssScore=?, cvssAccessVector=?, "
 193  
             + "cvssAccessComplexity=?, cvssAuthentication=?, cvssConfidentialityImpact=?, cvssIntegrityImpact=?, cvssAvailabilityImpact=? "
 194  
             + "WHERE id=?";
 195  
     /**
 196  
      * SQL Statement to find CVE entries based on CPE data.
 197  
      */
 198  
     private static final String SELECT_CVE_FROM_SOFTWARE = "SELECT cve, cpe, previousVersion "
 199  
             + "FROM software INNER JOIN vulnerability ON vulnerability.id = software.cveId "
 200  
             + "INNER JOIN cpeEntry ON cpeEntry.id = software.cpeEntryId "
 201  
             + "WHERE vendor = ? AND product = ?";
 202  
     //unfortunately, the version info is too complicated to do in a select. Need to filter this afterwards
 203  
     //        + " AND (version = '-' OR previousVersion IS NOT NULL OR version=?)";
 204  
     //
 205  
     /**
 206  
      * SQL Statement to find the CPE entry based on the vendor and product.
 207  
      */
 208  
     private static final String SELECT_CPE_ENTRIES = "SELECT cpe FROM cpeEntry WHERE vendor = ? AND product = ?";
 209  
     /**
 210  
      * SQL Statement to select references by CVEID.
 211  
      */
 212  
     private static final String SELECT_REFERENCE = "SELECT source, name, url FROM reference WHERE cveid = ?";
 213  
     /**
 214  
      * SQL Statement to select vendor and product for lucene index.
 215  
      */
 216  
     private static final String SELECT_VENDOR_PRODUCT_LIST = "SELECT vendor, product FROM cpeEntry GROUP BY vendor, product";
 217  
     /**
 218  
      * SQL Statement to select software by CVEID.
 219  
      */
 220  
     private static final String SELECT_SOFTWARE = "SELECT cpe, previousVersion "
 221  
             + "FROM software INNER JOIN cpeEntry ON software.cpeEntryId = cpeEntry.id WHERE cveid = ?";
 222  
 //    public static final String SELECT_SOFTWARE = "SELECT part, vendor, product, version, revision, previousVersion "
 223  
 //            + "FROM software INNER JOIN cpeProduct ON cpeProduct.id = software.cpeProductId LEFT JOIN cpeVersion ON "
 224  
 //            + "software.cpeVersionId = cpeVersion.id LEFT JOIN Version ON cpeVersion.versionId = version.id WHERE cveid = ?";
 225  
     /**
 226  
      * SQL Statement to select a vulnerability by CVEID.
 227  
      */
 228  
     private static final String SELECT_VULNERABILITY = "SELECT id, description, cwe, cvssScore, cvssAccessVector, cvssAccessComplexity, "
 229  
             + "cvssAuthentication, cvssConfidentialityImpact, cvssIntegrityImpact, cvssAvailabilityImpact FROM vulnerability WHERE cve = ?";
 230  
     /**
 231  
      * SQL Statement to select a vulnerability's primary key.
 232  
      */
 233  
     private static final String SELECT_VULNERABILITY_ID = "SELECT id FROM vulnerability WHERE cve = ?";
 234  
     /**
 235  
      * SQL Statement to retrieve the properties from the database.
 236  
      */
 237  
     private static final String SELECT_PROPERTIES = "SELECT id, value FROM properties";
 238  
     /**
 239  
      * SQL Statement to retrieve a property from the database.
 240  
      */
 241  
     private static final String SELECT_PROPERTY = "SELECT id, value FROM properties WHERE id = ?";
 242  
     /**
 243  
      * SQL Statement to insert a new property.
 244  
      */
 245  
     private static final String INSERT_PROPERTY = "INSERT INTO properties (id, value) VALUES (?, ?)";
 246  
     /**
 247  
      * SQL Statement to update a property.
 248  
      */
 249  
     private static final String UPDATE_PROPERTY = "UPDATE properties SET value = ? WHERE id = ?";
 250  
     /**
 251  
      * SQL Statement to delete a property.
 252  
      */
 253  
     private static final String DELETE_PROPERTY = "DELETE FROM properties WHERE id = ?";
 254  
 
 255  
     //</editor-fold>
 256  
     /**
 257  
      * Searches the CPE entries in the database and retrieves all entries for a given vendor and product combination.
 258  
      * The returned list will include all versions of the product that are registered in the NVD CVE data.
 259  
      *
 260  
      * @param vendor the identified vendor name of the dependency being analyzed
 261  
      * @param product the identified name of the product of the dependency being analyzed
 262  
      * @return a set of vulnerable software
 263  
      */
 264  
     public Set<VulnerableSoftware> getCPEs(String vendor, String product) {
 265  72
         final Set<VulnerableSoftware> cpe = new HashSet<VulnerableSoftware>();
 266  72
         ResultSet rs = null;
 267  72
         PreparedStatement ps = null;
 268  
         try {
 269  72
             ps = getConnection().prepareStatement(SELECT_CPE_ENTRIES);
 270  72
             ps.setString(1, vendor);
 271  72
             ps.setString(2, product);
 272  72
             rs = ps.executeQuery();
 273  
 
 274  4462
             while (rs.next()) {
 275  4390
                 final VulnerableSoftware vs = new VulnerableSoftware();
 276  4390
                 vs.setCpe(rs.getString(1));
 277  4390
                 cpe.add(vs);
 278  4390
             }
 279  0
         } catch (SQLException ex) {
 280  0
             final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
 281  0
             Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, msg);
 282  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 283  
         } finally {
 284  72
             DBUtils.closeResultSet(rs);
 285  72
             DBUtils.closeStatement(ps);
 286  72
         }
 287  72
         return cpe;
 288  
     }
 289  
 
 290  
     /**
 291  
      * Returns the entire list of vendor/product combinations.
 292  
      *
 293  
      * @return the entire list of vendor/product combinations.
 294  
      */
 295  
     public ResultSet getVendorProductList() {
 296  11
         ResultSet rs = null;
 297  
         try {
 298  11
             final PreparedStatement ps = getConnection().prepareStatement(SELECT_VENDOR_PRODUCT_LIST);
 299  11
             rs = ps.executeQuery();
 300  0
         } catch (SQLException ex) {
 301  0
             final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
 302  0
             Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, msg);
 303  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 304  11
         } // can't close the statement in the PS as the resultset is returned, closing PS would close the resultset
 305  11
         return rs;
 306  
     }
 307  
 
 308  
     /**
 309  
      * Returns a set of properties.
 310  
      *
 311  
      * @return the properties from the database
 312  
      */
 313  
     Properties getProperties() {
 314  24
         final Properties prop = new Properties();
 315  24
         PreparedStatement ps = null;
 316  24
         ResultSet rs = null;
 317  
         try {
 318  24
             ps = getConnection().prepareStatement(SELECT_PROPERTIES);
 319  24
             rs = ps.executeQuery();
 320  390
             while (rs.next()) {
 321  366
                 prop.setProperty(rs.getString(1), rs.getString(2));
 322  
             }
 323  0
         } catch (SQLException ex) {
 324  0
             final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
 325  0
             Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, msg);
 326  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 327  
         } finally {
 328  24
             DBUtils.closeStatement(ps);
 329  24
             DBUtils.closeResultSet(rs);
 330  24
         }
 331  24
         return prop;
 332  
     }
 333  
 
 334  
     /**
 335  
      * Saves a set of properties to the database.
 336  
      *
 337  
      * @param props a collection of properties
 338  
      */
 339  
     void saveProperties(Properties props) {
 340  0
         PreparedStatement updateProperty = null;
 341  0
         PreparedStatement insertProperty = null;
 342  
         try {
 343  
             try {
 344  0
                 updateProperty = getConnection().prepareStatement(UPDATE_PROPERTY);
 345  0
                 insertProperty = getConnection().prepareStatement(INSERT_PROPERTY);
 346  0
             } catch (SQLException ex) {
 347  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.WARNING, "Unable to save properties to the database");
 348  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Unable to save properties to the database", ex);
 349  
                 return;
 350  0
             }
 351  0
             for (Entry<Object, Object> entry : props.entrySet()) {
 352  0
                 final String key = entry.getKey().toString();
 353  0
                 final String value = entry.getValue().toString();
 354  
                 try {
 355  0
                     updateProperty.setString(1, value);
 356  0
                     updateProperty.setString(2, key);
 357  0
                     if (updateProperty.executeUpdate() == 0) {
 358  0
                         insertProperty.setString(1, key);
 359  0
                         insertProperty.setString(2, value);
 360  
                     }
 361  0
                 } catch (SQLException ex) {
 362  0
                     final String msg = String.format("Unable to save property '%s' with a value of '%s' to the database", key, value);
 363  0
                     Logger.getLogger(CveDB.class.getName()).log(Level.WARNING, msg);
 364  0
                     Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 365  0
                 }
 366  0
             }
 367  
         } finally {
 368  0
             DBUtils.closeStatement(updateProperty);
 369  0
             DBUtils.closeStatement(insertProperty);
 370  0
         }
 371  0
     }
 372  
 
 373  
     /**
 374  
      * Saves a property to the database.
 375  
      *
 376  
      * @param key the property key
 377  
      * @param value the property value
 378  
      */
 379  
     void saveProperty(String key, String value) {
 380  1
         PreparedStatement updateProperty = null;
 381  1
         PreparedStatement insertProperty = null;
 382  
         try {
 383  
             try {
 384  1
                 updateProperty = getConnection().prepareStatement(UPDATE_PROPERTY);
 385  0
             } catch (SQLException ex) {
 386  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.WARNING, "Unable to save properties to the database");
 387  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Unable to save properties to the database", ex);
 388  
                 return;
 389  1
             }
 390  
             try {
 391  1
                 updateProperty.setString(1, value);
 392  1
                 updateProperty.setString(2, key);
 393  1
                 if (updateProperty.executeUpdate() == 0) {
 394  
                     try {
 395  1
                         insertProperty = getConnection().prepareStatement(INSERT_PROPERTY);
 396  0
                     } catch (SQLException ex) {
 397  0
                         Logger.getLogger(CveDB.class.getName()).log(Level.WARNING, "Unable to save properties to the database");
 398  0
                         Logger.getLogger(CveDB.class.getName()).log(Level.FINE, "Unable to save properties to the database", ex);
 399  
                         return;
 400  1
                     }
 401  1
                     insertProperty.setString(1, key);
 402  1
                     insertProperty.setString(2, value);
 403  1
                     insertProperty.execute();
 404  
                 }
 405  0
             } catch (SQLException ex) {
 406  0
                 final String msg = String.format("Unable to save property '%s' with a value of '%s' to the database", key, value);
 407  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.WARNING, msg);
 408  0
                 Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 409  1
             }
 410  
         } finally {
 411  1
             DBUtils.closeStatement(updateProperty);
 412  1
             DBUtils.closeStatement(insertProperty);
 413  1
         }
 414  1
     }
 415  
 
 416  
     /**
 417  
      * Retrieves the vulnerabilities associated with the specified CPE.
 418  
      *
 419  
      * @param cpeStr the CPE name
 420  
      * @return a list of Vulnerabilities
 421  
      * @throws DatabaseException thrown if there is an exception retrieving data
 422  
      */
 423  
     public List<Vulnerability> getVulnerabilities(String cpeStr) throws DatabaseException {
 424  12
         ResultSet rs = null;
 425  12
         final VulnerableSoftware cpe = new VulnerableSoftware();
 426  
         try {
 427  12
             cpe.parseName(cpeStr);
 428  0
         } catch (UnsupportedEncodingException ex) {
 429  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINEST, null, ex);
 430  12
         }
 431  12
         final DependencyVersion detectedVersion = parseDependencyVersion(cpe);
 432  12
         final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>();
 433  
 
 434  
         PreparedStatement ps;
 435  12
         final HashSet<String> cveEntries = new HashSet<String>();
 436  
         try {
 437  12
             ps = getConnection().prepareStatement(SELECT_CVE_FROM_SOFTWARE);
 438  12
             ps.setString(1, cpe.getVendor());
 439  12
             ps.setString(2, cpe.getProduct());
 440  12
             rs = ps.executeQuery();
 441  4591
             while (rs.next()) {
 442  4579
                 final String cveId = rs.getString(1);
 443  4579
                 final String cpeId = rs.getString(2);
 444  4579
                 final String previous = rs.getString(3);
 445  4579
                 if (!cveEntries.contains(cveId) && isAffected(cpe.getVendor(), cpe.getProduct(), detectedVersion, cpeId, previous)) {
 446  61
                     cveEntries.add(cveId);
 447  
                 }
 448  4579
             }
 449  12
             DBUtils.closeResultSet(rs);
 450  12
             DBUtils.closeStatement(ps);
 451  12
             for (String cve : cveEntries) {
 452  61
                 final Vulnerability v = getVulnerability(cve);
 453  61
                 vulnerabilities.add(v);
 454  61
             }
 455  
 
 456  0
         } catch (SQLException ex) {
 457  0
             throw new DatabaseException("Exception retrieving vulnerability for " + cpeStr, ex);
 458  
         } finally {
 459  12
             DBUtils.closeResultSet(rs);
 460  12
         }
 461  12
         return vulnerabilities;
 462  
     }
 463  
 
 464  
     /**
 465  
      * Gets a vulnerability for the provided CVE.
 466  
      *
 467  
      * @param cve the CVE to lookup
 468  
      * @return a vulnerability object
 469  
      * @throws DatabaseException if an exception occurs
 470  
      */
 471  
     private Vulnerability getVulnerability(String cve) throws DatabaseException {
 472  61
         PreparedStatement psV = null;
 473  61
         PreparedStatement psR = null;
 474  61
         PreparedStatement psS = null;
 475  61
         ResultSet rsV = null;
 476  61
         ResultSet rsR = null;
 477  61
         ResultSet rsS = null;
 478  61
         Vulnerability vuln = null;
 479  
         try {
 480  61
             psV = getConnection().prepareStatement(SELECT_VULNERABILITY);
 481  61
             psV.setString(1, cve);
 482  61
             rsV = psV.executeQuery();
 483  61
             if (rsV.next()) {
 484  61
                 vuln = new Vulnerability();
 485  61
                 vuln.setName(cve);
 486  61
                 vuln.setDescription(rsV.getString(2));
 487  61
                 String cwe = rsV.getString(3);
 488  61
                 if (cwe != null) {
 489  50
                     final String name = CweDB.getCweName(cwe);
 490  50
                     if (name != null) {
 491  48
                         cwe += " " + name;
 492  
                     }
 493  
                 }
 494  61
                 final int cveId = rsV.getInt(1);
 495  61
                 vuln.setCwe(cwe);
 496  61
                 vuln.setCvssScore(rsV.getFloat(4));
 497  61
                 vuln.setCvssAccessVector(rsV.getString(5));
 498  61
                 vuln.setCvssAccessComplexity(rsV.getString(6));
 499  61
                 vuln.setCvssAuthentication(rsV.getString(7));
 500  61
                 vuln.setCvssConfidentialityImpact(rsV.getString(8));
 501  61
                 vuln.setCvssIntegrityImpact(rsV.getString(9));
 502  61
                 vuln.setCvssAvailabilityImpact(rsV.getString(10));
 503  
 
 504  61
                 psR = getConnection().prepareStatement(SELECT_REFERENCE);
 505  61
                 psR.setInt(1, cveId);
 506  61
                 rsR = psR.executeQuery();
 507  477
                 while (rsR.next()) {
 508  416
                     vuln.addReference(rsR.getString(1), rsR.getString(2), rsR.getString(3));
 509  
                 }
 510  61
                 psS = getConnection().prepareStatement(SELECT_SOFTWARE);
 511  61
                 psS.setInt(1, cveId);
 512  61
                 rsS = psS.executeQuery();
 513  2765
                 while (rsS.next()) {
 514  2704
                     final String cpe = rsS.getString(1);
 515  2704
                     final String prevVersion = rsS.getString(2);
 516  2704
                     if (prevVersion == null) {
 517  2662
                         vuln.addVulnerableSoftware(cpe);
 518  
                     } else {
 519  42
                         vuln.addVulnerableSoftware(cpe, prevVersion);
 520  
                     }
 521  2704
                 }
 522  
             }
 523  0
         } catch (SQLException ex) {
 524  0
             throw new DatabaseException("Error retrieving " + cve, ex);
 525  
         } finally {
 526  61
             DBUtils.closeResultSet(rsV);
 527  61
             DBUtils.closeResultSet(rsR);
 528  61
             DBUtils.closeResultSet(rsS);
 529  61
             DBUtils.closeStatement(psV);
 530  61
             DBUtils.closeStatement(psR);
 531  61
             DBUtils.closeStatement(psS);
 532  61
         }
 533  61
         return vuln;
 534  
     }
 535  
 
 536  
     /**
 537  
      * Updates the vulnerability within the database. If the vulnerability does not exist it will be added.
 538  
      *
 539  
      * @param vuln the vulnerability to add to the database
 540  
      * @throws DatabaseException is thrown if the database
 541  
      */
 542  
     public void updateVulnerability(Vulnerability vuln) throws DatabaseException {
 543  0
         PreparedStatement selectVulnerabilityId = null;
 544  0
         PreparedStatement deleteVulnerability = null;
 545  0
         PreparedStatement deleteReferences = null;
 546  0
         PreparedStatement deleteSoftware = null;
 547  0
         PreparedStatement updateVulnerability = null;
 548  0
         PreparedStatement insertVulnerability = null;
 549  0
         PreparedStatement insertReference = null;
 550  0
         PreparedStatement selectCpeId = null;
 551  0
         PreparedStatement insertCpe = null;
 552  0
         PreparedStatement insertSoftware = null;
 553  
 
 554  
         try {
 555  0
             selectVulnerabilityId = getConnection().prepareStatement(SELECT_VULNERABILITY_ID);
 556  0
             deleteVulnerability = getConnection().prepareStatement(DELETE_VULNERABILITY);
 557  0
             deleteReferences = getConnection().prepareStatement(DELETE_REFERENCE);
 558  0
             deleteSoftware = getConnection().prepareStatement(DELETE_SOFTWARE);
 559  0
             updateVulnerability = getConnection().prepareStatement(UPDATE_VULNERABILITY);
 560  0
             insertVulnerability = getConnection().prepareStatement(INSERT_VULNERABILITY, Statement.RETURN_GENERATED_KEYS);
 561  0
             insertReference = getConnection().prepareStatement(INSERT_REFERENCE);
 562  0
             selectCpeId = getConnection().prepareStatement(SELECT_CPE_ID);
 563  0
             insertCpe = getConnection().prepareStatement(INSERT_CPE, Statement.RETURN_GENERATED_KEYS);
 564  0
             insertSoftware = getConnection().prepareStatement(INSERT_SOFTWARE);
 565  0
             int vulnerabilityId = 0;
 566  0
             selectVulnerabilityId.setString(1, vuln.getName());
 567  0
             ResultSet rs = selectVulnerabilityId.executeQuery();
 568  0
             if (rs.next()) {
 569  0
                 vulnerabilityId = rs.getInt(1);
 570  
                 // first delete any existing vulnerability info. We don't know what was updated. yes, slower but atm easier.
 571  0
                 deleteReferences.setInt(1, vulnerabilityId);
 572  0
                 deleteReferences.execute();
 573  0
                 deleteSoftware.setInt(1, vulnerabilityId);
 574  0
                 deleteSoftware.execute();
 575  
             }
 576  0
             DBUtils.closeResultSet(rs);
 577  0
             rs = null;
 578  0
             if (vulnerabilityId != 0) {
 579  0
                 if (vuln.getDescription().contains("** REJECT **")) {
 580  0
                     deleteVulnerability.setInt(1, vulnerabilityId);
 581  0
                     deleteVulnerability.executeUpdate();
 582  
                 } else {
 583  0
                     updateVulnerability.setString(1, vuln.getDescription());
 584  0
                     updateVulnerability.setString(2, vuln.getCwe());
 585  0
                     updateVulnerability.setFloat(3, vuln.getCvssScore());
 586  0
                     updateVulnerability.setString(4, vuln.getCvssAccessVector());
 587  0
                     updateVulnerability.setString(5, vuln.getCvssAccessComplexity());
 588  0
                     updateVulnerability.setString(6, vuln.getCvssAuthentication());
 589  0
                     updateVulnerability.setString(7, vuln.getCvssConfidentialityImpact());
 590  0
                     updateVulnerability.setString(8, vuln.getCvssIntegrityImpact());
 591  0
                     updateVulnerability.setString(9, vuln.getCvssAvailabilityImpact());
 592  0
                     updateVulnerability.setInt(10, vulnerabilityId);
 593  0
                     updateVulnerability.executeUpdate();
 594  
                 }
 595  
             } else {
 596  0
                 insertVulnerability.setString(1, vuln.getName());
 597  0
                 insertVulnerability.setString(2, vuln.getDescription());
 598  0
                 insertVulnerability.setString(3, vuln.getCwe());
 599  0
                 insertVulnerability.setFloat(4, vuln.getCvssScore());
 600  0
                 insertVulnerability.setString(5, vuln.getCvssAccessVector());
 601  0
                 insertVulnerability.setString(6, vuln.getCvssAccessComplexity());
 602  0
                 insertVulnerability.setString(7, vuln.getCvssAuthentication());
 603  0
                 insertVulnerability.setString(8, vuln.getCvssConfidentialityImpact());
 604  0
                 insertVulnerability.setString(9, vuln.getCvssIntegrityImpact());
 605  0
                 insertVulnerability.setString(10, vuln.getCvssAvailabilityImpact());
 606  0
                 insertVulnerability.execute();
 607  
                 try {
 608  0
                     rs = insertVulnerability.getGeneratedKeys();
 609  0
                     rs.next();
 610  0
                     vulnerabilityId = rs.getInt(1);
 611  0
                 } catch (SQLException ex) {
 612  0
                     final String msg = String.format("Unable to retrieve id for new vulnerability for '%s'", vuln.getName());
 613  0
                     throw new DatabaseException(msg, ex);
 614  
                 } finally {
 615  0
                     DBUtils.closeResultSet(rs);
 616  0
                     rs = null;
 617  0
                 }
 618  
             }
 619  0
             insertReference.setInt(1, vulnerabilityId);
 620  0
             for (Reference r : vuln.getReferences()) {
 621  0
                 insertReference.setString(2, r.getName());
 622  0
                 insertReference.setString(3, r.getUrl());
 623  0
                 insertReference.setString(4, r.getSource());
 624  0
                 insertReference.execute();
 625  0
             }
 626  0
             for (VulnerableSoftware s : vuln.getVulnerableSoftware()) {
 627  0
                 int cpeProductId = 0;
 628  0
                 selectCpeId.setString(1, s.getName());
 629  
                 try {
 630  0
                     rs = selectCpeId.executeQuery();
 631  0
                     if (rs.next()) {
 632  0
                         cpeProductId = rs.getInt(1);
 633  
                     }
 634  0
                 } catch (SQLException ex) {
 635  0
                     throw new DatabaseException("Unable to get primary key for new cpe: " + s.getName(), ex);
 636  
                 } finally {
 637  0
                     DBUtils.closeResultSet(rs);
 638  0
                     rs = null;
 639  0
                 }
 640  
 
 641  0
                 if (cpeProductId == 0) {
 642  0
                     insertCpe.setString(1, s.getName());
 643  0
                     insertCpe.setString(2, s.getVendor());
 644  0
                     insertCpe.setString(3, s.getProduct());
 645  0
                     insertCpe.executeUpdate();
 646  0
                     cpeProductId = DBUtils.getGeneratedKey(insertCpe);
 647  
                 }
 648  0
                 if (cpeProductId == 0) {
 649  0
                     throw new DatabaseException("Unable to retrieve cpeProductId - no data returned");
 650  
                 }
 651  
 
 652  0
                 insertSoftware.setInt(1, vulnerabilityId);
 653  0
                 insertSoftware.setInt(2, cpeProductId);
 654  0
                 if (s.getPreviousVersion() == null) {
 655  0
                     insertSoftware.setNull(3, java.sql.Types.VARCHAR);
 656  
                 } else {
 657  0
                     insertSoftware.setString(3, s.getPreviousVersion());
 658  
                 }
 659  0
                 insertSoftware.execute();
 660  0
             }
 661  
 
 662  0
         } catch (SQLException ex) {
 663  0
             final String msg = String.format("Error updating '%s'", vuln.getName());
 664  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 665  0
             throw new DatabaseException(msg, ex);
 666  
         } finally {
 667  0
             DBUtils.closeStatement(selectVulnerabilityId);
 668  0
             DBUtils.closeStatement(deleteReferences);
 669  0
             DBUtils.closeStatement(deleteSoftware);
 670  0
             DBUtils.closeStatement(updateVulnerability);
 671  0
             DBUtils.closeStatement(deleteVulnerability);
 672  0
             DBUtils.closeStatement(insertVulnerability);
 673  0
             DBUtils.closeStatement(insertReference);
 674  0
             DBUtils.closeStatement(selectCpeId);
 675  0
             DBUtils.closeStatement(insertCpe);
 676  0
             DBUtils.closeStatement(insertSoftware);
 677  0
         }
 678  0
     }
 679  
 
 680  
     /**
 681  
      * It is possible that orphaned rows may be generated during database updates. This should be called after all
 682  
      * updates have been completed to ensure orphan entries are removed.
 683  
      */
 684  
     public void cleanupDatabase() {
 685  0
         PreparedStatement ps = null;
 686  
         try {
 687  0
             ps = getConnection().prepareStatement(CLEANUP_ORPHANS);
 688  0
             if (ps != null) {
 689  0
                 ps.executeUpdate();
 690  
             }
 691  0
         } catch (SQLException ex) {
 692  0
             final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details.";
 693  0
             Logger.getLogger(CveDB.class.getName()).log(Level.SEVERE, msg);
 694  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINE, null, ex);
 695  
         } finally {
 696  0
             DBUtils.closeStatement(ps);
 697  0
         }
 698  0
     }
 699  
 
 700  
     /**
 701  
      * Determines if the given identifiedVersion is affected by the given cpeId and previous version flag. A non-null,
 702  
      * non-empty string passed to the previous version argument indicates that all previous versions are affected.
 703  
      *
 704  
      * @param vendor the vendor of the dependency being analyzed
 705  
      * @param product the product name of the dependency being analyzed
 706  
      * @param identifiedVersion the identified version of the dependency being analyzed
 707  
      * @param cpeId the cpe identifier of software that has a known vulnerability
 708  
      * @param previous a flag indicating if previous versions of the product are vulnerable
 709  
      * @return true if the identified version is affected, otherwise false
 710  
      */
 711  
     private boolean isAffected(String vendor, String product, DependencyVersion identifiedVersion, String cpeId, String previous) {
 712  3532
         boolean affected = false;
 713  3532
         final boolean isStruts = "apache".equals(vendor) && "struts".equals(product);
 714  3532
         final DependencyVersion v = parseDependencyVersion(cpeId);
 715  3532
         final boolean prevAffected = previous != null && !previous.isEmpty();
 716  3532
         if (identifiedVersion == null || "-".equals(identifiedVersion.toString())) {
 717  96
             if (v == null || "-".equals(v.toString())) {
 718  0
                 affected = true;
 719  
             }
 720  3436
         } else if (identifiedVersion.equals(v) || (prevAffected && identifiedVersion.compareTo(v) < 0)) {
 721  83
             if (isStruts) { //struts 2 vulns don't affect struts 1
 722  72
                 if (identifiedVersion.getVersionParts().get(0).equals(v.getVersionParts().get(0))) {
 723  50
                     affected = true;
 724  
                 }
 725  
             } else {
 726  11
                 affected = true;
 727  
             }
 728  
         }
 729  
         /*
 730  
          * TODO consider utilizing the matchThreeVersion method to get additional results. However, this
 731  
          *      might also introduce false positives.
 732  
          */
 733  3532
         return affected;
 734  
     }
 735  
 
 736  
     /**
 737  
      * Parses the version (including revision) from a CPE identifier. If no version is identified then a '-' is
 738  
      * returned.
 739  
      *
 740  
      * @param cpeStr a cpe identifier
 741  
      * @return a dependency version
 742  
      */
 743  
     private DependencyVersion parseDependencyVersion(String cpeStr) {
 744  3532
         final VulnerableSoftware cpe = new VulnerableSoftware();
 745  
         try {
 746  3532
             cpe.parseName(cpeStr);
 747  0
         } catch (UnsupportedEncodingException ex) {
 748  
             //never going to happen.
 749  0
             Logger.getLogger(CveDB.class.getName()).log(Level.FINEST, null, ex);
 750  3532
         }
 751  3532
         return parseDependencyVersion(cpe);
 752  
     }
 753  
 
 754  
     /**
 755  
      * Takes a CPE and parses out the version number. If no version is identified then a '-' is returned.
 756  
      *
 757  
      * @param cpe a cpe object
 758  
      * @return a dependency version
 759  
      */
 760  
     private DependencyVersion parseDependencyVersion(VulnerableSoftware cpe) {
 761  
         DependencyVersion cpeVersion;
 762  3544
         if (cpe.getVersion() != null && cpe.getVersion().length() > 0) {
 763  
             String versionText;
 764  3540
             if (cpe.getRevision() != null && cpe.getRevision().length() > 0) {
 765  441
                 versionText = String.format("%s.%s", cpe.getVersion(), cpe.getRevision());
 766  
             } else {
 767  3099
                 versionText = cpe.getVersion();
 768  
             }
 769  3540
             cpeVersion = DependencyVersionUtil.parseVersion(versionText);
 770  3540
         } else {
 771  4
             cpeVersion = new DependencyVersion("-");
 772  
         }
 773  3544
         return cpeVersion;
 774  
     }
 775  
 }