View Javadoc
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) 2014 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.data.nvdcve;
19  
20  import com.google.common.io.Resources;
21  import org.apache.commons.dbcp2.BasicDataSource;
22  import org.apache.commons.io.IOUtils;
23  import org.owasp.dependencycheck.utils.DBUtils;
24  import org.owasp.dependencycheck.utils.DependencyVersion;
25  import org.owasp.dependencycheck.utils.DependencyVersionUtil;
26  import org.owasp.dependencycheck.utils.FileUtils;
27  import org.owasp.dependencycheck.utils.Settings;
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  
31  import javax.annotation.concurrent.ThreadSafe;
32  import java.io.File;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.net.URL;
36  import java.nio.charset.StandardCharsets;
37  import java.sql.Connection;
38  import java.sql.Driver;
39  import java.sql.DriverManager;
40  import java.sql.PreparedStatement;
41  import java.sql.ResultSet;
42  import java.sql.SQLException;
43  import java.sql.Statement;
44  import java.util.Locale;
45  import java.util.ResourceBundle;
46  
47  /**
48   * Loads the configured database driver and returns the database connection. If
49   * the embedded H2 database is used obtaining a connection will ensure the
50   * database file exists and that the appropriate table structure has been
51   * created.
52   *
53   * @author Jeremy Long
54   */
55  @ThreadSafe
56  public final class DatabaseManager {
57  
58      /**
59       * The Logger.
60       */
61      private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseManager.class);
62      /**
63       * Resource location for SQL file used to create the database schema.
64       */
65      public static final String DB_STRUCTURE_RESOURCE = "data/initialize.sql";
66      /**
67       * Resource location for SQL file used to create the database schema.
68       */
69      public static final String DB_STRUCTURE_UPDATE_RESOURCE = "data/upgrade_%s.sql";
70      /**
71       * The URL that discusses upgrading non-H2 databases.
72       */
73      public static final String UPGRADE_HELP_URL = "https://dependency-check.github.io/DependencyCheck/data/upgrade.html";
74      /**
75       * The database driver used to connect to the database.
76       */
77      private Driver driver = null;
78      /**
79       * The database connection string.
80       */
81      private String connectionString = null;
82      /**
83       * The username to connect to the database.
84       */
85      private String userName = null;
86      /**
87       * The password for the database.
88       */
89      private String password = null;
90      /**
91       * Counter to ensure that calls to ensureSchemaVersion does not end up in an
92       * endless loop.
93       */
94      private int callDepth = 0;
95      /**
96       * The configured settings.
97       */
98      private final Settings settings;
99      /**
100      * Flag indicating if the database connection is for an H2 database.
101      */
102     private boolean isH2;
103     /**
104      * Flag indicating if the database connection is for an Oracle database.
105      */
106     private boolean isOracle;
107     /**
108      * The database product name.
109      */
110     private String databaseProductName;
111     /**
112      * The database connection pool.
113      */
114     private BasicDataSource connectionPool;
115 
116     /**
117      * Private constructor for this factory class; no instance is ever needed.
118      *
119      * @param settings the configured settings
120      * @throws DatabaseException thrown if we are unable to connect to the
121      * database
122      */
123     public DatabaseManager(Settings settings) throws DatabaseException {
124         this.settings = settings;
125         initialize();
126     }
127 
128     /**
129      * Initializes the connection factory. Ensuring that the appropriate drivers
130      * are loaded and that a connection can be made successfully.
131      *
132      * @throws DatabaseException thrown if we are unable to connect to the
133      * database
134      */
135     private void initialize() throws DatabaseException {
136         final boolean autoUpdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true);
137         Connection conn = null;
138         try {
139             //load the driver if necessary
140             final String driverName = settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
141             if (!driverName.isEmpty()) {
142                 final String driverPath = settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
143                 LOGGER.debug("Loading driver '{}'", driverName);
144                 try {
145                     if (!driverPath.isEmpty()) {
146                         LOGGER.debug("Loading driver from: {}", driverPath);
147                         driver = DriverLoader.load(driverName, driverPath);
148                     } else {
149                         driver = DriverLoader.load(driverName);
150                     }
151                 } catch (DriverLoadException ex) {
152                     LOGGER.debug("Unable to load database driver", ex);
153                     throw new DatabaseException("Unable to load database driver", ex);
154                 }
155             }
156             userName = settings.getString(Settings.KEYS.DB_USER, "dcuser");
157             //yes, yes - hard-coded password - only if there isn't one in the properties file.
158             password = settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
159             try {
160                 connectionString = settings.getConnectionString(
161                         Settings.KEYS.DB_CONNECTION_STRING,
162                         Settings.KEYS.DB_FILE_NAME);
163             } catch (IOException ex) {
164                 LOGGER.debug("Unable to retrieve the database connection string", ex);
165                 throw new DatabaseException("Unable to retrieve the database connection string", ex);
166             }
167             isH2 = isH2Connection(connectionString);
168             boolean shouldCreateSchema = false;
169             try {
170                 if (autoUpdate && isH2) {
171                     shouldCreateSchema = !h2DataFileExists();
172                     LOGGER.debug("Need to create DB Structure: {}", shouldCreateSchema);
173                 }
174             } catch (IOException ioex) {
175                 LOGGER.debug("Unable to verify database exists", ioex);
176                 throw new DatabaseException("Unable to verify database exists", ioex);
177             }
178             LOGGER.debug("Loading database connection");
179             LOGGER.debug("Connection String: {}", connectionString);
180             LOGGER.debug("Database User: {}", userName);
181 
182             try {
183                 if (connectionString.toLowerCase().contains("integrated security=true")
184                         || connectionString.toLowerCase().contains("trusted_connection=true")) {
185                     conn = DriverManager.getConnection(connectionString);
186                 } else {
187                     conn = DriverManager.getConnection(connectionString, userName, password);
188                 }
189             } catch (SQLException ex) {
190                 if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
191                     connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
192                     try {
193                         conn = DriverManager.getConnection(connectionString, userName, password);
194                         settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
195                         LOGGER.debug("Unable to start the database in server mode; reverting to single user mode");
196                     } catch (SQLException sqlex) {
197                         LOGGER.debug("Unable to connect to the database", ex);
198                         throw new DatabaseException("Unable to connect to the database", ex);
199                     }
200                 } else if (isH2 && ex.getMessage().contains("file version or invalid file header")) {
201                     LOGGER.error("Incompatible or corrupt database found. To resolve this issue please remove the existing "
202                             + "database by running purge");
203                     throw new DatabaseException("Incompatible or corrupt database found; run the purge command to resolve the issue");
204                 } else {
205                     LOGGER.debug("Unable to connect to the database", ex);
206                     throw new DatabaseException("Unable to connect to the database", ex);
207                 }
208             }
209             databaseProductName = determineDatabaseProductName(conn);
210             isOracle = "oracle".equals(databaseProductName);
211             if (shouldCreateSchema) {
212                 try {
213                     createTables(conn);
214                 } catch (DatabaseException dex) {
215                     LOGGER.debug("", dex);
216                     throw new DatabaseException("Unable to create the database structure", dex);
217                 }
218             }
219             try {
220                 ensureSchemaVersion(conn);
221             } catch (DatabaseException dex) {
222                 LOGGER.debug("", dex);
223                 throw new DatabaseException("Database schema does not match this version of dependency-check", dex);
224             }
225         } finally {
226             if (conn != null) {
227                 try {
228                     conn.close();
229                 } catch (SQLException ex) {
230                     LOGGER.debug("An error occurred closing the connection", ex);
231                 }
232             }
233         }
234     }
235 
236     /**
237      * Tries to determine the product name of the database.
238      *
239      * @param conn the database connection
240      * @return the product name of the database if successful, {@code null} else
241      */
242     private String determineDatabaseProductName(Connection conn) {
243         try {
244             final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
245             LOGGER.debug("Database product: {}", databaseProductName);
246             return databaseProductName;
247         } catch (SQLException se) {
248             LOGGER.warn("Problem determining database product!", se);
249             return null;
250         }
251     }
252 
253     /**
254      * Cleans up resources and unloads any registered database drivers. This
255      * needs to be called to ensure the driver is unregistered prior to the
256      * finalize method being called as during shutdown the class loader used to
257      * load the driver may be unloaded prior to the driver being de-registered.
258      */
259     public void cleanup() {
260         if (driver != null) {
261             DriverLoader.cleanup(driver);
262             driver = null;
263         }
264         connectionString = null;
265         userName = null;
266         password = null;
267     }
268 
269     /**
270      * Determines if the H2 database file exists. If it does not exist then the
271      * data structure will need to be created.
272      *
273      * @return true if the H2 database file does not exist; otherwise false
274      * @throws IOException thrown if the data directory does not exist and
275      * cannot be created
276      */
277     public boolean h2DataFileExists() throws IOException {
278         return h2DataFileExists(settings);
279     }
280 
281     /**
282      * Determines if the H2 database file exists. If it does not exist then the
283      * data structure will need to be created.
284      *
285      * @param configuration the configured settings
286      * @return true if the H2 database file does not exist; otherwise false
287      * @throws IOException thrown if the data directory does not exist and
288      * cannot be created
289      */
290     public static boolean h2DataFileExists(Settings configuration) throws IOException {
291         final File file = getH2DataFile(configuration);
292         return file.exists();
293     }
294 
295     /**
296      * Returns a reference to the H2 database file.
297      *
298      * @param configuration the configured settings
299      * @return the path to the H2 database file
300      * @throws IOException thrown if there is an error
301      */
302     public static File getH2DataFile(Settings configuration) throws IOException {
303         final File dir = configuration.getH2DataDirectory();
304         final String fileName = configuration.getString(Settings.KEYS.DB_FILE_NAME);
305         return new File(dir, fileName);
306     }
307 
308     /**
309      * Returns the database product name.
310      *
311      * @return the database product name
312      */
313     public String getDatabaseProductName() {
314         return databaseProductName;
315     }
316 
317     /**
318      * Determines if the connection string is for an H2 database.
319      *
320      * @return true if the connection string is for an H2 database
321      */
322     public boolean isH2Connection() {
323         return isH2;
324     }
325 
326     /**
327      * Determines if the connection string is for an Oracle database.
328      *
329      * @return true if the connection string is for an Oracle database
330      */
331     public boolean isOracle() {
332         return isOracle;
333     }
334 
335     /**
336      * Determines if the connection string is for an H2 database.
337      *
338      * @param configuration the configured settings
339      * @return true if the connection string is for an H2 database
340      */
341     public static boolean isH2Connection(Settings configuration) {
342         final String connStr;
343         try {
344             connStr = configuration.getConnectionString(
345                     Settings.KEYS.DB_CONNECTION_STRING,
346                     Settings.KEYS.DB_FILE_NAME);
347         } catch (IOException ex) {
348             LOGGER.debug("Unable to get connectionn string", ex);
349             return false;
350         }
351         return isH2Connection(connStr);
352     }
353 
354     /**
355      * Determines if the connection string is for an H2 database.
356      *
357      * @param connectionString the connection string
358      * @return true if the connection string is for an H2 database
359      */
360     public static boolean isH2Connection(String connectionString) {
361         return connectionString.startsWith("jdbc:h2:file:");
362     }
363 
364     /**
365      * Creates the database structure (tables and indexes) to store the CVE
366      * data.
367      *
368      * @param conn the database connection
369      * @throws DatabaseException thrown if there is a Database Exception
370      */
371     private void createTables(Connection conn) throws DatabaseException {
372         LOGGER.debug("Creating database structure");
373         final String dbStructure;
374         try {
375             dbStructure = getResource(DB_STRUCTURE_RESOURCE);
376 
377             Statement statement = null;
378             try {
379                 statement = conn.createStatement();
380                 statement.execute(dbStructure);
381             } catch (SQLException ex) {
382                 LOGGER.debug("", ex);
383                 throw new DatabaseException("Unable to create database statement", ex);
384             } finally {
385                 DBUtils.closeStatement(statement);
386             }
387         } catch (IOException ex) {
388             throw new DatabaseException("Unable to create database schema", ex);
389         }
390     }
391 
392     private String getResource(String resource) throws IOException {
393         String dbStructure;
394         try {
395             final URL url = Resources.getResource(resource);
396             dbStructure = Resources.toString(url, StandardCharsets.UTF_8);
397         } catch (IllegalArgumentException ex) {
398             LOGGER.debug("Resources.getResource(String) failed to find the DB Structure Resource", ex);
399             try (InputStream is = FileUtils.getResourceAsStream(resource)) {
400                 dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);
401             }
402         }
403         return dbStructure;
404     }
405 
406     /**
407      * Updates the database schema by loading the upgrade script for the version
408      * specified. The intended use is that if the current schema version is 2.9
409      * then we would call updateSchema(conn, "2.9"). This would load the
410      * upgrade_2.9.sql file and execute it against the database. The upgrade
411      * script must update the 'version' in the properties table.
412      *
413      * @param conn the database connection object
414      * @param appExpectedVersion the schema version that the application expects
415      * @param currentDbVersion the current schema version of the database
416      * @throws DatabaseException thrown if there is an exception upgrading the
417      * database schema
418      */
419     private void updateSchema(Connection conn, DependencyVersion appExpectedVersion, DependencyVersion currentDbVersion)
420             throws DatabaseException {
421 
422         if (connectionString.startsWith("jdbc:h2:file:")) {
423             LOGGER.debug("Updating database structure");
424             final String updateFile = String.format(DB_STRUCTURE_UPDATE_RESOURCE, currentDbVersion.toString());
425             if ("data/upgrade_4.2.sql".equals(updateFile) && !FileUtils.getResourceAsFile(updateFile).exists()) {
426                 throw new DatabaseException("unable to upgrade the database schema - please run the dependency-check "
427                         + "purge command to remove the existing database");
428             }
429             try {
430                 final String dbStructureUpdate = getResource(updateFile);
431                 Statement statement = null;
432                 try {
433                     statement = conn.createStatement();
434                     statement.execute(dbStructureUpdate);
435                 } catch (SQLException ex) {
436                     throw new DatabaseException(String.format("Unable to upgrade the database schema from %s to %s",
437                             currentDbVersion, appExpectedVersion.toString()), ex);
438                 } finally {
439                     DBUtils.closeStatement(statement);
440                 }
441             } catch (IllegalArgumentException | IOException ex) {
442                 final String msg = String.format("Upgrade SQL file does not exist: %s", updateFile);
443                 throw new DatabaseException(msg, ex);
444             }
445         } else {
446             final int e0 = Integer.parseInt(appExpectedVersion.getVersionParts().get(0));
447             final int c0 = Integer.parseInt(currentDbVersion.getVersionParts().get(0));
448             final int e1 = Integer.parseInt(appExpectedVersion.getVersionParts().get(1));
449             final int c1 = Integer.parseInt(currentDbVersion.getVersionParts().get(1));
450             //CSOFF: EmptyBlock
451             if (e0 == c0 && e1 < c1) {
452                 LOGGER.warn("A new version of dependency-check is available; consider upgrading");
453                 settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
454             } else if (e0 == c0 && e1 == c1) {
455                 //do nothing - not sure how we got here, but just in case...
456             } else {
457                 LOGGER.error("The database schema must be upgraded to use this version of dependency-check. Please see {} for more information.",
458                         UPGRADE_HELP_URL);
459                 throw new DatabaseException("Database schema is out of date");
460             }
461             //CSON: EmptyBlock
462         }
463     }
464 
465     /**
466      * Returns a resource bundle containing the SQL Statements needed for the
467      * database engine being used.
468      *
469      * @return a resource bundle containing the SQL Statements
470      */
471     public ResourceBundle getSqlStatements() {
472         final ResourceBundle statementBundle = getDatabaseProductName() != null
473                 ? ResourceBundle.getBundle("data/dbStatements", new Locale(getDatabaseProductName()))
474                 : ResourceBundle.getBundle("data/dbStatements");
475         return statementBundle;
476     }
477 
478     /**
479      * Uses the provided connection to check the specified schema version within
480      * the database.
481      *
482      * @param conn the database connection object
483      * @throws DatabaseException thrown if the schema version is not compatible
484      * with this version of dependency-check
485      */
486     private void ensureSchemaVersion(Connection conn) throws DatabaseException {
487         ResultSet rs = null;
488         PreparedStatement ps = null;
489         final ResourceBundle statementBundle = getSqlStatements();
490         final String sql = statementBundle.getString("SELECT_SCHEMA_VERSION");
491         try {
492             ps = conn.prepareStatement(sql);
493             rs = ps.executeQuery();
494             if (rs.next()) {
495                 final String dbSchemaVersion = settings.getString(Settings.KEYS.DB_VERSION);
496                 final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(dbSchemaVersion);
497                 if (appDbVersion == null) {
498                     throw new DatabaseException("Invalid application database schema");
499                 }
500                 final DependencyVersion db = DependencyVersionUtil.parseVersion(rs.getString(1));
501                 if (db == null) {
502                     throw new DatabaseException("Invalid database schema");
503                 }
504                 LOGGER.debug("DC Schema: {}", appDbVersion);
505                 LOGGER.debug("DB Schema: {}", db);
506                 if (appDbVersion.compareTo(db) > 0) {
507                     final boolean autoUpdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true);
508                     if (autoUpdate) {
509                         updateSchema(conn, appDbVersion, db);
510                         if (++callDepth < 10) {
511                             ensureSchemaVersion(conn);
512                         }
513                     } else {
514                         throw new DatabaseException("Old database schema identified - please execute "
515                                 + "dependency-check without the no-update configuration to continue");
516                     }
517                 }
518             } else {
519                 throw new DatabaseException("Database schema is missing");
520             }
521         } catch (SQLException ex) {
522             LOGGER.debug("", ex);
523             throw new DatabaseException("Unable to check the database schema version", ex);
524         } finally {
525             DBUtils.closeResultSet(rs);
526             DBUtils.closeStatement(ps);
527         }
528     }
529 
530     /**
531      * Opens the database connection pool.
532      */
533     public void open() {
534         connectionPool = new BasicDataSource();
535         if (driver != null) {
536             connectionPool.setDriver(driver);
537         }
538         connectionPool.setUrl(connectionString);
539         connectionPool.setUsername(userName);
540         connectionPool.setPassword(password);
541     }
542 
543     /**
544      * Closes the database connection pool.
545      */
546     public void close() {
547         try {
548             connectionPool.close();
549         } catch (SQLException ex) {
550             LOGGER.debug("Error closing the connection pool", ex);
551         }
552         connectionPool = null;
553     }
554 
555     /**
556      * Returns if the connection pool is open.
557      *
558      * @return if the connection pool is open
559      */
560     public boolean isOpen() {
561         return connectionPool != null;
562     }
563 
564     /**
565      * Constructs a new database connection object per the database
566      * configuration.
567      *
568      * @return a database connection object
569      * @throws DatabaseException thrown if there is an exception obtaining the
570      * database connection
571      */
572     public Connection getConnection() throws DatabaseException {
573         try {
574             return connectionPool.getConnection();
575         } catch (SQLException ex) {
576             throw new DatabaseException("Error connecting to the database", ex);
577         }
578     }
579 }