diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java index 5f6ccc06d..919c5f93b 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java @@ -948,7 +948,7 @@ public class Check extends Update { dealWithReferences(); validateConfiguration(); populateSettings(); - try (Engine engine = new Engine(Check.class.getClassLoader())) { + try (Engine engine = new Engine(Check.class.getClassLoader(), getSettings())) { if (isUpdateOnly()) { log("Deprecated 'UpdateOnly' property set; please use the UpdateTask instead", Project.MSG_WARN); try { @@ -999,7 +999,7 @@ public class Check extends Update { } log(msg, ex, Project.MSG_ERR); } finally { - Settings.cleanup(true); + getSettings().cleanup(true); } } @@ -1028,33 +1028,33 @@ public class Check extends Update { @Override protected void populateSettings() throws BuildException { super.populateSettings(); - Settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); - Settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFiles.toArray(new String[suppressionFiles.size()])); - Settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled); - Settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, nspAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); - Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); + getSettings().setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); + getSettings().setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFiles.toArray(new String[suppressionFiles.size()])); + getSettings().setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled); + getSettings().setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, nspAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled); + getSettings().setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); + getSettings().setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); + getSettings().setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); + getSettings().setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); } /** diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java index 23f520f35..c1582edb2 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java @@ -37,22 +37,35 @@ public class Purge extends Task { * The properties file location. */ private static final String PROPERTIES_FILE = "task.properties"; - /** - * Construct a new DependencyCheckTask. + * The configured settings. */ - public Purge() { - super(); - // Call this before Dependency Check Core starts logging anything - this way, all SLF4J messages from - // core end up coming through this tasks logger - StaticLoggerBinder.getSingleton().setTask(this); - } + private Settings settings; /** * The location of the data directory that contains */ private String dataDirectory = null; + /** + * Indicates if dependency-check should fail the build if an exception + * occurs. + */ + private boolean failOnError = true; + /** + * Construct a new DependencyCheckTask. + */ + public Purge() { + super(); + + // Call this before Dependency Check Core starts logging anything - this way, all SLF4J messages from + // core end up coming through this tasks logger + StaticLoggerBinder.getSingleton().setTask(this); + } + public Settings getSettings() { + return settings; + } + /** * Get the value of dataDirectory. * @@ -71,12 +84,6 @@ public class Purge extends Task { this.dataDirectory = dataDirectory; } - /** - * Indicates if dependency-check should fail the build if an exception - * occurs. - */ - private boolean failOnError = true; - /** * Get the value of failOnError. * @@ -106,7 +113,7 @@ public class Purge extends Task { populateSettings(); File db; try { - db = new File(Settings.getDataDirectory(), "dc.h2.db"); + db = new File(settings.getDataDirectory(), "dc.h2.db"); if (db.exists()) { if (db.delete()) { log("Database file purged; local copy of the NVD has been removed", Project.MSG_INFO); @@ -131,7 +138,7 @@ public class Purge extends Task { } log(msg, Project.MSG_ERR); } finally { - Settings.cleanup(true); + settings.cleanup(true); } } @@ -143,9 +150,9 @@ public class Purge extends Task { * @throws BuildException thrown if the properties file cannot be read. */ protected void populateSettings() throws BuildException { - Settings.initialize(); + settings = new Settings(); try (InputStream taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)) { - Settings.mergeProperties(taskProperties); + settings.mergeProperties(taskProperties); } catch (IOException ex) { final String msg = "Unable to load the dependency-check ant task.properties file."; if (this.failOnError) { @@ -154,13 +161,13 @@ public class Purge extends Task { log(msg, ex, Project.MSG_WARN); } if (dataDirectory != null) { - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); } else { final File jarPath = new File(Purge.class.getProtectionDomain().getCodeSource().getLocation().getPath()); final File base = jarPath.getParentFile(); - final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY); + final String sub = settings.getString(Settings.KEYS.DATA_DIRECTORY); final File dataDir = new File(base, sub); - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); } } } diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Update.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Update.java index a422962f2..3281d10ae 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Update.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Update.java @@ -385,7 +385,7 @@ public class Update extends Purge { @Override public void execute() throws BuildException { populateSettings(); - try (Engine engine = new Engine(Update.class.getClassLoader())) { + try (Engine engine = new Engine(Update.class.getClassLoader(), getSettings())) { try { engine.doUpdates(); } catch (UpdateException ex) { @@ -401,7 +401,7 @@ public class Update extends Purge { } log(msg, Project.MSG_ERR); } finally { - Settings.cleanup(true); + getSettings().cleanup(true); } } @@ -415,23 +415,23 @@ public class Update extends Purge { @Override protected void populateSettings() throws BuildException { super.populateSettings(); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUsername); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPassword); - Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); + getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); + getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); + getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUsername); + getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPassword); + getSettings().setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); + getSettings().setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); + getSettings().setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); + getSettings().setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); + getSettings().setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); + getSettings().setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); + getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); + getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); + getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); + getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); if (cveValidForHours != null) { if (cveValidForHours >= 0) { - Settings.setInt(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); + getSettings().setInt(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); } else { throw new BuildException("Invalid setting: `cpeValidForHours` must be 0 or greater"); } diff --git a/dependency-check-ant/src/test/java/org/owasp/dependencycheck/taskdefs/DependencyCheckTaskTest.java b/dependency-check-ant/src/test/java/org/owasp/dependencycheck/taskdefs/DependencyCheckTaskTest.java index 657b284b2..ec8d065e1 100644 --- a/dependency-check-ant/src/test/java/org/owasp/dependencycheck/taskdefs/DependencyCheckTaskTest.java +++ b/dependency-check-ant/src/test/java/org/owasp/dependencycheck/taskdefs/DependencyCheckTaskTest.java @@ -21,13 +21,11 @@ import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildFileRule; -import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.owasp.dependencycheck.BaseDBTestCase; -import org.owasp.dependencycheck.utils.Settings; import static org.junit.Assert.assertTrue; @@ -35,7 +33,7 @@ import static org.junit.Assert.assertTrue; * * @author Jeremy Long */ -public class DependencyCheckTaskTest { +public class DependencyCheckTaskTest extends BaseDBTestCase { @Rule public BuildFileRule buildFileRule = new BuildFileRule(); @@ -44,20 +42,13 @@ public class DependencyCheckTaskTest { public ExpectedException expectedException = ExpectedException.none(); @Before + @Override public void setUp() throws Exception { - Settings.initialize(); - BaseDBTestCase.ensureDBExists(); + super.setUp(); final String buildFile = this.getClass().getClassLoader().getResource("build.xml").getPath(); buildFileRule.configureProject(buildFile); } - @After - public void tearDown() { - //no cleanup... - //executeTarget("cleanup"); - Settings.cleanup(true); - } - /** * Test of addFileSet method, of class DependencyCheckTask. */ diff --git a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java index 39b564bab..742017611 100644 --- a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java +++ b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java @@ -53,6 +53,10 @@ public class App { * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** + * The configured settings. + */ + private Settings settings = null; /** * The main method for the application. @@ -61,17 +65,28 @@ public class App { */ public static void main(String[] args) { int exitCode = 0; - try { - Settings.initialize(); - final App app = new App(); - exitCode = app.run(args); - LOGGER.debug("Exit code: {}", exitCode); - } finally { - Settings.cleanup(true); - } + final App app = new App(); + exitCode = app.run(args); + LOGGER.debug("Exit code: {}", exitCode); System.exit(exitCode); } + /** + * Builds the App object. + */ + public App() { + settings = new Settings(); + } + + /** + * Builds the App object; this method is used for testing. + * + * @param settings the configured settings + */ + protected App(Settings settings) { + this.settings = settings; + } + /** * Main CLI entry-point into the application. * @@ -80,7 +95,7 @@ public class App { */ public int run(String[] args) { int exitCode = 0; - final CliParser cli = new CliParser(); + final CliParser cli = new CliParser(settings); try { cli.parse(args); @@ -109,10 +124,11 @@ public class App { LOGGER.error(ex.getMessage()); LOGGER.debug("Error loading properties file", ex); exitCode = -4; + return exitCode; } File db; try { - db = new File(Settings.getDataDirectory(), Settings.getString(Settings.KEYS.DB_FILE_NAME, "dc.h2.db")); + db = new File(settings.getDataDirectory(), settings.getString(Settings.KEYS.DB_FILE_NAME, "dc.h2.db")); if (db.exists()) { if (db.delete()) { LOGGER.info("Database file purged; local copy of the NVD has been removed"); @@ -127,6 +143,8 @@ public class App { } catch (IOException ex) { LOGGER.error("Unable to delete the database"); exitCode = -7; + } finally { + settings.cleanup(); } } } else if (cli.isGetVersion()) { @@ -138,6 +156,7 @@ public class App { LOGGER.error(ex.getMessage()); LOGGER.debug("Error loading properties file", ex); exitCode = -4; + return exitCode; } try { runUpdateOnly(); @@ -147,6 +166,8 @@ public class App { } catch (DatabaseException ex) { LOGGER.error(ex.getMessage()); exitCode = -9; + } finally { + settings.cleanup(); } } else if (cli.isRunScan()) { try { @@ -155,6 +176,7 @@ public class App { LOGGER.error(ex.getMessage()); LOGGER.debug("Error loading properties file", ex); exitCode = -4; + return exitCode; } try { final String[] scanFiles = cli.getScanFiles(); @@ -183,6 +205,8 @@ public class App { for (Throwable e : ex.getExceptions()) { LOGGER.error(e.getMessage()); } + } finally { + settings.cleanup(); } } else { cli.printHelp(); @@ -221,7 +245,7 @@ public class App { final List antStylePaths = getPaths(files); final Set paths = scanAntStylePaths(antStylePaths, symLinkDepth, excludes); - engine = new Engine(); + engine = new Engine(settings); engine.scan(paths); ExceptionCollection exCol = null; @@ -359,7 +383,7 @@ public class App { * connection to the database could not be established */ private void runUpdateOnly() throws UpdateException, DatabaseException { - try (Engine engine = new Engine()) { + try (Engine engine = new Engine(settings)) { engine.doUpdates(); } } @@ -401,7 +425,7 @@ public class App { if (propertiesFile != null) { try { - Settings.mergeProperties(propertiesFile); + settings.mergeProperties(propertiesFile); } catch (FileNotFoundException ex) { throw new InvalidSettingException("Unable to find properties file '" + propertiesFile.getPath() + "'", ex); } catch (IOException ex) { @@ -413,65 +437,65 @@ public class App { // on the command line. This is true of other boolean values set below not using the setBooleanIfNotNull. final boolean nexusUsesProxy = cli.isNexusUsesProxy(); if (dataDirectory != null) { - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); } else if (System.getProperty("basedir") != null) { final File dataDir = new File(System.getProperty("basedir"), "data"); - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); } else { final File jarPath = new File(App.class.getProtectionDomain().getCodeSource().getLocation().getPath()); final File base = jarPath.getParentFile(); - final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY); + final String sub = settings.getString(Settings.KEYS.DATA_DIRECTORY); final File dataDir = new File(base, sub); - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); } - Settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUser); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPass); - Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); - Settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); - Settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); + settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUser); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPass); + settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); + settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); + settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); - Settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFiles); + settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFiles); //File Type Analyzer Settings - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, experimentalEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, experimentalEnabled); - Settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, !cli.isJarDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, !cli.isArchiveDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, !cli.isPythonDistributionDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, !cli.isPythonPackageDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, !cli.isAutoconfDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_CMAKE_ENABLED, !cli.isCmakeDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, !cli.isNuspecDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, !cli.isAssemblyDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, !cli.isBundleAuditDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, !cli.isOpenSSLDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, !cli.isComposerDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, !cli.isNodeJsDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, !cli.isNspDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, !cli.isSwiftPackageAnalyzerDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, !cli.isCocoapodsAnalyzerDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, !cli.isRubyGemspecDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, !cli.isCentralDisabled()); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, !cli.isNexusDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, !cli.isJarDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, !cli.isArchiveDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, !cli.isPythonDistributionDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, !cli.isPythonPackageDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, !cli.isAutoconfDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_CMAKE_ENABLED, !cli.isCmakeDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, !cli.isNuspecDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, !cli.isAssemblyDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, !cli.isBundleAuditDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, !cli.isOpenSSLDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, !cli.isComposerDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, !cli.isNodeJsDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, !cli.isNspDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, !cli.isSwiftPackageAnalyzerDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, !cli.isCocoapodsAnalyzerDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, !cli.isRubyGemspecDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, !cli.isCentralDisabled()); + settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, !cli.isNexusDisabled()); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, cli.getPathToBundleAudit()); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); - Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, additionalZipExtensions); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, cli.getPathToBundleAudit()); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); + settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); + settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); + settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); + settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); + settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, additionalZipExtensions); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); if (cveBase12 != null && !cveBase12.isEmpty()) { - Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveBase12); - Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveBase20); - Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveMod12); - Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveMod20); + settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveBase12); + settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveBase20); + settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveMod12); + settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveMod20); } } diff --git a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java index 080826b12..eee18ca27 100644 --- a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java +++ b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java @@ -53,6 +53,14 @@ public final class CliParser { * Indicates whether the arguments are valid. */ private boolean isValid = true; + /** + * The configured settings. + */ + private final Settings settings; + + public CliParser(Settings settings) { + this.settings = settings; + } /** * Parses the arguments passed in and captures the results for later use. @@ -582,7 +590,7 @@ public final class CliParser { private boolean hasDisableOption(String argument, String setting) { if (line == null || !line.hasOption(argument)) { try { - return !Settings.getBoolean(setting); + return !settings.getBoolean(setting); } catch (InvalidSettingException ise) { LOGGER.warn("Invalid property setting '{}' defaulting to false", setting); return false; @@ -801,7 +809,7 @@ public final class CliParser { // still honor the property if it's set. if (line == null || !line.hasOption(ARGUMENT.NEXUS_USES_PROXY)) { try { - return Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); + return settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); } catch (InvalidSettingException ise) { return true; } @@ -823,10 +831,10 @@ public final class CliParser { final String helpMsg = String.format("%n%s" + " can be used to identify if there are any known CVE vulnerabilities in libraries utilized by an application. " + "%s will automatically update required data from the Internet, such as the CVE and CPE data files from nvd.nist.gov.%n%n", - Settings.getString("application.name", "DependencyCheck"), - Settings.getString("application.name", "DependencyCheck")); + settings.getString("application.name", "DependencyCheck"), + settings.getString("application.name", "DependencyCheck")); - formatter.printHelp(Settings.getString("application.name", "DependencyCheck"), + formatter.printHelp(settings.getString("application.name", "DependencyCheck"), helpMsg, options, "", @@ -1054,8 +1062,8 @@ public final class CliParser { */ public void printVersionInfo() { final String version = String.format("%s version %s", - Settings.getString(Settings.KEYS.APPLICATION_NAME, "dependency-check"), - Settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); + settings.getString(Settings.KEYS.APPLICATION_NAME, "dependency-check"), + settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); System.out.println(version); } diff --git a/dependency-check-cli/src/test/java/org/owasp/dependencycheck/AppTest.java b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/AppTest.java index 4a2346a31..4aebdefed 100644 --- a/dependency-check-cli/src/test/java/org/owasp/dependencycheck/AppTest.java +++ b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/AppTest.java @@ -30,8 +30,6 @@ import java.util.Map; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.UnrecognizedOptionException; -import org.junit.After; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -42,7 +40,7 @@ import org.owasp.dependencycheck.utils.Settings.KEYS; /** * Tests for the {@link AppTest} class. */ -public class AppTest { +public class AppTest extends BaseTest { /** * Test rule for asserting exceptions and their contents. @@ -50,29 +48,13 @@ public class AppTest { @Rule public ExpectedException expectedException = ExpectedException.none(); - /** - * Initialize the {@link Settings} singleton. - */ - @Before - public void setUp() { - Settings.initialize(); - } - - /** - * Clean the {@link Settings} singleton. - */ - @After - public void tearDown() { - Settings.cleanup(); - } - /** * Test of ensureCanonicalPath method, of class App. */ @Test public void testEnsureCanonicalPath() { String file = "../*.jar"; - App instance = new App(); + App instance = new App(getSettings()); String result = instance.ensureCanonicalPath(file); assertFalse(result.contains("..")); assertTrue(result.endsWith("*.jar")); @@ -85,7 +67,7 @@ public class AppTest { /** * Assert that boolean properties can be set on the CLI and parsed into the - * {@link Settings} singleton. + * {@link Settings}. * * @throws Exception the unexpected {@link Exception}. */ @@ -165,13 +147,13 @@ public class AppTest { String[] args = {"-P", prop.getAbsolutePath(), "--suppression", "another-file.xml"}; // WHEN parsing the CLI arguments - final CliParser cli = new CliParser(); + final CliParser cli = new CliParser(getSettings()); cli.parse(args); - final App classUnderTest = new App(); + final App classUnderTest = new App(getSettings()); classUnderTest.populateSettings(cli); - // THEN the suppression file is set in the settings singleton for use in the application core - assertThat("Expected the suppression file to be set in the Settings singleton", Settings.getString(KEYS.SUPPRESSION_FILE), is("another-file.xml")); + // THEN the suppression file is set in the settings for use in the application core + assertThat("Expected the suppression file to be set in the Settings", getSettings().getString(KEYS.SUPPRESSION_FILE), is("another-file.xml")); } /** @@ -188,31 +170,25 @@ public class AppTest { String[] args = {"-P", prop.getAbsolutePath(), "--suppression", "first-file.xml", "another-file.xml"}; // WHEN parsing the CLI arguments - final CliParser cli = new CliParser(); + final CliParser cli = new CliParser(getSettings()); cli.parse(args); - final App classUnderTest = new App(); + final App classUnderTest = new App(getSettings()); classUnderTest.populateSettings(cli); - // THEN the suppression file is set in the settings singleton for use in the application core - assertThat("Expected the suppression files to be set in the Settings singleton with a separator", Settings.getString(KEYS.SUPPRESSION_FILE), is("first-file.xml,another-file.xml")); + // THEN the suppression file is set in the settings for use in the application core + assertThat("Expected the suppression files to be set in the Settings with a separator", getSettings().getString(KEYS.SUPPRESSION_FILE), is("first-file.xml,another-file.xml")); } private boolean testBooleanProperties(String[] args, Map expected) throws URISyntaxException, FileNotFoundException, ParseException, InvalidSettingException { - Settings.initialize(); - try { - final CliParser cli = new CliParser(); - cli.parse(args); - App instance = new App(); - instance.populateSettings(cli); - boolean results = true; - for (Map.Entry entry : expected.entrySet()) { - results &= Settings.getBoolean(entry.getKey()) == entry.getValue(); - } - - return results; - } finally { - Settings.cleanup(); + this.reloadSettings(); + final CliParser cli = new CliParser(getSettings()); + cli.parse(args); + App instance = new App(getSettings()); + instance.populateSettings(cli); + boolean results = true; + for (Map.Entry entry : expected.entrySet()) { + results &= getSettings().getBoolean(entry.getKey()) == entry.getValue(); } + return results; } - } diff --git a/dependency-check-cli/src/test/java/org/owasp/dependencycheck/BaseTest.java b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/BaseTest.java new file mode 100644 index 000000000..cf8dec880 --- /dev/null +++ b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/BaseTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014 OWASP. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.owasp.dependencycheck; + +import org.junit.After; +import org.junit.Before; +import org.owasp.dependencycheck.utils.Settings; + +/** + * + * @author Jeremy Long + */ +public class BaseTest { + + /** + * The configured settings. + */ + private Settings settings; + + /** + * Initialize the {@link Settings}. + */ + @Before + public void setUp() { + settings = new Settings(); + } + + /** + * Clean the {@link Settings}. + */ + @After + public void tearDown() { + settings.cleanup(true); + } + + /** + * Returns the settings for the test cases. + * + * @return + */ + protected Settings getSettings() { + return settings; + } + + protected void reloadSettings() { + tearDown(); + setUp(); + } +} diff --git a/dependency-check-cli/src/test/java/org/owasp/dependencycheck/CliParserTest.java b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/CliParserTest.java index c564d7c79..30c43992a 100644 --- a/dependency-check-cli/src/test/java/org/owasp/dependencycheck/CliParserTest.java +++ b/dependency-check-cli/src/test/java/org/owasp/dependencycheck/CliParserTest.java @@ -33,17 +33,7 @@ import org.owasp.dependencycheck.utils.Settings; * * @author Jeremy Long */ -public class CliParserTest { - - @BeforeClass - public static void setUpClass() throws Exception { - Settings.initialize(); - } - - @AfterClass - public static void tearDownClass() throws Exception { - Settings.cleanup(true); - } +public class CliParserTest extends BaseTest { /** * Test of parse method, of class CliParser. @@ -59,7 +49,7 @@ public class CliParserTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertFalse(instance.isGetVersion()); @@ -78,7 +68,7 @@ public class CliParserTest { String[] args = {"-help"}; PrintStream out = System.out; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertFalse(instance.isGetVersion()); @@ -96,7 +86,7 @@ public class CliParserTest { String[] args = {"-version"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertTrue(instance.isGetVersion()); Assert.assertFalse(instance.isGetHelp()); @@ -114,7 +104,7 @@ public class CliParserTest { String[] args = {"--failOnCVSS"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); try { instance.parse(args); } catch (ParseException ex) { @@ -135,7 +125,7 @@ public class CliParserTest { String[] args = {"--failOnCVSS","bad"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertEquals("Default should be 11", 11, instance.getFailOnCVSS()); Assert.assertFalse(instance.isGetVersion()); @@ -153,7 +143,7 @@ public class CliParserTest { String[] args = {"--failOnCVSS","6"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertEquals(6, instance.getFailOnCVSS()); Assert.assertFalse(instance.isGetVersion()); @@ -178,7 +168,7 @@ public class CliParserTest { System.setOut(new PrintStream(baos_out)); System.setErr(new PrintStream(baos_err)); - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); try { instance.parse(args); @@ -200,7 +190,7 @@ public class CliParserTest { String[] args = {"-scan"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); try { instance.parse(args); @@ -223,7 +213,7 @@ public class CliParserTest { String[] args = {"-scan", "jar.that.does.not.exist", "-app", "test"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); try { instance.parse(args); } catch (FileNotFoundException ex) { @@ -245,7 +235,7 @@ public class CliParserTest { File path = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").toURI().getPath()); String[] args = {"-scan", path.getCanonicalPath(), "-out", "./", "-app", "test"}; - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.parse(args); Assert.assertEquals(path.getCanonicalPath(), instance.getScanFiles()[0]); @@ -267,7 +257,7 @@ public class CliParserTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); instance.printVersionInfo(); try { baos.flush(); @@ -296,7 +286,7 @@ public class CliParserTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); - CliParser instance = new CliParser(); + CliParser instance = new CliParser(getSettings()); String[] args = {"-h"}; instance.parse(args); instance.printHelp(); diff --git a/dependency-check-cli/src/test/resources/sample.properties b/dependency-check-cli/src/test/resources/sample.properties index 0b45d5d04..51fdaa872 100644 --- a/dependency-check-cli/src/test/resources/sample.properties +++ b/dependency-check-cli/src/test/resources/sample.properties @@ -1,5 +1,5 @@ autoupdate=false - +somethingmadeup=test analyzer.experimental.enabled=false analyzer.jar.enabled=true analyzer.archive.enabled=true diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java index 7f96e269c..21b6da092 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java @@ -89,26 +89,20 @@ public class AnalysisTask implements Callable { */ @Override public Void call() { - try { - Settings.setInstance(settings); - - if (shouldAnalyze()) { - LOGGER.debug("Begin Analysis of '{}' ({})", dependency.getActualFilePath(), analyzer.getName()); - try { - analyzer.analyze(dependency, engine); - } catch (AnalysisException ex) { - LOGGER.warn("An error occurred while analyzing '{}' ({}).", dependency.getActualFilePath(), analyzer.getName()); - LOGGER.debug("", ex); - exceptions.add(ex); - } catch (Throwable ex) { - LOGGER.warn("An unexpected error occurred during analysis of '{}' ({}): {}", - dependency.getActualFilePath(), analyzer.getName(), ex.getMessage()); - LOGGER.debug("", ex); - exceptions.add(ex); - } + if (shouldAnalyze()) { + LOGGER.debug("Begin Analysis of '{}' ({})", dependency.getActualFilePath(), analyzer.getName()); + try { + analyzer.analyze(dependency, engine); + } catch (AnalysisException ex) { + LOGGER.warn("An error occurred while analyzing '{}' ({}).", dependency.getActualFilePath(), analyzer.getName()); + LOGGER.debug("", ex); + exceptions.add(ex); + } catch (Throwable ex) { + LOGGER.warn("An unexpected error occurred during analysis of '{}' ({}): {}", + dependency.getActualFilePath(), analyzer.getName(), ex.getMessage()); + LOGGER.debug("", ex); + exceptions.add(ex); } - } finally { - Settings.cleanup(false); } return null; } @@ -123,7 +117,6 @@ public class AnalysisTask implements Callable { final FileTypeAnalyzer fileTypeAnalyzer = (FileTypeAnalyzer) analyzer; return fileTypeAnalyzer.accept(dependency.getActualFile()); } - return true; } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java index 116dfe43e..96cfd4ca3 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java @@ -179,30 +179,38 @@ public class Engine implements FileFilter, AutoCloseable { * The Logger for use throughout the class. */ private static final Logger LOGGER = LoggerFactory.getLogger(Engine.class); + /** + * The configured settings. + */ + private final Settings settings; /** * Creates a new {@link Mode#STANDALONE} Engine. + * + * @param settings reference to the configured settings */ - public Engine() { - this(Mode.STANDALONE); + public Engine(Settings settings) { + this(Mode.STANDALONE, settings); } /** * Creates a new Engine. * * @param mode the mode of operation + * @param settings reference to the configured settings */ - public Engine(Mode mode) { - this(Thread.currentThread().getContextClassLoader(), mode); + public Engine(Mode mode, Settings settings) { + this(Thread.currentThread().getContextClassLoader(), mode, settings); } /** * Creates a new {@link Mode#STANDALONE} Engine. * * @param serviceClassLoader a reference the class loader being used + * @param settings reference to the configured settings */ - public Engine(ClassLoader serviceClassLoader) { - this(serviceClassLoader, Mode.STANDALONE); + public Engine(ClassLoader serviceClassLoader, Settings settings) { + this(serviceClassLoader, Mode.STANDALONE, settings); } /** @@ -210,8 +218,10 @@ public class Engine implements FileFilter, AutoCloseable { * * @param serviceClassLoader a reference the class loader being used * @param mode the mode of the engine + * @param settings reference to the configured settings */ - public Engine(ClassLoader serviceClassLoader, Mode mode) { + public Engine(ClassLoader serviceClassLoader, Mode mode, Settings settings) { + this.settings = settings; this.serviceClassLoader = serviceClassLoader; this.mode = mode; initializeEngine(); @@ -225,9 +235,6 @@ public class Engine implements FileFilter, AutoCloseable { * database */ protected final void initializeEngine() { - if (mode.isDatabseRequired()) { - ConnectionFactory.initialize(); - } loadAnalyzers(); } @@ -240,7 +247,6 @@ public class Engine implements FileFilter, AutoCloseable { database.close(); database = null; } - ConnectionFactory.cleanup(); } } @@ -260,10 +266,16 @@ public class Engine implements FileFilter, AutoCloseable { for (AnalysisPhase phase : mode.getPhases()) { analyzers.put(phase, new ArrayList()); } - - final AnalyzerService service = new AnalyzerService(serviceClassLoader); + boolean loadExperimental = false; + try { + loadExperimental = settings.getBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false); + } catch (InvalidSettingException ex) { + LOGGER.trace("Experimenal setting not configured; defaulting to false"); + } + final AnalyzerService service = new AnalyzerService(serviceClassLoader, loadExperimental); final List iterator = service.getAnalyzers(mode.getPhases()); for (Analyzer a : iterator) { + a.initializeSettings(this.settings); analyzers.get(a.getAnalysisPhase()).add(a); if (a instanceof FileTypeAnalyzer) { this.fileTypeAnalyzers.add((FileTypeAnalyzer) a); @@ -662,14 +674,13 @@ public class Engine implements FileFilter, AutoCloseable { } boolean autoUpdate = true; try { - autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); + autoUpdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE); } catch (InvalidSettingException ex) { LOGGER.debug("Invalid setting for auto-update; using true."); exceptions.add(ex); } if (autoUpdate) { try { - database = CveDB.getInstance(); doUpdates(); } catch (UpdateException ex) { exceptions.add(ex); @@ -681,10 +692,10 @@ public class Engine implements FileFilter, AutoCloseable { } } else { try { - if (ConnectionFactory.isH2Connection() && !ConnectionFactory.h2DataFileExists()) { + if (ConnectionFactory.isH2Connection(settings) && !ConnectionFactory.h2DataFileExists(settings)) { throw new ExceptionCollection(new NoDataException("Autoupdate is disabled and the database does not exist"), true); } else { - database = CveDB.getInstance(); + openDatabase(); } } catch (IOException ex) { throw new ExceptionCollection(new DatabaseException("Autoupdate is disabled and unable to connect to the database"), true); @@ -739,7 +750,7 @@ public class Engine implements FileFilter, AutoCloseable { final List result = new ArrayList<>(); synchronized (dependencies) { for (final Dependency dependency : dependencies) { - final AnalysisTask task = new AnalysisTask(analyzer, dependency, this, exceptions, Settings.getInstance()); + final AnalysisTask task = new AnalysisTask(analyzer, dependency, this, exceptions, settings); result.add(task); } } @@ -773,7 +784,7 @@ public class Engine implements FileFilter, AutoCloseable { protected void initializeAnalyzer(Analyzer analyzer) throws InitializationException { try { LOGGER.debug("Initializing {}", analyzer.getName()); - analyzer.initialize(); + analyzer.initialize(this); } catch (InitializationException ex) { LOGGER.error("Exception occurred initializing {}.", analyzer.getName()); LOGGER.debug("", ex); @@ -817,13 +828,14 @@ public class Engine implements FileFilter, AutoCloseable { */ public void doUpdates() throws UpdateException { if (mode.isDatabseRequired()) { + openDatabase(); LOGGER.info("Checking for updates"); final long updateStart = System.currentTimeMillis(); final UpdateService service = new UpdateService(serviceClassLoader); final Iterator iterator = service.getDataSources(); while (iterator.hasNext()) { final CachedWebDataSource source = iterator.next(); - source.update(); + source.update(this); } LOGGER.info("Check for updates complete ({} ms)", System.currentTimeMillis() - updateStart); } else { @@ -831,6 +843,24 @@ public class Engine implements FileFilter, AutoCloseable { } } + /** + * Opens the database connection. + */ + public void openDatabase() { + if (mode.isDatabseRequired() && database == null) { + database = new CveDB(settings); + } + } + + /** + * Returns a reference to the database. + * + * @return a reference to the database + */ + public CveDB getDatabase() { + return this.database; + } + /** * Returns a full list of all of the analyzers. This is useful for reporting * which analyzers where used. @@ -876,6 +906,15 @@ public class Engine implements FileFilter, AutoCloseable { return this.fileTypeAnalyzers; } + /** + * Returns + * + * @return + */ + public Settings getSettings() { + return settings; + } + /** * Adds a file type analyzer. This has been added solely to assist in unit * testing the Engine. @@ -932,7 +971,7 @@ public class Engine implements FileFilter, AutoCloseable { throw new UnsupportedOperationException("Cannot generate report in evidence collection mode."); } final DatabaseProperties prop = database.getDatabaseProperties(); - final ReportGenerator r = new ReportGenerator(applicationName, groupId, artifactId, version, dependencies, getAnalyzers(), prop); + final ReportGenerator r = new ReportGenerator(applicationName, groupId, artifactId, version, dependencies, getAnalyzers(), prop, settings); try { r.write(outputDir.getAbsolutePath(), format); } catch (ReportException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java index 22f5e0f62..fea1064c7 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java @@ -207,6 +207,10 @@ public class DependencyCheckScanAgent { * The path to Mono for .NET assembly analysis on non-windows systems. */ private String pathToMono; + /** + * The configured settings. + */ + private Settings settings; // // @@ -823,7 +827,7 @@ public class DependencyCheckScanAgent { populateSettings(); final Engine engine; try { - engine = new Engine(); + engine = new Engine(settings); } catch (DatabaseException ex) { throw new ExceptionCollection(ex, true); } @@ -855,40 +859,40 @@ public class DependencyCheckScanAgent { * proxy server, port, and connection timeout. */ private void populateSettings() { - Settings.initialize(); + settings = new Settings(); if (dataDirectory != null) { - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); } else { final File jarPath = new File(DependencyCheckScanAgent.class.getProtectionDomain().getCodeSource().getLocation().getPath()); final File base = jarPath.getParentFile(); - final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY); + final String sub = settings.getString(Settings.KEYS.DATA_DIRECTORY); final File dataDir = new File(base, sub); - Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); + settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath()); } - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUsername); - Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPassword); - Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); - Settings.setStringIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFile); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_CENTRAL_URL, centralUrl); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); - Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); + settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUsername); + settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPassword); + settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); + settings.setStringIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFile); + settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_CENTRAL_URL, centralUrl); + settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); + settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); + settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); + settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); + settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); + settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); } /** @@ -918,7 +922,7 @@ public class DependencyCheckScanAgent { } throw new ScanAgentException("One or more exceptions occurred during analysis; please see the debug log for more details.", ex); } finally { - Settings.cleanup(true); + settings.cleanup(true); if (engine != null) { engine.cleanup(); } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java index 891ed6835..682bf411a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java @@ -42,6 +42,10 @@ public abstract class AbstractAnalyzer implements Analyzer { * A flag indicating whether or not the analyzer is enabled. */ private volatile boolean enabled = true; + /** + * The configured settings. + */ + private Settings settings; /** * Get the value of enabled. @@ -62,6 +66,25 @@ public abstract class AbstractAnalyzer implements Analyzer { this.enabled = enabled; } + /** + * Returns the configured settings. + * + * @return the configured settings + */ + protected Settings getSettings() { + return settings; + } + + /** + * Initializes the analyzer with the configured settings. + * + * @param settings the configured settings to use + */ + @Override + public void initializeSettings(Settings settings) { + this.settings = settings; + } + /** *

* Returns the setting key to determine if the analyzer is enabled.

@@ -85,9 +108,11 @@ public abstract class AbstractAnalyzer implements Analyzer { * Initializes a given Analyzer. This will be skipped if the analyzer is * disabled. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if there is an exception */ - protected void initializeAnalyzer() throws InitializationException { + protected void initializeAnalyzer(Engine engine) throws InitializationException { + // Intentionally empty, analyzer will override this if they must initialize anything. } /** @@ -117,22 +142,24 @@ public abstract class AbstractAnalyzer implements Analyzer { } /** - * The initialize method does nothing for this Analyzer. + * Initialize the abstract analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if there is an exception */ @Override - public final void initialize() throws InitializationException { + public final void initialize(Engine engine) throws InitializationException { final String key = getAnalyzerEnabledSettingKey(); try { - this.setEnabled(Settings.getBoolean(key, true)); + this.setEnabled(settings.getBoolean(key, true)); } catch (InvalidSettingException ex) { - LOGGER.warn("Invalid setting for property '{}'", key); - LOGGER.debug("", ex); + String msg = String.format("Invalid setting for property '{}'", key); + LOGGER.warn(msg); + LOGGER.debug(msg, ex); } if (isEnabled()) { - initializeAnalyzer(); + initializeAnalyzer(engine); } else { LOGGER.debug("{} has been disabled", getName()); } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java index 74e87bd0e..fb12ffdd3 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java @@ -25,6 +25,7 @@ import java.io.FileFilter; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.exception.InitializationException; /** @@ -70,13 +71,14 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen /** * Initializes the analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if there is an exception during * initialization */ @Override - protected final void initializeAnalyzer() throws InitializationException { + protected final void initializeAnalyzer(Engine engine) throws InitializationException { if (filesMatched) { - initializeFileTypeAnalyzer(); + initializeFileTypeAnalyzer(engine); } else { this.setEnabled(false); } @@ -101,10 +103,11 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen /** * Initializes the file type analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if there is an exception during * initialization */ - protected abstract void initializeFileTypeAnalyzer() throws InitializationException; + protected abstract void initializeFileTypeAnalyzer(Engine engine) throws InitializationException; //
/** diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java index bab7dcfd1..6aec24cff 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java @@ -79,10 +79,11 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { /** * The initialize method loads the suppression XML file. * + * @param engine a reference the dependency-check engine * @throws InitializationException thrown if there is an exception */ @Override - public void initializeAnalyzer() throws InitializationException { + public void initializeAnalyzer(Engine engine) throws InitializationException { try { loadSuppressionData(); } catch (SuppressionParseException ex) { @@ -101,8 +102,7 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { } /** - * Loads all the suppression rules files configured in the {@link Settings} - * singleton. + * Loads all the suppression rules files configured in the {@link Settings}. * * @throws SuppressionParseException thrown if the XML cannot be parsed. */ @@ -114,7 +114,7 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { } catch (SAXException ex) { throw new SuppressionParseException("Unable to parse the base suppression data file", ex); } - final String[] suppressionFilePaths = Settings.getArray(Settings.KEYS.SUPPRESSION_FILE); + final String[] suppressionFilePaths = getSettings().getArray(Settings.KEYS.SUPPRESSION_FILE); if (suppressionFilePaths == null || suppressionFilePaths.length == 0) { return; } @@ -144,12 +144,14 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { final Pattern uriRx = Pattern.compile("^(https?|file)\\:.*", Pattern.CASE_INSENSITIVE); if (uriRx.matcher(suppressionFilePath).matches()) { deleteTempFile = true; - file = FileUtils.getTempFile("suppression", "xml"); + file = getSettings().getTempFile("suppression", "xml"); final URL url = new URL(suppressionFilePath); + Downloader downloader = new Downloader(getSettings()); try { - Downloader.fetchFile(url, file, false); + downloader.fetchFile(url, file, false); } catch (DownloadFailedException ex) { - Downloader.fetchFile(url, file, true); + LOGGER.trace("Failed download - first attempt", ex); + downloader.fetchFile(url, file, true); } } else { file = new File(suppressionFilePath); @@ -158,7 +160,7 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { try (InputStream suppressionsFromClasspath = FileUtils.getResourceAsStream(suppressionFilePath)) { if (suppressionsFromClasspath != null) { deleteTempFile = true; - file = FileUtils.getTempFile("suppression", "xml"); + file = getSettings().getTempFile("suppression", "xml"); try { org.apache.commons.io.FileUtils.copyInputStreamToFile(suppressionsFromClasspath, file); } catch (IOException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/Analyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/Analyzer.java index 0180a0d01..c00565ecd 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/Analyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/Analyzer.java @@ -21,11 +21,22 @@ import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.exception.InitializationException; +import org.owasp.dependencycheck.utils.Settings; /** + *

* An interface that defines an Analyzer that is used to identify Dependencies. * An analyzer will collect information about the dependency in the form of - * Evidence. + * Evidence.

+ *

+ * When the {@link org.owasp.dependencycheck.Engine} executes it will load the + * analyzers and call the methods in the following order: + *

    + *
  1. {@link #initializeSettings(org.owasp.dependencycheck.utils.Settings)}
  2. + *
  3. {@link #initialize(org.owasp.dependencycheck.Engine)}
  4. + *
  5. {@link #analyze(org.owasp.dependencycheck.dependency.Dependency, org.owasp.dependencycheck.Engine)}
  6. + *
  7. {@link #close()}
  8. + *
* * @author Jeremy Long */ @@ -59,14 +70,22 @@ public interface Analyzer { */ AnalysisPhase getAnalysisPhase(); + /** + * Initializes the analyzer with the configured settings. + * + * @param settings the configured settings + */ + public void initializeSettings(Settings settings); + /** * The initialize method is called (once) prior to the analyze method being * called on all of the dependencies. * + * @param engine a reference to the dependency-check engine * @throws InitializationException is thrown if an exception occurs * initializing the analyzer. */ - void initialize() throws InitializationException; + void initialize(Engine engine) throws InitializationException; /** * The close method is called after all of the dependencies have been @@ -77,16 +96,20 @@ public interface Analyzer { void close() throws Exception; /** - * Returns whether multiple instances of the same type of analyzer can run in parallel. - * Note that running analyzers of different types in parallel is not supported at all. + * Returns whether multiple instances of the same type of analyzer can run + * in parallel. Note that running analyzers of different types in parallel + * is not supported at all. * - * @return {@code true} if the analyzer supports parallel processing, {@code false} else + * @return {@code true} if the analyzer supports parallel processing, + * {@code false} else */ boolean supportsParallelProcessing(); + /** * Get the value of enabled. * * @return the value of enabled */ boolean isEnabled(); + } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java index 4e136aa6f..aa87b8924 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java @@ -18,8 +18,6 @@ package org.owasp.dependencycheck.analyzer; import java.util.ArrayList; -import org.owasp.dependencycheck.utils.InvalidSettingException; -import org.owasp.dependencycheck.utils.Settings; import org.slf4j.LoggerFactory; import static java.util.Arrays.asList; @@ -44,14 +42,20 @@ public class AnalyzerService { * The service loader for analyzers. */ private final ServiceLoader service; + /** + * The configured settings. + */ + private final boolean loadExperimental; /** * Creates a new instance of AnalyzerService. * * @param classLoader the ClassLoader to use when dynamically loading * Analyzer and Update services + * @param loadExperimental whether or not to load the experimental analyzers */ - public AnalyzerService(ClassLoader classLoader) { + public AnalyzerService(ClassLoader classLoader, boolean loadExperimental) { + this.loadExperimental = loadExperimental; service = ServiceLoader.load(Analyzer.class, classLoader); } @@ -85,18 +89,12 @@ public class AnalyzerService { private List getAnalyzers(List phases) { final List analyzers = new ArrayList<>(); final Iterator iterator = service.iterator(); - boolean experimentalEnabled = false; - try { - experimentalEnabled = Settings.getBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false); - } catch (InvalidSettingException ex) { - LOGGER.error("invalid experimental setting", ex); - } while (iterator.hasNext()) { final Analyzer a = iterator.next(); if (!phases.contains(a.getAnalysisPhase())) { continue; } - if (!experimentalEnabled && a.getClass().isAnnotationPresent(Experimental.class)) { + if (!loadExperimental && a.getClass().isAnnotationPresent(Experimental.class)) { continue; } LOGGER.debug("Loaded Analyzer {}", a.getName()); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java index ffd2bc2c2..23a3609d6 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java @@ -80,21 +80,16 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { * The max scan depth that the analyzer will recursively extract nested * archives. */ - private static final int MAX_SCAN_DEPTH = Settings.getInt("archive.scan.depth", 3); + private int maxScanDepth; /** * Tracks the current scan/extraction depth for nested archives. */ private int scanDepth = 0; - // /** - * The name of the analyzer. + * The file filter used to filter supported files. */ - private static final String ANALYZER_NAME = "Archive Analyzer"; - /** - * The phase that this analyzer is intended to run in. - */ - private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL; + private FileFilter fileFilter = null; /** * The set of things we can handle with Zip methods */ @@ -106,35 +101,40 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { */ private static final Set EXTENSIONS = newHashSet("tar", "gz", "tgz", "bz2", "tbz2"); - static { - final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS); - if (additionalZipExt != null) { - final String[] ext = additionalZipExt.split("\\s*,\\s*"); - Collections.addAll(KNOWN_ZIP_EXT, ext); - } - EXTENSIONS.addAll(KNOWN_ZIP_EXT); - } - /** * Detects files with extensions to remove from the engine's collection of * dependencies. */ private static final FileFilter REMOVE_FROM_ANALYSIS = FileFilterBuilder.newInstance() .addExtensions("zip", "tar", "gz", "tgz", "bz2", "tbz2").build(); - - /** - * The file filter used to filter supported files. - */ - private static final FileFilter FILTER = FileFilterBuilder.newInstance().addExtensions(EXTENSIONS).build(); - /** * Detects files with .zip extension. */ private static final FileFilter ZIP_FILTER = FileFilterBuilder.newInstance().addExtensions("zip").build(); + + // + /** + * The name of the analyzer. + */ + private static final String ANALYZER_NAME = "Archive Analyzer"; + /** + * The phase that this analyzer is intended to run in. + */ + private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL; + /** + * Initializes the analyzer with the configured settings. + * + * @param settings the configured settings to use + */ + @Override + public void initializeSettings(Settings settings) { + super.initializeSettings(settings); + initializeSettings(); + } @Override protected FileFilter getFileFilter() { - return FILTER; + return fileFilter; } /** @@ -172,13 +172,14 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { /** * The initialize method does nothing for this Analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException is thrown if there is an exception * deleting or creating temporary files */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { try { - final File baseDir = Settings.getTempDirectory(); + final File baseDir = getSettings().getTempDirectory(); tempFileLocation = File.createTempFile("check", "tmp", baseDir); if (!tempFileLocation.delete()) { setEnabled(false); @@ -265,7 +266,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { //TODO - can we get more evidence from the parent? EAR contains module name, etc. //analyze the dependency (i.e. extract files) if it is a supported type. - if (this.accept(d.getActualFile()) && scanDepth < MAX_SCAN_DEPTH) { + if (this.accept(d.getActualFile()) && scanDepth < maxScanDepth) { scanDepth += 1; analyze(d, engine); scanDepth -= 1; @@ -603,4 +604,19 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { } return isJar; } + + /** + * Initializes settings used by the scanning functions of the archive + * analyzer. + */ + private void initializeSettings() { + maxScanDepth = getSettings().getInt("archive.scan.depth", 3); + final String additionalZipExt = getSettings().getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS); + if (additionalZipExt != null) { + final String[] ext = additionalZipExt.split("\\s*,\\s*"); + Collections.addAll(KNOWN_ZIP_EXT, ext); + } + EXTENSIONS.addAll(KNOWN_ZIP_EXT); + fileFilter = FileFilterBuilder.newInstance().addExtensions(EXTENSIONS).build(); + } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java index d0b53be6f..e0bf7a027 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java @@ -91,8 +91,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { // Use file.separator as a wild guess as to whether this is Windows final List args = new ArrayList<>(); if (!SystemUtils.IS_OS_WINDOWS) { - if (Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) { - args.add(Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH)); + if (getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) { + args.add(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH)); } else if (isInPath("mono")) { args.add("mono"); } else { @@ -207,14 +207,15 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { * Initialize the analyzer. In this case, extract GrokAssembly.exe to a * temporary location. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if anything goes wrong */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { final File tempFile; final File cfgFile; try { - tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory()); + tempFile = File.createTempFile("GKA", ".exe", getSettings().getTempDirectory()); cfgFile = new File(tempFile.getPath() + ".config"); } catch (IOException ex) { setEnabled(false); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java index 88beaa168..4124fe993 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java @@ -268,11 +268,12 @@ public class AutoconfAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the file type analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if there is an exception during * initialization */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // No initialization needed. } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java index f24a468c4..a33ba330a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java @@ -125,11 +125,12 @@ public class CMakeAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if an exception occurs getting an * instance of SHA1 */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { try { getSha1MessageDigest(); } catch (IllegalStateException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java index c23ceccc4..e65ac8da9 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java @@ -138,14 +138,14 @@ public class CPEAnalyzer extends AbstractAnalyzer { /** * Creates the CPE Lucene Index. - * + * @param engine a reference to the dependency-check engine * @throws InitializationException is thrown if there is an issue opening * the index. */ @Override - public void initializeAnalyzer() throws InitializationException { + public void initializeAnalyzer(Engine engine) throws InitializationException { try { - this.open(); + this.open(engine.getDatabase()); } catch (IOException ex) { LOGGER.debug("Exception initializing the Lucene Index", ex); throw new InitializationException("An exception occurred initializing the Lucene Index", ex); @@ -158,15 +158,16 @@ public class CPEAnalyzer extends AbstractAnalyzer { /** * Opens the data source. * + * @param cve a reference to the NVD CVE database * @throws IOException when the Lucene directory to be queried does not * exist or is corrupt. * @throws DatabaseException when the database throws an exception. This * usually occurs when the database is in use by another process. */ - public void open() throws IOException, DatabaseException { + public void open(CveDB cve) throws IOException, DatabaseException { if (!isOpen()) { - cve = CveDB.getInstance(); - cpe = CpeMemoryIndex.getInstance(); + this.cve = cve; + this.cpe = CpeMemoryIndex.getInstance(); try { final long creationStart = System.currentTimeMillis(); cpe.open(cve); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CentralAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CentralAnalyzer.java index c38070e30..b0bb13a03 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CentralAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CentralAnalyzer.java @@ -84,7 +84,18 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer { /** * Field indicating if the analyzer is enabled. */ - private final boolean enabled = checkEnabled(); + private boolean enabled = true; + + /** + * Initializes the analyzer with the configured settings. + * + * @param settings the configured settings to use + */ + @Override + public void initializeSettings(Settings settings) { + super.initializeSettings(settings); + enabled = checkEnabled(); + } /** * Determine whether to enable this analyzer or not. @@ -106,9 +117,9 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer { boolean retVal = false; try { - if (Settings.getBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED)) { - if (!Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED) - || NexusAnalyzer.DEFAULT_URL.equals(Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL))) { + if (getSettings().getBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED)) { + if (!getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED) + || NexusAnalyzer.DEFAULT_URL.equals(getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL))) { LOGGER.debug("Enabling the Central analyzer"); retVal = true; } else { @@ -126,20 +137,19 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer once before any analysis is performed. * + * @param engine a reference to the dependency-check engine * @throws InitializationException if there's an error during initialization */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { LOGGER.debug("Initializing Central analyzer"); LOGGER.debug("Central analyzer enabled: {}", isEnabled()); if (isEnabled()) { - final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL); - LOGGER.debug("Central Analyzer URL: {}", searchUrl); try { - searcher = new CentralSearch(new URL(searchUrl)); + searcher = new CentralSearch(getSettings()); } catch (MalformedURLException ex) { setEnabled(false); - throw new InitializationException("The configured URL to Maven Central is malformed: " + searchUrl, ex); + throw new InitializationException("The configured URL to Maven Central is malformed", ex); } } } @@ -214,7 +224,7 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer { if (!pomAnalyzed && ma.getPomUrl() != null) { File pomFile = null; try { - final File baseDir = Settings.getTempDirectory(); + final File baseDir = getSettings().getTempDirectory(); pomFile = File.createTempFile("pom", ".xml", baseDir); if (!pomFile.delete()) { LOGGER.warn("Unable to fetch pom.xml for {} from Central; " @@ -222,7 +232,8 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer { LOGGER.debug("Unable to delete temp file"); } LOGGER.debug("Downloading {}", ma.getPomUrl()); - Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); + Downloader downloader = new Downloader(getSettings()); + downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); PomUtils.analyzePOM(dependency, pomFile); } catch (DownloadFailedException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java index a8a33121e..e12546ccc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CocoaPodsAnalyzer.java @@ -83,7 +83,7 @@ public class CocoaPodsAnalyzer extends AbstractFileTypeAnalyzer { } @Override - protected void initializeFileTypeAnalyzer() { + protected void initializeFileTypeAnalyzer(Engine engine) { // NO-OP } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java index cccfeb010..79ea9c6e6 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java @@ -79,11 +79,12 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException thrown if an exception occurs getting an * instance of SHA1 */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { try { getSha1MessageDigest(); } catch (IllegalStateException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/HintAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/HintAnalyzer.java index 29bf2a875..d5d8683d9 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/HintAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/HintAnalyzer.java @@ -110,10 +110,11 @@ public class HintAnalyzer extends AbstractAnalyzer { /** * The initialize method does nothing for this Analyzer. * + * @param engine a reference the dependency-check engine * @throws InitializationException thrown if there is an exception */ @Override - public void initializeAnalyzer() throws InitializationException { + public void initializeAnalyzer(Engine engine) throws InitializationException { try { loadHintRules(); } catch (HintParseException ex) { @@ -224,7 +225,7 @@ public class HintAnalyzer extends AbstractAnalyzer { LOGGER.error("Unable to parse the base hint data file"); LOGGER.debug("Unable to parse the base hint data file", ex); } - final String filePath = Settings.getString(Settings.KEYS.HINTS_FILE); + final String filePath = getSettings().getString(Settings.KEYS.HINTS_FILE); if (filePath == null) { return; } @@ -233,12 +234,13 @@ public class HintAnalyzer extends AbstractAnalyzer { final Pattern uriRx = Pattern.compile("^(https?|file)\\:.*", Pattern.CASE_INSENSITIVE); if (uriRx.matcher(filePath).matches()) { deleteTempFile = true; - file = FileUtils.getTempFile("hint", "xml"); + file = getSettings().getTempFile("hint", "xml"); final URL url = new URL(filePath); + Downloader downloader = new Downloader(getSettings()); try { - Downloader.fetchFile(url, file, false); + downloader.fetchFile(url, file, false); } catch (DownloadFailedException ex) { - Downloader.fetchFile(url, file, true); + downloader.fetchFile(url, file, true); } } else { file = new File(filePath); @@ -246,7 +248,7 @@ public class HintAnalyzer extends AbstractAnalyzer { try (InputStream fromClasspath = FileUtils.getResourceAsStream(filePath)) { if (fromClasspath != null) { deleteTempFile = true; - file = FileUtils.getTempFile("hint", "xml"); + file = getSettings().getTempFile("hint", "xml"); try { org.apache.commons.io.FileUtils.copyInputStreamToFile(fromClasspath, file); } catch (IOException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java index db54d1ab6..7f91d1b39 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java @@ -264,13 +264,15 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Checks if the given dependency appears to be a macOS metadata file, returning true if its filename starts with a - * ._ prefix and if there is another dependency with the same filename minus the ._ prefix, otherwise it returns - * false. + * Checks if the given dependency appears to be a macOS metadata file, + * returning true if its filename starts with a ._ prefix and if there is + * another dependency with the same filename minus the ._ prefix, otherwise + * it returns false. * * @param dependency the dependency to check if it's a macOS metadata file - * @param engine the engine that is scanning the dependencies - * @return whether or not the given dependency appears to be a macOS metadata file + * @param engine the engine that is scanning the dependencies + * @return whether or not the given dependency appears to be a macOS + * metadata file */ private boolean isMacOSMetaDataFile(final Dependency dependency, final Engine engine) { final String fileName = Paths.get(dependency.getActualFilePath()).getFileName().toString(); @@ -278,17 +280,19 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Iterates through the given list of dependencies and returns true when it finds a dependency with a filename - * matching the given filename, otherwise returns false. + * Iterates through the given list of dependencies and returns true when it + * finds a dependency with a filename matching the given filename, otherwise + * returns false. * * @param dependencies the dependencies to search within - * @param fileName the filename to search for - * @return whether or not the given dependencies contain a dependency with the given filename + * @param fileName the filename to search for + * @return whether or not the given dependencies contain a dependency with + * the given filename */ private boolean hasDependencyWithFilename(final List dependencies, final String fileName) { for (final Dependency dependency : dependencies) { if (Paths.get(dependency.getActualFilePath()).getFileName().toString().toLowerCase() - .equals(fileName.toLowerCase())) { + .equals(fileName.toLowerCase())) { return true; } } @@ -296,23 +300,24 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Attempts to read the first bytes of the given dependency (using its actual file path) and returns true if they - * match the expected first bytes of a zip file, which may be empty or spanned. If they don't match, or if the file - * could not be read, then it returns false. + * Attempts to read the first bytes of the given dependency (using its + * actual file path) and returns true if they match the expected first bytes + * of a zip file, which may be empty or spanned. If they don't match, or if + * the file could not be read, then it returns false. * * @param dependency the dependency to check if it's a zip file - * @return whether or not the given dependency appears to be a zip file from its first bytes + * @return whether or not the given dependency appears to be a zip file from + * its first bytes */ private boolean isZipFile(final Dependency dependency) { final byte[] buffer = new byte[4]; try (final FileInputStream fileInputStream = new FileInputStream(dependency.getActualFilePath())) { fileInputStream.read(buffer); - if (Arrays.equals(buffer, ZIP_FIRST_BYTES) || Arrays.equals(buffer, ZIP_EMPTY_FIRST_BYTES) || - Arrays.equals(buffer, ZIP_SPANNED_FIRST_BYTES)) { + if (Arrays.equals(buffer, ZIP_FIRST_BYTES) || Arrays.equals(buffer, ZIP_EMPTY_FIRST_BYTES) + || Arrays.equals(buffer, ZIP_SPANNED_FIRST_BYTES)) { return true; } - } - catch (Exception e) { + } catch (Exception e) { LOGGER.warn("Unable to check if '{}' is a zip file", dependency.getActualFilePath()); LOGGER.trace("", e); } @@ -911,13 +916,14 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the JarAnalyzer. * + * @param engine a reference to the dependency-check engine * @throws InitializationException is thrown if there is an exception * creating a temporary directory */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { try { - final File baseDir = Settings.getTempDirectory(); + final File baseDir = getSettings().getTempDirectory(); tempFileLocation = File.createTempFile("check", "tmp", baseDir); if (!tempFileLocation.delete()) { final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath()); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java index b6eae2a1d..9dda549ab 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java @@ -95,7 +95,18 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { /** * Field indicating if the analyzer is enabled. */ - private final boolean enabled = checkEnabled(); + private boolean enabled = true; + + /** + * Initializes the analyzer with the configured settings. + * + * @param settings the configured settings to use + */ + @Override + public void initializeSettings(Settings settings) { + super.initializeSettings(settings); + enabled = checkEnabled(); + } /** * Determines if this analyzer is enabled @@ -110,8 +121,8 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { */ boolean retval = false; try { - if (!DEFAULT_URL.equals(Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL)) - && Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)) { + if (!DEFAULT_URL.equals(getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL)) + && getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)) { LOGGER.info("Enabling Nexus analyzer"); retval = true; } else { @@ -137,25 +148,25 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer once before any analysis is performed. * + * @param engine a reference to the dependency-check engine * @throws InitializationException if there's an error during initialization */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { LOGGER.debug("Initializing Nexus Analyzer"); LOGGER.debug("Nexus Analyzer enabled: {}", isEnabled()); if (isEnabled()) { final boolean useProxy = useProxy(); - final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); - LOGGER.debug("Nexus Analyzer URL: {}", searchUrl); + LOGGER.debug("Using proxy: {}", useProxy); try { - searcher = new NexusSearch(new URL(searchUrl), useProxy); + searcher = new NexusSearch(getSettings(), useProxy); if (!searcher.preflightRequest()) { setEnabled(false); throw new InitializationException("There was an issue getting Nexus status. Disabling analyzer."); } } catch (MalformedURLException mue) { setEnabled(false); - throw new InitializationException("Malformed URL to Nexus: " + searchUrl, mue); + throw new InitializationException("Malformed URL to Nexus", mue); } } } @@ -232,7 +243,7 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { if (!pomAnalyzed && ma.getPomUrl() != null) { File pomFile = null; try { - final File baseDir = Settings.getTempDirectory(); + final File baseDir = getSettings().getTempDirectory(); pomFile = File.createTempFile("pom", ".xml", baseDir); if (!pomFile.delete()) { LOGGER.warn("Unable to fetch pom.xml for {} from Nexus repository; " @@ -240,7 +251,8 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { LOGGER.debug("Unable to delete temp file"); } LOGGER.debug("Downloading {}", ma.getPomUrl()); - Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); + Downloader downloader = new Downloader(getSettings()); + downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); PomUtils.analyzePOM(dependency, pomFile); } catch (DownloadFailedException ex) { LOGGER.warn("Unable to download pom.xml for {} from Nexus repository; " @@ -266,14 +278,14 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Determine if a proxy should be used. + * Determine if a proxy should be used for the Nexus Analyzer. * * @return {@code true} if a proxy should be used */ - public static boolean useProxy() { + public boolean useProxy() { try { - return Settings.getString(Settings.KEYS.PROXY_SERVER) != null - && Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); + return getSettings().getString(Settings.KEYS.PROXY_SERVER) != null + && getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY); } catch (InvalidSettingException ise) { LOGGER.warn("Failed to parse proxy settings.", ise); return false; diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java index ffd94fa7c..9bda92357 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java @@ -85,7 +85,7 @@ public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer { } @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // NO-OP } @@ -123,7 +123,7 @@ public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer { @Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File file = dependency.getActualFile(); - if (!file.isFile() || file.length()==0) { + if (!file.isFile() || file.length() == 0) { return; } try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NspAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NspAnalyzer.java index 5fe536afc..0eb1f3690 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NspAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NspAnalyzer.java @@ -100,17 +100,17 @@ public class NspAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer once before any analysis is performed. * + * @param engine a reference to the dependency-check engine * @throws InitializationException if there's an error during initialization */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { LOGGER.debug("Initializing {}", getName()); - final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NSP_URL, DEFAULT_URL); try { - searcher = new NspSearch(new URL(searchUrl)); + searcher = new NspSearch(getSettings()); } catch (MalformedURLException ex) { setEnabled(false); - throw new InitializationException("The configured URL to Node Security Platform is malformed: " + searchUrl, ex); + throw new InitializationException("The configured URL to Node Security Platform is malformed", ex); } } @@ -148,7 +148,7 @@ public class NspAnalyzer extends AbstractFileTypeAnalyzer { @Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File file = dependency.getActualFile(); - if (!file.isFile() || file.length()==0) { + if (!file.isFile() || file.length() == 0) { return; } try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) { @@ -276,8 +276,8 @@ public class NspAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Processes a part of package.json (as defined by JsonArray) and update - * the specified dependency with relevant info. + * Processes a part of package.json (as defined by JsonArray) and update the + * specified dependency with relevant info. * * @param dependency the Dependency to update * @param jsonArray the jsonArray to parse diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java index 1aefe1129..72f56c47a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java @@ -69,10 +69,11 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer { /** * Initializes the analyzer once before any analysis is performed. * + * @param engine a reference to the dependency-check engine * @throws InitializationException if there's an error during initialization */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { //nothing to initialize } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NvdCveAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NvdCveAnalyzer.java index c3cdedf2f..69da7f193 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NvdCveAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NvdCveAnalyzer.java @@ -50,19 +50,6 @@ public class NvdCveAnalyzer extends AbstractAnalyzer { */ private CveDB cveDB; - /** - * Opens the data source. - * - * @throws SQLException thrown when there is a SQL Exception - * @throws IOException thrown when there is an IO Exception - * @throws DatabaseException thrown when there is a database exceptions - * @throws ClassNotFoundException thrown if the h2 database driver cannot be - * loaded - */ - public void open() throws SQLException, IOException, DatabaseException, ClassNotFoundException { - cveDB = CveDB.getInstance(); - } - /** * Closes the data source. */ @@ -150,25 +137,12 @@ public class NvdCveAnalyzer extends AbstractAnalyzer { /** * Opens the database used to gather NVD CVE data. * + * @param engine a reference the dependency-check engine * @throws InitializationException is thrown if there is an issue opening * the index. */ @Override - public void initializeAnalyzer() throws InitializationException { - try { - this.open(); - } catch (SQLException ex) { - LOGGER.debug("SQL Exception initializing NvdCveAnalyzer", ex); - throw new InitializationException(ex); - } catch (IOException ex) { - LOGGER.debug("IO Exception initializing NvdCveAnalyzer", ex); - throw new InitializationException(ex); - } catch (DatabaseException ex) { - LOGGER.debug("Database Exception initializing NvdCveAnalyzer", ex); - throw new InitializationException(ex); - } catch (ClassNotFoundException ex) { - LOGGER.debug("Exception initializing NvdCveAnalyzer", ex); - throw new InitializationException(ex); - } + public void initializeAnalyzer(Engine engine) throws InitializationException { + this.cveDB = engine.getDatabase(); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java index 308f81f3d..2506b0d66 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java @@ -146,10 +146,11 @@ public class OpenSSLAnalyzer extends AbstractFileTypeAnalyzer { /** * No-op initializer implementation. * + * @param engine a reference to the dependency-check engine * @throws InitializationException never thrown */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // Nothing to do here. } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java index 551279eb7..b15e304cc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java @@ -241,13 +241,14 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { /** * Makes sure a usable temporary directory is available. * + * @param engine a reference to the dependency-check engine * @throws InitializationException an AnalyzeException is thrown when the * temp directory cannot be created */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { try { - final File baseDir = Settings.getTempDirectory(); + final File baseDir = getSettings().getTempDirectory(); tempFileLocation = File.createTempFile("check", "tmp", baseDir); if (!tempFileLocation.delete()) { setEnabled(false); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java index 12e58d3f4..787dd4598 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java @@ -143,10 +143,11 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { /** * No-op initializer implementation. * + * @param engine a reference to the dependency-check engine * @throws InitializationException never thrown */ @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // Nothing to do here. } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java index 45cfd7955..7b5bb4301 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java @@ -90,7 +90,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { /** * The DAL. */ - private CveDB cvedb; + private CveDB cvedb = null; /** * @return a filter that accepts files named Gemfile.lock @@ -113,7 +113,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); } final List args = new ArrayList<>(); - final String bundleAuditPath = Settings.getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH); + final String bundleAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH); File bundleAudit = null; if (bundleAuditPath != null) { bundleAudit = new File(bundleAuditPath); @@ -140,22 +140,18 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { * Initialize the analyzer. In this case, extract GrokAssembly.exe to a * temporary location. * + * @param engine a reference to the dependency-check engine * @throws InitializationException if anything goes wrong */ @Override - public void initializeFileTypeAnalyzer() throws InitializationException { - try { - cvedb = CveDB.getInstance(); - } catch (DatabaseException ex) { - LOGGER.warn("Exception opening the database"); - LOGGER.debug("error", ex); - setEnabled(false); - throw new InitializationException("Error connecting to the database", ex); - } + public void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // Now, need to see if bundle-audit actually runs from this location. + if (engine != null) { + this.cvedb = engine.getDatabase(); + } Process process = null; try { - process = launchBundleAudit(Settings.getTempDirectory()); + process = launchBundleAudit(getSettings().getTempDirectory()); } catch (AnalysisException ae) { setEnabled(false); @@ -208,17 +204,6 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { } } - /** - * Closes the data source. - */ - @Override - public void closeAnalyzer() { - if (cvedb != null) { - cvedb.close(); - cvedb = null; - } - } - /** * Returns the name of the analyzer. * @@ -413,13 +398,21 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { final String criticality = nextLine.substring(CRITICALITY.length()).trim(); float score = -1.0f; Vulnerability v = null; - try { - v = cvedb.getVulnerability(vulnerability.getName()); - } catch (DatabaseException ex) { - LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName()); + if (cvedb != null) { + try { + v = cvedb.getVulnerability(vulnerability.getName()); + } catch (DatabaseException ex) { + LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName()); + } } if (v != null) { score = v.getCvssScore(); + vulnerability.setCvssAccessComplexity(v.getCvssAccessComplexity()); + vulnerability.setCvssAccessVector(v.getCvssAccessVector()); + vulnerability.setCvssAuthentication(v.getCvssAuthentication()); + vulnerability.setCvssAvailabilityImpact(v.getCvssAvailabilityImpact()); + vulnerability.setCvssConfidentialityImpact(v.getCvssConfidentialityImpact()); + vulnerability.setCvssIntegrityImpact(v.getCvssIntegrityImpact()); } else if ("High".equalsIgnoreCase(criticality)) { score = 8.5f; } else if ("Medium".equalsIgnoreCase(criticality)) { @@ -477,7 +470,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { * @throws IOException thrown if a temporary gem file could not be written */ private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String filePath, String gem) throws IOException { - final File gemFile = new File(Settings.getTempDirectory(), gem + "_Gemfile.lock"); + final File gemFile = new File(getSettings().getTempDirectory(), gem + "_Gemfile.lock"); if (!gemFile.createNewFile()) { throw new IOException("Unable to create temporary gem file"); } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzer.java index b600236d2..b79a0e231 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzer.java @@ -89,7 +89,7 @@ public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer { } @Override - protected void initializeFileTypeAnalyzer() throws InitializationException { + protected void initializeFileTypeAnalyzer(Engine engine) throws InitializationException { // NO-OP } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/SwiftPackageManagerAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/SwiftPackageManagerAnalyzer.java index 5823d8aaf..5dda68202 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/SwiftPackageManagerAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/SwiftPackageManagerAnalyzer.java @@ -80,7 +80,7 @@ public class SwiftPackageManagerAnalyzer extends AbstractFileTypeAnalyzer { } @Override - protected void initializeFileTypeAnalyzer() { + protected void initializeFileTypeAnalyzer(Engine engine) { // NO-OP } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java index 314e321fb..fd81c65f7 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java @@ -20,6 +20,7 @@ package org.owasp.dependencycheck.data.central; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; @@ -60,16 +61,25 @@ public class CentralSearch { * Used for logging. */ private static final Logger LOGGER = LoggerFactory.getLogger(CentralSearch.class); + /** + * The configured settings. + */ + private final Settings settings; /** * Creates a NexusSearch for the given repository URL. * - * @param rootURL the URL of the repository on which searches should - * execute. Only parameters are added to this (so it should end in /select) + * @param settings the configured settings + * @throws java.net.MalformedURLException thrown if the configured URL is + * invalid */ - public CentralSearch(URL rootURL) { - this.rootURL = rootURL; - if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)) { + public CentralSearch(Settings settings) throws MalformedURLException { + this.settings = settings; + + final String searchUrl = settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL); + LOGGER.debug("Central Search URL: {}", searchUrl); + this.rootURL = new URL(searchUrl); + if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) { useProxy = true; LOGGER.debug("Using proxy"); } else { @@ -101,7 +111,8 @@ public class CentralSearch { // 1) If the proxy is set, AND the setting is set to true, use the proxy // 2) Otherwise, don't use the proxy (either the proxy isn't configured, // or proxy is specifically set to false) - final HttpURLConnection conn = URLConnectionFactory.createHttpURLConnection(url, useProxy); + final URLConnectionFactory factory = new URLConnectionFactory(settings); + final HttpURLConnection conn = factory.createHttpURLConnection(url, useProxy); conn.setDoOutput(true); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java index 09567475f..07c0b23ac 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java @@ -20,12 +20,14 @@ package org.owasp.dependencycheck.data.nexus; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.URLConnectionFactory; import org.owasp.dependencycheck.utils.XmlUtils; @@ -50,6 +52,10 @@ public class NexusSearch { * Whether to use the Proxy when making requests. */ private final boolean useProxy; + /** + * The configured settings. + */ + private final Settings settings; /** * Used for logging. */ @@ -58,15 +64,18 @@ public class NexusSearch { /** * Creates a NexusSearch for the given repository URL. * - * @param rootURL the root URL of the repository on which searches should - * execute. full URL's are calculated relative to this URL, so it should end - * with a / + * @param settings the configured settings * @param useProxy flag indicating if the proxy settings should be used + * @throws java.net.MalformedURLException thrown if the configured URL is invalid */ - public NexusSearch(URL rootURL, boolean useProxy) { - this.rootURL = rootURL; + public NexusSearch(Settings settings, boolean useProxy) throws MalformedURLException { + this.settings = settings; this.useProxy = useProxy; - LOGGER.debug("Using proxy: {}", useProxy); + + final String searchUrl = settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); + LOGGER.debug("Nexus Search URL: {}", searchUrl); + this.rootURL = new URL(searchUrl); + } /** @@ -94,7 +103,8 @@ public class NexusSearch { // 2) Otherwise, don't use the proxy (either the proxy isn't configured, // or proxy is specifically set to false HttpURLConnection conn; - conn = URLConnectionFactory.createHttpURLConnection(url, useProxy); + URLConnectionFactory factory = new URLConnectionFactory(settings); + conn = factory.createHttpURLConnection(url, useProxy); conn.setDoOutput(true); // JSON would be more elegant, but there's not currently a dependency @@ -159,7 +169,8 @@ public class NexusSearch { HttpURLConnection conn; try { final URL url = new URL(rootURL, "status"); - conn = URLConnectionFactory.createHttpURLConnection(url, useProxy); + URLConnectionFactory factory = new URLConnectionFactory(settings); + conn = factory.createHttpURLConnection(url, useProxy); conn.addRequestProperty("Accept", "application/xml"); conn.connect(); if (conn.getResponseCode() != 200) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nsp/NspSearch.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nsp/NspSearch.java index e3ed19024..afc747c38 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nsp/NspSearch.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nsp/NspSearch.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -36,6 +37,7 @@ import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; +import static org.owasp.dependencycheck.analyzer.NspAnalyzer.DEFAULT_URL; import org.owasp.dependencycheck.utils.URLConnectionFailureException; /** @@ -54,7 +56,10 @@ public class NspSearch { * Whether to use the Proxy when making requests. */ private final boolean useProxy; - + /** + * The configured settings. + */ + private final Settings settings; /** * Used for logging. */ @@ -63,11 +68,16 @@ public class NspSearch { /** * Creates a NspSearch for the given repository URL. * - * @param nspCheckUrl the URL to the public NSP check API + * @param settings the configured settings + * @throws java.net.MalformedURLException thrown if the configured URL is + * invalid */ - public NspSearch(URL nspCheckUrl) { - this.nspCheckUrl = nspCheckUrl; - if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)) { + public NspSearch(Settings settings) throws MalformedURLException { + final String searchUrl = settings.getString(Settings.KEYS.ANALYZER_NSP_URL, DEFAULT_URL); + LOGGER.debug("NSP Search URL: {}", searchUrl); + this.nspCheckUrl = new URL(searchUrl); + this.settings = settings; + if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) { useProxy = true; LOGGER.debug("Using proxy"); } else { @@ -90,8 +100,8 @@ public class NspSearch { try { final List result = new ArrayList<>(); final byte[] packageDatabytes = packageJson.toString().getBytes(StandardCharsets.UTF_8); - - final HttpURLConnection conn = URLConnectionFactory.createHttpURLConnection(nspCheckUrl, useProxy); + final URLConnectionFactory factory = new URLConnectionFactory(settings); + final HttpURLConnection conn = factory.createHttpURLConnection(nspCheckUrl, useProxy); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java index e7a815c4c..942bb3b3d 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java @@ -50,10 +50,6 @@ public final class ConnectionFactory { * The Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionFactory.class); - /** - * The version of the current DB Schema. - */ - public static final String DB_SCHEMA_VERSION = Settings.getString(Settings.KEYS.DB_VERSION); /** * Resource location for SQL file used to create the database schema. */ @@ -69,29 +65,36 @@ public final class ConnectionFactory { /** * The database driver used to connect to the database. */ - private static Driver driver = null; + private Driver driver = null; /** * The database connection string. */ - private static String connectionString = null; + private String connectionString = null; /** * The username to connect to the database. */ - private static String userName = null; + private String userName = null; /** * The password for the database. */ - private static String password = null; + private String password = null; /** * Counter to ensure that calls to ensureSchemaVersion does not end up in an * endless loop. */ - private static int callDepth = 0; + private int callDepth = 0; + /** + * The configured settings. + */ + private final Settings settings; /** * Private constructor for this factory class; no instance is ever needed. + * + * @param settings the configured settings */ - private ConnectionFactory() { + public ConnectionFactory(Settings settings) { + this.settings = settings; } /** @@ -101,7 +104,7 @@ public final class ConnectionFactory { * @throws DatabaseException thrown if we are unable to connect to the * database */ - public static void initialize() throws DatabaseException { + public void initialize() throws DatabaseException { //this only needs to be called once. if (connectionString != null) { return; @@ -109,10 +112,10 @@ public final class ConnectionFactory { Connection conn = null; try { //load the driver if necessary - final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, ""); - if (!driverName.isEmpty()) { //likely need to load the correct driver + final String driverName = settings.getString(Settings.KEYS.DB_DRIVER_NAME, ""); + if (!driverName.isEmpty()) { LOGGER.debug("Loading driver: {}", driverName); - final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, ""); + final String driverPath = settings.getString(Settings.KEYS.DB_DRIVER_PATH, ""); try { if (!driverPath.isEmpty()) { LOGGER.debug("Loading driver from: {}", driverPath); @@ -125,11 +128,11 @@ public final class ConnectionFactory { throw new DatabaseException("Unable to load database driver", ex); } } - userName = Settings.getString(Settings.KEYS.DB_USER, "dcuser"); + userName = settings.getString(Settings.KEYS.DB_USER, "dcuser"); //yes, yes - hard-coded password - only if there isn't one in the properties file. - password = Settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!"); + password = settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!"); try { - connectionString = Settings.getConnectionString( + connectionString = settings.getConnectionString( Settings.KEYS.DB_CONNECTION_STRING, Settings.KEYS.DB_FILE_NAME); } catch (IOException ex) { @@ -158,7 +161,7 @@ public final class ConnectionFactory { connectionString = connectionString.replace("AUTO_SERVER=TRUE;", ""); try { conn = DriverManager.getConnection(connectionString, userName, password); - Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString); + settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString); LOGGER.debug("Unable to start the database in server mode; reverting to single user mode"); } catch (SQLException sqlex) { LOGGER.debug("Unable to connect to the database", ex); @@ -201,16 +204,9 @@ public final class ConnectionFactory { * finalize method being called as during shutdown the class loader used to * load the driver may be unloaded prior to the driver being de-registered. */ - public static void cleanup() { + public void cleanup() { if (driver != null) { - try { - DriverManager.deregisterDriver(driver); - } catch (SQLException ex) { - LOGGER.debug("An error occurred unloading the database driver", ex); - } catch (Throwable unexpected) { - LOGGER.debug( - "An unexpected throwable occurred unloading the database driver", unexpected); - } + DriverLoader.cleanup(driver); driver = null; } connectionString = null; @@ -226,7 +222,7 @@ public final class ConnectionFactory { * @throws DatabaseException thrown if there is an exception loading the * database connection */ - public static Connection getConnection() throws DatabaseException { + public Connection getConnection() throws DatabaseException { initialize(); Connection conn = null; try { @@ -246,9 +242,21 @@ public final class ConnectionFactory { * @throws IOException thrown if the data directory does not exist and * cannot be created */ - public static boolean h2DataFileExists() throws IOException { - final File dir = Settings.getDataDirectory(); - final String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME); + public boolean h2DataFileExists() throws IOException { + return h2DataFileExists(settings); + } + /** + * Determines if the H2 database file exists. If it does not exist then the + * data structure will need to be created. + * + * @param configuration the configured settings + * @return true if the H2 database file does not exist; otherwise false + * @throws IOException thrown if the data directory does not exist and + * cannot be created + */ + public static boolean h2DataFileExists(Settings configuration) throws IOException { + final File dir = configuration.getDataDirectory(); + final String fileName = configuration.getString(Settings.KEYS.DB_FILE_NAME); final File file = new File(dir, fileName); return file.exists(); } @@ -258,10 +266,20 @@ public final class ConnectionFactory { * * @return true if the connection string is for an H2 database */ - public static boolean isH2Connection() { + public boolean isH2Connection() { + return isH2Connection(settings); + } + + /** + * Determines if the connection string is for an H2 database. + * + * @param configuration the configured settings + * @return true if the connection string is for an H2 database + */ + public static boolean isH2Connection(Settings configuration) { String connStr; try { - connStr = Settings.getConnectionString( + connStr = configuration.getConnectionString( Settings.KEYS.DB_CONNECTION_STRING, Settings.KEYS.DB_FILE_NAME); } catch (IOException ex) { @@ -278,7 +296,7 @@ public final class ConnectionFactory { * @param conn the database connection * @throws DatabaseException thrown if there is a Database Exception */ - private static void createTables(Connection conn) throws DatabaseException { + private void createTables(Connection conn) throws DatabaseException { LOGGER.debug("Creating database structure"); InputStream is = null; try { @@ -315,7 +333,7 @@ public final class ConnectionFactory { * @throws DatabaseException thrown if there is an exception upgrading the * database schema */ - private static void updateSchema(Connection conn, DependencyVersion appExpectedVersion, DependencyVersion currentDbVersion) + private void updateSchema(Connection conn, DependencyVersion appExpectedVersion, DependencyVersion currentDbVersion) throws DatabaseException { final String databaseProductName; @@ -363,7 +381,7 @@ public final class ConnectionFactory { final int c1 = Integer.parseInt(currentDbVersion.getVersionParts().get(1)); if (e0 == c0 && e1 < c1) { LOGGER.warn("A new version of dependency-check is available; consider upgrading"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); + settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); } else if (e0 == c0 && e1 == c1) { //do nothing - not sure how we got here, but just in case... } else { @@ -382,7 +400,7 @@ public final class ConnectionFactory { * @throws DatabaseException thrown if the schema version is not compatible * with this version of dependency-check */ - private static void ensureSchemaVersion(Connection conn) throws DatabaseException { + private void ensureSchemaVersion(Connection conn) throws DatabaseException { ResultSet rs = null; PreparedStatement ps = null; try { @@ -390,7 +408,8 @@ public final class ConnectionFactory { ps = conn.prepareStatement("SELECT value FROM properties WHERE id = 'version'"); rs = ps.executeQuery(); if (rs.next()) { - final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(DB_SCHEMA_VERSION); + final String dbSchemaVersion = settings.getString(Settings.KEYS.DB_VERSION); + final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(dbSchemaVersion); if (appDbVersion == null) { throw new DatabaseException("Invalid application database schema"); } @@ -399,7 +418,7 @@ public final class ConnectionFactory { throw new DatabaseException("Invalid database schema"); } if (appDbVersion.compareTo(db) > 0) { - LOGGER.debug("Current Schema: {}", DB_SCHEMA_VERSION); + LOGGER.debug("Current Schema: {}", dbSchemaVersion); LOGGER.debug("DB Schema: {}", rs.getString(1)); updateSchema(conn, appDbVersion, db); if (++callDepth < 10) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java index c4b08cde3..7d4baa35b 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java @@ -17,6 +17,7 @@ */ package org.owasp.dependencycheck.data.nvdcve; +import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Connection; @@ -64,19 +65,14 @@ import static org.owasp.dependencycheck.data.nvdcve.CveDB.PreparedStatementCveDb @ThreadSafe public final class CveDB implements AutoCloseable { - /** - * Singleton instance of the CveDB. - */ - private static CveDB instance = null; - /** - * Track the number of current users of the CveDB; so that if someone is - * using database another user cannot close the connection on them. - */ - private int usageCount = 0; /** * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(CveDB.class); + /** + * The database connection factory. + */ + private final ConnectionFactory connectionFactory; /** * Database connection */ @@ -100,6 +96,10 @@ public final class CveDB implements AutoCloseable { */ @SuppressWarnings("unchecked") private final Map> vulnerabilitiesForCpeCache = Collections.synchronizedMap(new ReferenceMap(HARD, SOFT)); + /** + * The configured settings + */ + private final Settings settings; /** * The enum value names must match the keys of the statements in the @@ -196,31 +196,19 @@ public final class CveDB implements AutoCloseable { UPDATE_VULNERABILITY } - /** - * Gets the CveDB singleton object. - * - * @return the CveDB singleton - * @throws DatabaseException thrown if there is a database error - */ - public static synchronized CveDB getInstance() throws DatabaseException { - if (instance == null) { - instance = new CveDB(); - } - if (!instance.isOpen()) { - instance.open(); - } - instance.usageCount += 1; - return instance; - } - /** * Creates a new CveDB object and opens the database connection. Note, the * connection must be closed by the caller by calling the close method. * + * @param settings the configured settings * @throws DatabaseException thrown if there is an exception opening the * database. */ - private CveDB() throws DatabaseException { + public CveDB(Settings settings) throws DatabaseException { + this.settings = settings; + connectionFactory = new ConnectionFactory(settings); + connectionFactory.initialize(); + open(); } /** @@ -229,7 +217,7 @@ public final class CveDB implements AutoCloseable { * @param conn the database connection * @return the product name of the database if successful, {@code null} else */ - private static String determineDatabaseProductName(Connection conn) { + private String determineDatabaseProductName(Connection conn) { try { final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase(); LOGGER.debug("Database product: {}", databaseProductName); @@ -240,16 +228,6 @@ public final class CveDB implements AutoCloseable { } } - /** - * Method added for testing, returns the current usage count of the CveDB - * singleton. - * - * @return the current usage of the CveDB singleton - */ - protected synchronized int getUsageCount() { - return usageCount; - } - /** * Opens the database connection. If the database does not exist, it will * create a new one. @@ -259,14 +237,14 @@ public final class CveDB implements AutoCloseable { */ private synchronized void open() throws DatabaseException { try { - if (!instance.isOpen()) { - instance.connection = ConnectionFactory.getConnection(); - final String databaseProductName = determineDatabaseProductName(instance.connection); - instance.statementBundle = databaseProductName != null + if (!isOpen()) { + connection = connectionFactory.getConnection(); + final String databaseProductName = determineDatabaseProductName(this.connection); + statementBundle = databaseProductName != null ? ResourceBundle.getBundle("data/dbStatements", new Locale(databaseProductName)) : ResourceBundle.getBundle("data/dbStatements"); - instance.prepareStatements(); - instance.databaseProperties = new DatabaseProperties(instance); + prepareStatements(); + databaseProperties = new DatabaseProperties(this); } } catch (DatabaseException e) { releaseResources(); @@ -280,23 +258,20 @@ public final class CveDB implements AutoCloseable { */ @Override public synchronized void close() { - if (instance != null) { - instance.usageCount -= 1; - if (instance.usageCount <= 0 && instance.isOpen()) { - instance.usageCount = 0; - clearCache(); - instance.closeStatements(); - try { - instance.connection.close(); - } catch (SQLException ex) { - LOGGER.error("There was an error attempting to close the CveDB, see the log for more details."); - LOGGER.debug("", ex); - } catch (Throwable ex) { - LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details."); - LOGGER.debug("", ex); - } - releaseResources(); + if (isOpen()) { + clearCache(); + closeStatements(); + try { + connection.close(); + } catch (SQLException ex) { + LOGGER.error("There was an error attempting to close the CveDB, see the log for more details."); + LOGGER.debug("", ex); + } catch (Throwable ex) { + LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details."); + LOGGER.debug("", ex); } + releaseResources(); + connectionFactory.cleanup(); } } @@ -304,10 +279,10 @@ public final class CveDB implements AutoCloseable { * Releases the resources used by CveDB. */ private synchronized void releaseResources() { - instance.statementBundle = null; - instance.preparedStatements.clear(); - instance.databaseProperties = null; - instance.connection = null; + statementBundle = null; + preparedStatements.clear(); + databaseProperties = null; + connection = null; } /** @@ -836,15 +811,15 @@ public final class CveDB implements AutoCloseable { } catch (Exception ex) { String dd; try { - dd = Settings.getDataDirectory().getAbsolutePath(); + dd = settings.getDataDirectory().getAbsolutePath(); } catch (IOException ex1) { - dd = Settings.getString(Settings.KEYS.DATA_DIRECTORY); + dd = settings.getString(Settings.KEYS.DATA_DIRECTORY); } LOGGER.error("Unable to access the local database.\n\nEnsure that '{}' is a writable directory. " + "If the problem persist try deleting the files in '{}' and running {} again. If the problem continues, please " + "create a log file (see documentation at http://jeremylong.github.io/DependencyCheck/) and open a ticket at " + "https://github.com/jeremylong/DependencyCheck/issues and include the log file.\n\n", - dd, dd, Settings.getString(Settings.KEYS.APPLICATION_NAME)); + dd, dd, settings.getString(Settings.KEYS.APPLICATION_NAME)); LOGGER.debug("", ex); } finally { DBUtils.closeResultSet(rs); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java index 1c61fcde9..ac8d49e17 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java @@ -44,6 +44,21 @@ public final class DriverLoader { */ private static final Logger LOGGER = LoggerFactory.getLogger(DriverLoader.class); + /** + * De-registers the driver. + * + * @param driver the driver to de-register + */ + public static void cleanup(Driver driver) { + try { + DriverManager.deregisterDriver(driver); + } catch (SQLException ex) { + LOGGER.debug("An error occurred unloading the database driver", ex); + } catch (Throwable unexpected) { + LOGGER.debug("An unexpected throwable occurred unloading the database driver", unexpected); + } + } + /** * Private constructor for a utility class. */ @@ -51,25 +66,30 @@ public final class DriverLoader { } /** - * Loads the specified class using the system class loader and registers the driver with the driver manager. + * Loads the specified class using the system class loader and registers the + * driver with the driver manager. * * @param className the fully qualified name of the desired class * @return the loaded Driver * @throws DriverLoadException thrown if the driver cannot be loaded */ public static Driver load(String className) throws DriverLoadException { - final ClassLoader loader = DriverLoader.class.getClassLoader(); //ClassLoader.getSystemClassLoader(); + final ClassLoader loader = DriverLoader.class.getClassLoader(); return load(className, loader); } /** - * Loads the specified class by registering the supplied paths to the class loader and then registers the driver with the - * driver manager. The pathToDriver argument is added to the class loader so that an external driver can be loaded. Note, the - * pathToDriver can contain a semi-colon separated list of paths so any dependencies can be added as needed. If a path in the - * pathToDriver argument is a directory all files in the directory are added to the class path. + * Loads the specified class by registering the supplied paths to the class + * loader and then registers the driver with the driver manager. The + * pathToDriver argument is added to the class loader so that an external + * driver can be loaded. Note, the pathToDriver can contain a semi-colon + * separated list of paths so any dependencies can be added as needed. If a + * path in the pathToDriver argument is a directory all files in the + * directory are added to the class path. * * @param className the fully qualified name of the desired class - * @param pathToDriver the path to the JAR file containing the driver; note, this can be a semi-colon separated list of paths + * @param pathToDriver the path to the JAR file containing the driver; note, + * this can be a semi-colon separated list of paths * @return the loaded Driver * @throws DriverLoadException thrown if the driver cannot be loaded */ @@ -113,7 +133,8 @@ public final class DriverLoader { } /** - * Loads the specified class using the supplied class loader and registers the driver with the driver manager. + * Loads the specified class using the supplied class loader and registers + * the driver with the driver manager. * * @param className the fully qualified name of the desired class * @param loader the class loader to use when loading the driver @@ -125,6 +146,10 @@ public final class DriverLoader { final Class c = Class.forName(className, true, loader); //final Class c = loader.loadClass(className); final Driver driver = (Driver) c.newInstance(); + + //TODO add usage count so we don't de-register a driver that is in use. + + final Driver shim = new DriverShim(driver); //using the DriverShim to get around the fact that the DriverManager won't register a driver not in the base class path DriverManager.registerDriver(shim); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CachedWebDataSource.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CachedWebDataSource.java index 4445cbce8..c66ac6af8 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CachedWebDataSource.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CachedWebDataSource.java @@ -17,21 +17,25 @@ */ package org.owasp.dependencycheck.data.update; +import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.data.update.exception.UpdateException; /** - * Defines a data source who's data is retrieved from the Internet. This data can be downloaded and the local cache - * updated. + * Defines a data source who's data is retrieved from the Internet. This data + * can be downloaded and the local cache updated. * * @author Jeremy Long */ public interface CachedWebDataSource { /** - * Determines if an update to the current data store is needed, if it is the new data is downloaded from the - * Internet and imported into the current cached data store. + * Determines if an update to the current data store is needed, if it is the + * new data is downloaded from the Internet and imported into the current + * cached data store. * - * @throws UpdateException is thrown if there is an exception downloading the data or updating the data store. + * @param engine a reference to the dependency-check engine + * @throws UpdateException is thrown if there is an exception downloading + * the data or updating the data store. */ - void update() throws UpdateException; + void update(Engine engine) throws UpdateException; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/EngineVersionCheck.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/EngineVersionCheck.java index 2bd2eb5ef..fb1c5f101 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/EngineVersionCheck.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/EngineVersionCheck.java @@ -22,6 +22,7 @@ import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.IOUtils; +import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; @@ -62,6 +63,25 @@ public class EngineVersionCheck implements CachedWebDataSource { * against. */ private String updateToVersion; + /** + * The configured settings. + */ + private Settings settings; + + /** + * Constructs a new engine version check utility for testing. + * + * @param settings the configured settings + */ + protected EngineVersionCheck(Settings settings) { + this.settings = settings; + } + + /** + * Constructs a new engine version check utility. + */ + public EngineVersionCheck() { + } /** * Getter for updateToVersion - only used for testing. Represents the @@ -92,12 +112,14 @@ public class EngineVersionCheck implements CachedWebDataSource { * be updated */ @Override - public void update() throws UpdateException { - try (CveDB db = CveDB.getInstance()) { - final boolean autoupdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true); - final boolean enabled = Settings.getBoolean(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, true); - final String original = Settings.getString(Settings.KEYS.CVE_ORIGINAL_MODIFIED_20_URL); - final String current = Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL); + public void update(Engine engine) throws UpdateException { + this.settings = engine.getSettings(); + try { + CveDB db = engine.getDatabase(); + final boolean autoupdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true); + final boolean enabled = settings.getBoolean(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, true); + final String original = settings.getString(Settings.KEYS.CVE_ORIGINAL_MODIFIED_20_URL); + final String current = settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL); /* * Only update if auto-update is enabled, the engine check is * enabled, and the NVD CVE URLs have not been modified (i.e. the @@ -111,7 +133,7 @@ public class EngineVersionCheck implements CachedWebDataSource { final long lastChecked = Long.parseLong(properties.getProperty(ENGINE_VERSION_CHECKED_ON, "0")); final long now = System.currentTimeMillis(); updateToVersion = properties.getProperty(CURRENT_ENGINE_RELEASE, ""); - final String currentVersion = Settings.getString(Settings.KEYS.APPLICATION_VERSION, "0.0.0"); + final String currentVersion = settings.getString(Settings.KEYS.APPLICATION_VERSION, "0.0.0"); LOGGER.debug("Last checked: {}", lastChecked); LOGGER.debug("Now: {}", now); LOGGER.debug("Current version: {}", currentVersion); @@ -184,9 +206,10 @@ public class EngineVersionCheck implements CachedWebDataSource { protected String getCurrentReleaseVersion() { HttpURLConnection conn = null; try { - final String str = Settings.getString(Settings.KEYS.ENGINE_VERSION_CHECK_URL, "http://jeremylong.github.io/DependencyCheck/current.txt"); + final String str = settings.getString(Settings.KEYS.ENGINE_VERSION_CHECK_URL, "http://jeremylong.github.io/DependencyCheck/current.txt"); final URL url = new URL(str); - conn = URLConnectionFactory.createHttpURLConnection(url); + URLConnectionFactory factory = new URLConnectionFactory(settings); + conn = factory.createHttpURLConnection(url); conn.connect(); if (conn.getResponseCode() != 200) { return null; diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java index b5fc703cd..ceee65cd8 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java @@ -36,6 +36,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.data.nvdcve.ConnectionFactory; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.DatabaseException; @@ -85,7 +86,10 @@ public class NvdCveUpdater implements CachedWebDataSource { * very CPU-intense, e.g. downloading files. */ private ExecutorService downloadExecutorService = null; - + /** + * The configured settings. + */ + private Settings settings; /** * Reference to the DAO. */ @@ -101,19 +105,21 @@ public class NvdCveUpdater implements CachedWebDataSource { * prevent more then one thread/JVM from updating the database at the same * time. This method may sleep upto 5 minutes. * + * @param engine a reference to the dependency-check engine * @throws UpdateException is thrown if there is an error updating the * database */ @Override - public synchronized void update() throws UpdateException { + public synchronized void update(Engine engine) throws UpdateException { + this.settings = engine.getSettings(); + this.cveDb = engine.getDatabase(); if (isUpdateConfiguredFalse()) { return; } - H2DBLock dbupdate = new H2DBLock(); + H2DBLock dbupdate = new H2DBLock(settings, ConnectionFactory.isH2Connection(settings)); try { dbupdate.lock(); initializeExecutorServices(); - cveDb = CveDB.getInstance(); dbProperties = cveDb.getDatabaseProperties(); if (checkUpdate()) { @@ -127,7 +133,7 @@ public class NvdCveUpdater implements CachedWebDataSource { throw new UpdateException("NVD CVE properties files contain an invalid URL, unable to update the data to use the most current data.", ex); } catch (DownloadFailedException ex) { LOGGER.warn("Unable to download the NVD CVE data; the results may not include the most recent CPE/CVEs from the NVD."); - if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) { + if (settings.getString(Settings.KEYS.PROXY_SERVER) == null) { LOGGER.info("If you are behind a proxy you may need to configure dependency-check to use the proxy."); } throw new UpdateException("Unable to download the NVD CVE data.", ex); @@ -136,9 +142,6 @@ public class NvdCveUpdater implements CachedWebDataSource { } catch (H2DBLockException ex) { throw new UpdateException("Unable to obtain an exclusive lock on the H2 database to perform updates", ex); } finally { - if (cveDb != null) { - cveDb.close(); - } dbupdate.release(); shutdownExecutorServices(); } @@ -152,7 +155,7 @@ public class NvdCveUpdater implements CachedWebDataSource { */ private boolean isUpdateConfiguredFalse() { try { - if (!Settings.getBoolean(Settings.KEYS.UPDATE_NVDCVE_ENABLED, true)) { + if (!settings.getBoolean(Settings.KEYS.UPDATE_NVDCVE_ENABLED, true)) { return true; } } catch (InvalidSettingException ex) { @@ -160,7 +163,7 @@ public class NvdCveUpdater implements CachedWebDataSource { } boolean autoUpdate = true; try { - autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); + autoUpdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE); } catch (InvalidSettingException ex) { LOGGER.debug("Invalid setting for auto-update; using true."); } @@ -204,7 +207,7 @@ public class NvdCveUpdater implements CachedWebDataSource { private boolean checkUpdate() throws UpdateException { boolean proceed = true; // If the valid setting has not been specified, then we proceed to check... - final int validForHours = Settings.getInt(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, 0); + final int validForHours = settings.getInt(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, 0); if (dataExists() && 0 < validForHours) { // ms Valid = valid (hours) x 60 min/hour x 60 sec/min x 1000 ms/sec final long msValid = validForHours * 60L * 60L * 1000L; @@ -213,8 +216,7 @@ public class NvdCveUpdater implements CachedWebDataSource { proceed = (now - lastChecked) > msValid; if (!proceed) { LOGGER.info("Skipping NVD check since last check was within {} hours.", validForHours); - LOGGER.debug("Last NVD was at {}, and now {} is within {} ms.", - lastChecked, now, msValid); + LOGGER.debug("Last NVD was at {}, and now {} is within {} ms.", lastChecked, now, msValid); } } return proceed; @@ -226,11 +228,7 @@ public class NvdCveUpdater implements CachedWebDataSource { * @return true if the database contains data */ private boolean dataExists() { - try (CveDB cve = CveDB.getInstance()) { - return cve.dataExists(); - } catch (DatabaseException ex) { - return false; - } + return cveDb.dataExists(); } /** @@ -259,7 +257,7 @@ public class NvdCveUpdater implements CachedWebDataSource { final Set>> downloadFutures = new HashSet<>(maxUpdates); for (NvdCveInfo cve : updateable) { if (cve.getNeedsUpdate()) { - final DownloadTask call = new DownloadTask(cve, processingExecutorService, cveDb, Settings.getInstance()); + final DownloadTask call = new DownloadTask(cve, processingExecutorService, cveDb, settings); downloadFutures.add(downloadExecutorService.submit(call)); } } @@ -343,7 +341,7 @@ public class NvdCveUpdater implements CachedWebDataSource { } if (dbProperties != null && !dbProperties.isEmpty()) { try { - final int startYear = Settings.getInt(Settings.KEYS.CVE_START_YEAR, 2002); + final int startYear = settings.getInt(Settings.KEYS.CVE_START_YEAR, 2002); final int endYear = Calendar.getInstance().get(Calendar.YEAR); boolean needsFullUpdate = false; for (int y = startYear; y <= endYear; y++) { @@ -355,7 +353,7 @@ public class NvdCveUpdater implements CachedWebDataSource { final long lastUpdated = Long.parseLong(dbProperties.getProperty(DatabaseProperties.LAST_UPDATED, "0")); final long now = System.currentTimeMillis(); - final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7); + final int days = settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7); if (!needsFullUpdate && lastUpdated == updates.getTimeStamp(MODIFIED)) { updates.clear(); //we don't need to update anything. } else if (!needsFullUpdate && DateUtil.withinDateRange(lastUpdated, now, days)) { @@ -408,25 +406,24 @@ public class NvdCveUpdater implements CachedWebDataSource { private UpdateableNvdCve retrieveCurrentTimestampsFromWeb() throws MalformedURLException, DownloadFailedException, InvalidDataException, InvalidSettingException { - final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR); + final int start = settings.getInt(Settings.KEYS.CVE_START_YEAR); final int end = Calendar.getInstance().get(Calendar.YEAR); final Map lastModifiedDates = retrieveLastModifiedDates(start, end); final UpdateableNvdCve updates = new UpdateableNvdCve(); - final String baseUrl20 = Settings.getString(Settings.KEYS.CVE_SCHEMA_2_0); - final String baseUrl12 = Settings.getString(Settings.KEYS.CVE_SCHEMA_1_2); + final String baseUrl20 = settings.getString(Settings.KEYS.CVE_SCHEMA_2_0); + final String baseUrl12 = settings.getString(Settings.KEYS.CVE_SCHEMA_1_2); for (int i = start; i <= end; i++) { final String url = String.format(baseUrl20, i); updates.add(Integer.toString(i), url, String.format(baseUrl12, i), lastModifiedDates.get(url), true); } - final String url = Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL); - updates.add(MODIFIED, url, Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL), + final String url = settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL); + updates.add(MODIFIED, url, settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL), lastModifiedDates.get(url), false); - return updates; } @@ -446,16 +443,16 @@ public class NvdCveUpdater implements CachedWebDataSource { throws MalformedURLException, DownloadFailedException { final Set urls = new HashSet<>(); - final String baseUrl20 = Settings.getString(Settings.KEYS.CVE_SCHEMA_2_0); + final String baseUrl20 = settings.getString(Settings.KEYS.CVE_SCHEMA_2_0); for (int i = startYear; i <= endYear; i++) { final String url = String.format(baseUrl20, i); urls.add(url); } - urls.add(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL)); + urls.add(settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL)); final Map> timestampFutures = new HashMap<>(); for (String url : urls) { - final TimestampRetriever timestampRetriever = new TimestampRetriever(url, Settings.getInstance()); + final TimestampRetriever timestampRetriever = new TimestampRetriever(url, settings); final Future future = downloadExecutorService.submit(timestampRetriever); timestampFutures.put(url, future); } @@ -478,6 +475,15 @@ public class NvdCveUpdater implements CachedWebDataSource { return lastModifiedDates; } + /** + * Sets the settings object; this is used during testing. + * + * @param settings the configured settings + */ + protected void setSettings(Settings settings) { + this.settings = settings; + } + /** * Retrieves the last modified timestamp from a NVD CVE meta data file. */ @@ -507,10 +513,10 @@ public class NvdCveUpdater implements CachedWebDataSource { public Long call() throws Exception { LOGGER.debug("Checking for updates from: {}", url); try { - Settings.setInstance(settings); - return Downloader.getLastModified(new URL(url)); + Downloader downloader = new Downloader(settings); + return downloader.getLastModified(new URL(url)); } finally { - Settings.cleanup(false); + settings.cleanup(false); } } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java index 123d326cc..63cd30d53 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java @@ -43,7 +43,7 @@ public class CPEHandler extends DefaultHandler { /** * The Starts with expression to filter CVE entries by CPE. */ - private static final String CPE_STARTS_WITH = Settings.getString(Settings.KEYS.CVE_CPE_STARTS_WITH_FILTER, "cpe:/a:"); + private final String cpeStartsWith; /** * The text content of the node being processed. This can be used during the * end element event. @@ -62,6 +62,10 @@ public class CPEHandler extends DefaultHandler { */ private final List data = new ArrayList<>(); + public CPEHandler(Settings settings) { + cpeStartsWith = settings.getString(Settings.KEYS.CVE_CPE_STARTS_WITH_FILTER, "cpe:/a:"); + } + /** * Returns the list of CPE values. * @@ -89,7 +93,7 @@ public class CPEHandler extends DefaultHandler { final String temp = attributes.getValue("deprecated"); final String value = attributes.getValue("name"); final boolean delete = "true".equalsIgnoreCase(temp); - if (!delete && value.startsWith(CPE_STARTS_WITH) && value.length() > 7) { + if (!delete && value.startsWith(cpeStartsWith) && value.length() > 7) { try { final Cpe cpe = new Cpe(value); data.add(cpe); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java index e34d5ab12..cdf0eac80 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java @@ -91,8 +91,8 @@ public class DownloadTask implements Callable> { final File file2; try { - file1 = File.createTempFile("cve" + nvdCveInfo.getId() + '_', ".xml", Settings.getTempDirectory()); - file2 = File.createTempFile("cve_1_2_" + nvdCveInfo.getId() + '_', ".xml", Settings.getTempDirectory()); + file1 = File.createTempFile("cve" + nvdCveInfo.getId() + '_', ".xml", settings.getTempDirectory()); + file2 = File.createTempFile("cve_1_2_" + nvdCveInfo.getId() + '_', ".xml", settings.getTempDirectory()); } catch (IOException ex) { throw new UpdateException("Unable to create temporary files", ex); } @@ -158,17 +158,17 @@ public class DownloadTask implements Callable> { @Override public Future call() throws Exception { try { - Settings.setInstance(settings); final URL url1 = new URL(nvdCveInfo.getUrl()); final URL url2 = new URL(nvdCveInfo.getOldSchemaVersionUrl()); LOGGER.info("Download Started for NVD CVE - {}", nvdCveInfo.getId()); final long startDownload = System.currentTimeMillis(); try { - Downloader.fetchFile(url1, first); - Downloader.fetchFile(url2, second); + Downloader downloader = new Downloader(settings); + downloader.fetchFile(url1, first); + downloader.fetchFile(url2, second); } catch (DownloadFailedException ex) { LOGGER.warn("Download Failed for NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId()); - if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) { + if (settings.getString(Settings.KEYS.PROXY_SERVER) == null) { LOGGER.info("If you are behind a proxy you may need to configure dependency-check to use the proxy."); } LOGGER.debug("", ex); @@ -193,7 +193,7 @@ public class DownloadTask implements Callable> { LOGGER.warn("An exception occurred downloading NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId()); LOGGER.debug("Download Task Failed", ex); } finally { - Settings.cleanup(false); + settings.cleanup(false); } return null; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java index d9c4f26f1..240b98873 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java @@ -114,12 +114,11 @@ public class ProcessTask implements Callable { @Override public ProcessTask call() throws Exception { try { - Settings.setInstance(settings); processFiles(); } catch (UpdateException ex) { this.exception = ex; } finally { - Settings.cleanup(false); + settings.cleanup(false); } return this; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java index df32a7402..66a4540b9 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java @@ -104,6 +104,10 @@ public class ReportGenerator { * The Velocity Engine Context. */ private final Context context; + /** + * The configured settings. + */ + private final Settings settings; /** * Constructs a new ReportGenerator. @@ -113,8 +117,11 @@ public class ReportGenerator { * @param analyzers the list of analyzers used * @param properties the database properties (containing timestamps of the * NVD CVE data) + * @param settings a reference to the database settings */ - public ReportGenerator(String applicationName, List dependencies, List analyzers, DatabaseProperties properties) { + public ReportGenerator(String applicationName, List dependencies, List analyzers, + DatabaseProperties properties, Settings settings) { + this.settings = settings; velocityEngine = createVelocityEngine(); velocityEngine.init(); context = createContext(applicationName, dependencies, analyzers, properties); @@ -131,11 +138,11 @@ public class ReportGenerator { * @param analyzers the list of analyzers used * @param properties the database properties (containing timestamps of the * NVD CVE data) + * @param settings a reference to the database settings */ public ReportGenerator(String applicationName, String groupID, String artifactID, String version, - List dependencies, List analyzers, DatabaseProperties properties) { - - this(applicationName, dependencies, analyzers, properties); + List dependencies, List analyzers, DatabaseProperties properties, Settings settings) { + this(applicationName, dependencies, analyzers, properties, settings); if (version != null) { context.put("applicationVersion", version); } @@ -187,7 +194,7 @@ public class ReportGenerator { ctxt.put("scanDate", scanDate); ctxt.put("scanDateXML", scanDateXML); ctxt.put("enc", new EscapeTool()); - ctxt.put("version", Settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); + ctxt.put("version", settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown")); return ctxt; } @@ -246,22 +253,6 @@ public class ReportGenerator { } } -// /** -// * Writes the dependency-check report(s). -// * -// * @param outputStream the OutputStream to send the generated report to -// * @param format the format the report should be written in -// * @throws ReportException thrown if the report format is ALL -// * @throws IOException is thrown when the template file does not exist -// * @throws Exception is thrown if there is an error writing out the reports -// */ -// public void write(OutputStream outputStream, Format format) throws ReportException, IOException, Exception { -// if (format == Format.ALL) { -// throw new ReportException("Unable to write ALL reports to a single output stream, please check the API"); -// } -// final String templateName = format.toString().toLowerCase() + "Report"; -// processTemplate(templateName, outputStream); -// } /** * Determines the report file name based on the give output location and * format. If the output location contains a full file name that has the diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java index 1d274bbd2..8f8929bc0 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java @@ -23,6 +23,7 @@ import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.util.Date; import org.owasp.dependencycheck.data.nvdcve.ConnectionFactory; +import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.exception.H2DBLockException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,6 +50,19 @@ public class H2DBLock { * The lock file. */ private File lockFile = null; + /** + * The configured settings. + */ + private final Settings settings; + /** + * Whether the database connection is using H2. + */ + private final boolean isH2Connection; + + public H2DBLock(Settings settings, boolean isH2Connection) { + this.settings = settings; + this.isH2Connection = isH2Connection; + } /** * Determine if the lock is currently held. @@ -65,9 +79,9 @@ public class H2DBLock { * @throws H2DBLockException thrown if a lock could not be obtained */ public void lock() throws H2DBLockException { - if (ConnectionFactory.isH2Connection()) { + if (isH2Connection) { try { - final File dir = Settings.getDataDirectory(); + final File dir = settings.getDataDirectory(); lockFile = new File(dir, "dc.update.lock"); if (lockFile.isFile() && getFileAge(lockFile) > 5 && !lockFile.delete()) { LOGGER.warn("An old db update lock file was found but the system was unable to delete " diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/AnalysisTaskTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/AnalysisTaskTest.java index bc9888376..d54c16dd4 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/AnalysisTaskTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/AnalysisTaskTest.java @@ -44,7 +44,7 @@ public class AnalysisTaskTest extends BaseTest { result = true; }}; - AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, Settings.getInstance()); + AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, getSettings()); boolean shouldAnalyze = analysisTask.shouldAnalyze(); assertTrue(shouldAnalyze); @@ -61,7 +61,7 @@ public class AnalysisTaskTest extends BaseTest { result = false; }}; - AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, Settings.getInstance()); + AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, getSettings()); boolean shouldAnalyze = analysisTask.shouldAnalyze(); assertFalse(shouldAnalyze); @@ -69,7 +69,7 @@ public class AnalysisTaskTest extends BaseTest { @Test public void taskAnalyzes() throws Exception { - final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, Settings.getInstance()); + final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, getSettings()); new Expectations(analysisTask) {{ analysisTask.shouldAnalyze(); result = true; @@ -85,7 +85,7 @@ public class AnalysisTaskTest extends BaseTest { @Test public void taskDoesNothingIfItShouldNotAnalyze() throws Exception { - final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, Settings.getInstance()); + final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, getSettings()); new Expectations(analysisTask) {{ analysisTask.shouldAnalyze(); result = false; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java index cec529ff2..0ee382691 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java @@ -43,17 +43,19 @@ public abstract class BaseDBTestCase extends BaseTest { private final static Logger LOGGER = LoggerFactory.getLogger(BaseDBTestCase.class); @Before - public void setUpDb() throws Exception { + @Override + public void setUp() throws Exception { + super.setUp(); ensureDBExists(); } - public static void ensureDBExists() throws Exception { + public void ensureDBExists() throws Exception { File f = new File("./target/data/dc.h2.db"); if (f.exists() && f.isFile() && f.length() < 71680) { f.delete(); } - File dataPath = Settings.getDataDirectory(); - String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME); + File dataPath = getSettings().getDataDirectory(); + String fileName = getSettings().getString(Settings.KEYS.DB_FILE_NAME); LOGGER.trace("DB file name {}", fileName); File dataFile = new File(dataPath, fileName); LOGGER.trace("Ensuring {} exists", dataFile.toString()); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseTest.java index bdf307cb6..0e60c7399 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseTest.java @@ -18,9 +18,11 @@ package org.owasp.dependencycheck; import java.io.File; import java.io.InputStream; import java.net.URISyntaxException; +import org.junit.After; import org.junit.AfterClass; import org.junit.Assume; +import org.junit.Before; import org.junit.BeforeClass; import org.owasp.dependencycheck.utils.Settings; @@ -30,9 +32,25 @@ import org.owasp.dependencycheck.utils.Settings; */ public class BaseTest { - @BeforeClass - public static void setUpClass() throws Exception { - Settings.initialize(); + /** + * The configured settings. + */ + private Settings settings; + + /** + * Initialize the {@link Settings}. + */ + @Before + public void setUp() throws Exception { + settings = new Settings(); + } + + /** + * Clean the {@link Settings}. + */ + @After + public void tearDown() throws Exception { + settings.cleanup(true); } @AfterClass @@ -45,13 +63,12 @@ public class BaseTest { System.err.println("------------------------------------------------"); System.err.println("------------------------------------------------"); } - - Settings.cleanup(true); } /** - * Returns the given resource as an InputStream using the object's class loader. The org.junit.Assume API is used so that test - * cases are skipped if the resource is not available. + * Returns the given resource as an InputStream using the object's class + * loader. The org.junit.Assume API is used so that test cases are skipped + * if the resource is not available. * * @param o the object used to obtain a reference to the class loader * @param resource the name of the resource to load @@ -63,20 +80,30 @@ public class BaseTest { } /** - * Returns the given resource as a File using the object's class loader. The org.junit.Assume API is used so that test cases - * are skipped if the resource is not available. + * Returns the given resource as a File using the object's class loader. The + * org.junit.Assume API is used so that test cases are skipped if the + * resource is not available. * * @param o the object used to obtain a reference to the class loader * @param resource the name of the resource to load * @return the resource as an File */ public static File getResourceAsFile(Object o, String resource) { - try{ + try { File f = new File(o.getClass().getClassLoader().getResource(resource).toURI().getPath()); Assume.assumeTrue(String.format("%n%n[SEVERE] Unable to load resource for test case: %s%n%n", resource), f.exists()); return f; - }catch (URISyntaxException e){ + } catch (URISyntaxException e) { throw new UnsupportedOperationException(e); } } + + /** + * Returns the settings for the test cases. + * + * @return + */ + protected Settings getSettings() { + return settings; + } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineIT.java index 45597a7c4..03dcf1e91 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineIT.java @@ -48,10 +48,10 @@ public class EngineIT extends BaseDBTestCase { @Test public void testEngine() throws IOException, InvalidSettingException, DatabaseException, ReportException, ExceptionCollection { String testClasses = "target/test-classes"; - boolean autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Engine instance = new Engine(); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); + boolean autoUpdate = getSettings().getBoolean(Settings.KEYS.AUTO_UPDATE); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + Engine instance = new Engine(getSettings()); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); instance.scan(testClasses); assertTrue(instance.getDependencies().size() > 0); try { diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineModeIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineModeIT.java index f1343adfd..ad63a608f 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineModeIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineModeIT.java @@ -38,26 +38,35 @@ public class EngineModeIT extends BaseTest { private String originalDataDir = null; @Before + @Override public void setUp() throws Exception { + super.setUp(); // Have to use System properties as the Settings object pulls from the // system properties before configured properties - originalDataDir = Settings.getString(Settings.KEYS.DATA_DIRECTORY); + originalDataDir = getSettings().getString(Settings.KEYS.DATA_DIRECTORY); System.setProperty(Settings.KEYS.DATA_DIRECTORY, tempDir.newFolder().getAbsolutePath()); } @After - public void tearDown() throws IOException { - //delete temp files - FileUtils.delete(Settings.getDataDirectory()); - //Reset system property to original value just to be safe for other tests. - System.setProperty(Settings.KEYS.DATA_DIRECTORY, originalDataDir); - + @Override + public void tearDown() throws Exception { + try { + //delete temp files + FileUtils.delete(getSettings().getDataDirectory()); + //Reset system property to original value just to be safe for other tests. + System.setProperty(Settings.KEYS.DATA_DIRECTORY, originalDataDir); + } catch (IOException ex) { + throw new RuntimeException(ex); + } finally { + super.tearDown(); + } } @Test public void testEvidenceCollectionAndEvidenceProcessingModes() throws Exception { List dependencies; - try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION)) { + try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION, getSettings())) { + engine.openDatabase(); //does nothing in the current mode assertDatabase(false); for (AnalysisPhase phase : Engine.Mode.EVIDENCE_COLLECTION.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); @@ -76,7 +85,8 @@ public class EngineModeIT extends BaseTest { assertTrue(dependency.getVulnerabilities().isEmpty()); } - try (Engine engine = new Engine(Engine.Mode.EVIDENCE_PROCESSING)) { + try (Engine engine = new Engine(Engine.Mode.EVIDENCE_PROCESSING, getSettings())) { + engine.openDatabase(); assertDatabase(true); for (AnalysisPhase phase : Engine.Mode.EVIDENCE_PROCESSING.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); @@ -93,7 +103,8 @@ public class EngineModeIT extends BaseTest { @Test public void testStandaloneMode() throws Exception { - try (Engine engine = new Engine(Engine.Mode.STANDALONE)) { + try (Engine engine = new Engine(Engine.Mode.STANDALONE, getSettings())) { + engine.openDatabase(); assertDatabase(true); for (AnalysisPhase phase : Engine.Mode.STANDALONE.getPhases()) { assertThat(engine.getAnalyzers(phase), is(notNullValue())); @@ -111,16 +122,15 @@ public class EngineModeIT extends BaseTest { } private void assertDatabase(boolean exists) throws Exception { - Assume.assumeThat(Settings.getString(Settings.KEYS.DB_DRIVER_NAME), is("org.h2.Driver")); - Path directory = Settings.getDataDirectory().toPath(); + Assume.assumeThat(getSettings().getString(Settings.KEYS.DB_DRIVER_NAME), is("org.h2.Driver")); + Path directory = getSettings().getDataDirectory().toPath(); assertThat(Files.exists(directory), is(true)); assertThat(Files.isDirectory(directory), is(true)); - Path database = directory.resolve(Settings.getString(Settings.KEYS.DB_FILE_NAME)); - System.err.println(database.toString()); - for (String f : directory.toFile().list()) { - System.err.println(f); - } - + Path database = directory.resolve(getSettings().getString(Settings.KEYS.DB_FILE_NAME)); + //System.err.println(database.toString()); + //for (String f : directory.toFile().list()) { + // System.err.println(f); + //} assertThat(Files.exists(database), is(exists)); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineTest.java index 189bd5ef7..3934d8b3c 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/EngineTest.java @@ -54,7 +54,7 @@ public class EngineTest extends BaseDBTestCase { */ @Test public void testScanFile() throws DatabaseException { - Engine instance = new Engine(); + Engine instance = new Engine(getSettings()); instance.addFileTypeAnalyzer(new JarAnalyzer()); File file = BaseTest.getResourceAsFile(this, "dwr.jar"); Dependency dwr = instance.scanFile(file); @@ -72,7 +72,7 @@ public class EngineTest extends BaseDBTestCase { @Test(expected = ExceptionCollection.class) public void exceptionDuringAnalysisTaskExecutionIsFatal() throws DatabaseException, ExceptionCollection { final ExecutorService executorService = Executors.newFixedThreadPool(3); - final Engine instance = new Engine(); + final Engine instance = new Engine(getSettings()); final List exceptions = new ArrayList<>(); new Expectations() { @@ -89,14 +89,11 @@ public class EngineTest extends BaseDBTestCase { { instance.getExecutorService(analyzer); result = executorService; - instance.getAnalysisTasks(analyzer, exceptions); result = failingAnalysisTask; } }; - instance.executeAnalysisTasks(analyzer, exceptions); - assertTrue(executorService.isShutdown()); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzerTest.java index 5f21d1216..e1c696466 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzerTest.java @@ -39,14 +39,18 @@ import org.owasp.dependencycheck.utils.Settings.KEYS; */ public class AbstractSuppressionAnalyzerTest extends BaseTest { - /** A second suppression file to test with. */ + /** + * A second suppression file to test with. + */ private static final String OTHER_SUPPRESSIONS_FILE = "other-suppressions.xml"; - /** Suppression file to test with. */ + /** + * Suppression file to test with. + */ private static final String SUPPRESSIONS_FILE = "suppressions.xml"; - + private AbstractSuppressionAnalyzer instance; - + @Before public void createObjectUnderTest() throws Exception { instance = new AbstractSuppressionAnalyzerImpl(); @@ -75,7 +79,7 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest { /** * Test of getRules method, of class AbstractSuppressionAnalyzer for - * suppression file on the classpath. + * suppression file on the class path. */ @Test public void testGetRulesFromSuppressionFileInClasspath() throws Exception { @@ -84,7 +88,8 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest { } /** - * Assert that rules are loaded from multiple files if multiple files are denfined in the {@link Settings} singleton. + * Assert that rules are loaded from multiple files if multiple files are + * defined in the {@link Settings}. */ @Test public void testGetRulesFromMultipleSuppressionFiles() throws Exception { @@ -97,71 +102,75 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest { final int rulesInSecondFile = getNumberOfRulesLoadedFromPath(OTHER_SUPPRESSIONS_FILE) - rulesInCoreFile; // WHEN initializing with both suppression files - final String[] suppressionFiles = { SUPPRESSIONS_FILE, OTHER_SUPPRESSIONS_FILE }; - Settings.setArrayIfNotEmpty(KEYS.SUPPRESSION_FILE, suppressionFiles); - instance.initialize(); + final String[] suppressionFiles = {SUPPRESSIONS_FILE, OTHER_SUPPRESSIONS_FILE}; + getSettings().setArrayIfNotEmpty(KEYS.SUPPRESSION_FILE, suppressionFiles); + instance.initializeSettings(getSettings()); + instance.initialize(null); // THEN rules from both files were loaded final int expectedSize = rulesInFirstFile + rulesInSecondFile + rulesInCoreFile; assertThat("Expected suppressions from both files", instance.getRuleCount(), is(expectedSize)); } - + @Test(expected = InitializationException.class) public void testFailureToLocateSuppressionFileAnywhere() throws Exception { - Settings.setString(Settings.KEYS.SUPPRESSION_FILE, "doesnotexist.xml"); - instance.initialize(); + getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, "doesnotexist.xml"); + instance.initializeSettings(getSettings()); + instance.initialize(null); } /** - * Return the number of rules that are loaded from the core suppression file. + * Return the number of rules that are loaded from the core suppression + * file. * - * @return the number of rules defined in the core suppresion file. + * @return the number of rules defined in the core suppression file. * @throws Exception if loading the rules fails. */ private int getNumberOfRulesLoadedInCoreFile() throws Exception { - Settings.removeProperty(KEYS.SUPPRESSION_FILE); - + getSettings().removeProperty(KEYS.SUPPRESSION_FILE); final AbstractSuppressionAnalyzerImpl coreFileAnalyzer = new AbstractSuppressionAnalyzerImpl(); - coreFileAnalyzer.initialize(); + coreFileAnalyzer.initializeSettings(getSettings()); + coreFileAnalyzer.initialize(null); return coreFileAnalyzer.getRuleCount(); } /** - * Load a file into the {@link AbstractSuppressionAnalyzer} and return the number of rules loaded. + * Load a file into the {@link AbstractSuppressionAnalyzer} and return the + * number of rules loaded. * * @param path the path to load. * @return the number of rules that were loaded (including the core rules). * @throws Exception if loading the rules fails. */ private int getNumberOfRulesLoadedFromPath(final String path) throws Exception { - Settings.setString(KEYS.SUPPRESSION_FILE, path); - + getSettings().setString(KEYS.SUPPRESSION_FILE, path); final AbstractSuppressionAnalyzerImpl fileAnalyzer = new AbstractSuppressionAnalyzerImpl(); - fileAnalyzer.initialize(); + fileAnalyzer.initializeSettings(getSettings()); + fileAnalyzer.initialize(null); return fileAnalyzer.getRuleCount(); } - + public class AbstractSuppressionAnalyzerImpl extends AbstractSuppressionAnalyzer { - + @Override public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } - + @Override public String getName() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } - + @Override public AnalysisPhase getAnalysisPhase() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } - + @Override protected String getAnalyzerEnabledSettingKey() { return "unknown"; } } - + } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AnalyzerServiceTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AnalyzerServiceTest.java index 34f83be44..7561eb0bb 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AnalyzerServiceTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AnalyzerServiceTest.java @@ -40,13 +40,14 @@ public class AnalyzerServiceTest extends BaseDBTestCase { */ @Test public void testGetAnalyzers() { - AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader()); + AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false); List result = instance.getAnalyzers(); boolean found = false; for (Analyzer a : result) { if ("Jar Analyzer".equals(a.getName())) { found = true; + break; } } assertTrue("JarAnalyzer loaded", found); @@ -57,7 +58,7 @@ public class AnalyzerServiceTest extends BaseDBTestCase { */ @Test public void testGetAnalyzers_SpecificPhases() throws Exception { - AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader()); + AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false); List result = instance.getAnalyzers(INITIAL, FINAL); for (Analyzer a : result) { @@ -72,8 +73,7 @@ public class AnalyzerServiceTest extends BaseDBTestCase { */ @Test public void testGetExperimentalAnalyzers() { - Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false); - AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader()); + AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false); List result = instance.getAnalyzers(); String experimental = "CMake Analyzer"; boolean found = false; @@ -83,8 +83,8 @@ public class AnalyzerServiceTest extends BaseDBTestCase { } } assertFalse("Experimental analyzer loaded when set to false", found); - - Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, true); + + instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), true); result = instance.getAnalyzers(); found = false; for (Analyzer a : result) { diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerIT.java index a80e845bd..0f8d8a82c 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerIT.java @@ -41,6 +41,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testSupportsExtensions() { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); Set expResult = new HashSet<>(); expResult.add("zip"); expResult.add("war"); @@ -65,6 +66,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testGetName() { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); String expResult = "Archive Analyzer"; String result = instance.getName(); assertEquals(expResult, result); @@ -77,6 +79,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { public void testSupportsExtension() { String extension = "test.7z"; //not supported ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); assertFalse(extension, instance.accept(new File(extension))); } @@ -86,6 +89,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testGetAnalysisPhase() { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); AnalysisPhase expResult = AnalysisPhase.INITIAL; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); @@ -97,10 +101,11 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testInitialize() { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); try { instance.setEnabled(true); instance.setFilesMatched(true); - instance.initialize(); + instance.initialize(null); } catch (InitializationException ex) { fail(ex.getMessage()); } finally { @@ -120,16 +125,18 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyze() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); //trick the analyzer into thinking it is active. instance.accept(new File("test.ear")); try { - instance.initialize(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); + + instance.initialize(engine); File file = BaseTest.getResourceAsFile(this, "daytrader-ear-2.1.7.ear"); Dependency dependency = new Dependency(file); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); int initial_size = engine.getDependencies().size(); instance.analyze(dependency, engine); @@ -150,16 +157,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeExecutableJar() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); //trick the analyzer into thinking it is active. instance.accept(new File("test.ear")); try { - instance.initialize(); + instance.initialize(null); File file = BaseTest.getResourceAsFile(this, "bootable-0.1.0.jar"); Dependency dependency = new Dependency(file); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); instance.analyze(dependency, engine); @@ -180,19 +188,20 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeTar() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); //trick the analyzer into thinking it is active so that it will initialize instance.accept(new File("test.tar")); try { - instance.initialize(); + instance.initialize(null); //File file = new File(this.getClass().getClassLoader().getResource("file.tar").getPath()); //File file = new File(this.getClass().getClassLoader().getResource("stagedhttp-modified.tar").getPath()); File file = BaseTest.getResourceAsFile(this, "stagedhttp-modified.tar"); Dependency dependency = new Dependency(file); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); instance.analyze(dependency, engine); @@ -212,17 +221,18 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeTarGz() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); instance.accept(new File("zip")); //ensure analyzer is "enabled" try { - instance.initialize(); + instance.initialize(null); //File file = new File(this.getClass().getClassLoader().getResource("file.tar.gz").getPath()); File file = BaseTest.getResourceAsFile(this, "file.tar.gz"); //Dependency dependency = new Dependency(file); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); //instance.analyze(dependency, engine); @@ -243,14 +253,15 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeTarBz2() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); instance.accept(new File("zip")); //ensure analyzer is "enabled" try { - instance.initialize(); + instance.initialize(null); File file = BaseTest.getResourceAsFile(this, "file.tar.bz2"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); engine.scan(file); engine.analyzeDependencies(); @@ -268,16 +279,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeTgz() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); instance.accept(new File("zip")); //ensure analyzer is "enabled" try { - instance.initialize(); + instance.initialize(null); //File file = new File(this.getClass().getClassLoader().getResource("file.tgz").getPath()); File file = BaseTest.getResourceAsFile(this, "file.tgz"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); engine.scan(file); @@ -297,14 +309,15 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyzeTbz2() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); instance.accept(new File("zip")); //ensure analyzer is "enabled" try { - instance.initialize(); + instance.initialize(null); File file = BaseTest.getResourceAsFile(this, "file.tbz2"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); engine.scan(file); engine.analyzeDependencies(); @@ -322,16 +335,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase { @Test public void testAnalyze_badZip() throws Exception { ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); try { - instance.initialize(); + instance.initialize(null); //File file = new File(this.getClass().getClassLoader().getResource("test.zip").getPath()); File file = BaseTest.getResourceAsFile(this, "test.zip"); Dependency dependency = new Dependency(file); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); int initial_size = engine.getDependencies().size(); // boolean failed = false; // try { diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerTest.java index be418c069..9afbfbf44 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzerTest.java @@ -36,8 +36,10 @@ import org.owasp.dependencycheck.utils.Settings; public class ArchiveAnalyzerTest extends BaseTest { @Before - public void setUp() { - Settings.setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, "z2, z3"); + @Override + public void setUp() throws Exception { + super.setUp(); + getSettings().setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, "z2, z3"); } /** @@ -47,6 +49,7 @@ public class ArchiveAnalyzerTest extends BaseTest { public void testZippableExtensions() throws Exception { assumeFalse(isPreviouslyLoaded("org.owasp.dependencycheck.analyzer.ArchiveAnalyzer")); ArchiveAnalyzer instance = new ArchiveAnalyzer(); + instance.initializeSettings(getSettings()); assertTrue(instance.getFileFilter().accept(new File("c:/test.zip"))); assertTrue(instance.getFileFilter().accept(new File("c:/test.z2"))); assertTrue(instance.getFileFilter().accept(new File("c:/test.z3"))); @@ -59,15 +62,7 @@ public class ArchiveAnalyzerTest extends BaseTest { m.setAccessible(true); Object t = m.invoke(Thread.currentThread().getContextClassLoader(), className); return t != null; - } catch (NoSuchMethodException ex) { - Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); - } catch (SecurityException ex) { - Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); - } catch (IllegalAccessException ex) { - Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); - } catch (IllegalArgumentException ex) { - Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); - } catch (InvocationTargetException ex) { + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); } return false; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java index 1ff39bc60..893e80749 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzerTest.java @@ -65,11 +65,14 @@ public class AssemblyAnalyzerTest extends BaseTest { * @throws Exception if anything goes sideways */ @Before + @Override public void setUp() throws Exception { + super.setUp(); try { analyzer = new AssemblyAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.accept(new File("test.dll")); // trick into "thinking it is active" - analyzer.initialize(); + analyzer.initialize(null); assertGrokAssembly(); } catch (Exception e) { if (e.getMessage().contains("Could not execute .NET AssemblyAnalyzer")) { @@ -86,8 +89,8 @@ public class AssemblyAnalyzerTest extends BaseTest { // directory and they must match the resources they were created from. File grokAssemblyExeFile = null; File grokAssemblyConfigFile = null; - - File tempDirectory = Settings.getTempDirectory(); + + File tempDirectory = getSettings().getTempDirectory(); for (File file : tempDirectory.listFiles()) { String filename = file.getName(); if (filename.startsWith("GKA") && filename.endsWith(".exe")) { @@ -99,10 +102,8 @@ public class AssemblyAnalyzerTest extends BaseTest { grokAssemblyConfigFile = new File(grokAssemblyExeFile.getPath() + ".config"); assertTrue("The GrokAssembly config was not created.", grokAssemblyConfigFile.isFile()); - assertFileContent("The GrokAssembly executable has incorrect content.", "GrokAssembly.exe", - grokAssemblyExeFile); - assertFileContent("The GrokAssembly config has incorrect content.", "GrokAssembly.exe.config", - grokAssemblyConfigFile); + assertFileContent("The GrokAssembly executable has incorrect content.", "GrokAssembly.exe", grokAssemblyExeFile); + assertFileContent("The GrokAssembly config has incorrect content.", "GrokAssembly.exe.config", grokAssemblyConfigFile); } private void assertFileContent(String message, String expectedResourceName, File actualFile) throws IOException { @@ -183,7 +184,7 @@ public class AssemblyAnalyzerTest extends BaseTest { //This test doesn't work on Windows. assumeFalse(System.getProperty("os.name").startsWith("Windows")); - String oldValue = Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH); + String oldValue = getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH); // if oldValue is null, that means that neither the system property nor the setting has // been set. If that's the case, then we have to make it such that when we recover, // null still comes back. But you can't put a null value in a HashMap, so we have to set @@ -191,7 +192,7 @@ public class AssemblyAnalyzerTest extends BaseTest { if (oldValue == null) { System.setProperty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono"); } else { - Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono"); + getSettings().setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono"); } String oldProp = System.getProperty(LOG_KEY, "info"); @@ -201,7 +202,7 @@ public class AssemblyAnalyzerTest extends BaseTest { // Have to make a NEW analyzer because during setUp, it would have gotten the correct one AssemblyAnalyzer aanalyzer = new AssemblyAnalyzer(); aanalyzer.accept(new File("test.dll")); // trick into "thinking it is active" - aanalyzer.initialize(); + aanalyzer.initialize(null); fail("Expected an InitializationException"); } catch (InitializationException ae) { assertEquals("An error occurred with the .NET AssemblyAnalyzer", ae.getMessage()); @@ -213,13 +214,20 @@ public class AssemblyAnalyzerTest extends BaseTest { if (oldValue == null) { System.getProperties().remove(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH); } else { - Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, oldValue); + getSettings().setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, oldValue); } } } @After + @Override public void tearDown() throws Exception { - analyzer.closeAnalyzer(); + try { + analyzer.closeAnalyzer(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } finally { + super.tearDown(); + } } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java index e8108ffef..8a0ff2fd2 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java @@ -30,11 +30,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** - * Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were obtained from outside open source software projects. - * Links to those projects are given below. + * Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were + * obtained from outside open source software projects. Links to those projects + * are given below. * * @author Dale Visser - * @see Readable Lisp S-expressions Project + * @see Readable Lisp S-expressions + * Project * @see GNU Binutils * @see GNU Ghostscript */ @@ -66,10 +68,13 @@ public class AutoconfAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new AutoconfAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initialize(null); } /** @@ -78,13 +83,16 @@ public class AutoconfAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); analyzer = null; + super.tearDown(); } /** - * Test whether expected evidence is gathered from Ghostscript's configure.ac. + * Test whether expected evidence is gathered from Ghostscript's + * configure. * * @throws AnalysisException is thrown when an exception occurs. */ @@ -130,7 +138,8 @@ public class AutoconfAnalyzerTest extends BaseTest { } /** - * Test whether expected evidence is gathered from GNU Ghostscript's configure. + * Test whether expected evidence is gathered from GNU Ghostscript's + * configure. * * @throws AnalysisException is thrown when an exception occurs. */ diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzerTest.java index 6408d4a86..4163bc728 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzerTest.java @@ -61,21 +61,29 @@ public class CMakeAnalyzerTest extends BaseDBTestCase { * @throws Exception if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new CMakeAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initialize(null); } /** * Cleanup any resources used. * - * @throws Exception if there is a problem */ @After + @Override public void tearDown() throws Exception { - analyzer.close(); - analyzer = null; + try { + analyzer.close(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } finally { + super.tearDown(); + } } /** @@ -124,14 +132,15 @@ public class CMakeAnalyzerTest extends BaseDBTestCase { final String product = "zlib"; assertProductEvidence(result, product); } - + private void assertProductEvidence(Dependency result, String product) { assertTrue("Expected product evidence to contain \"" + product + "\".", result.getProductEvidence().toString().contains(product)); } /** - * Test whether expected version evidence is gathered from OpenCV's third party cmake files. + * Test whether expected version evidence is gathered from OpenCV's third + * party cmake files. * * @throws AnalysisException is thrown when an exception occurs. */ @@ -139,7 +148,7 @@ public class CMakeAnalyzerTest extends BaseDBTestCase { public void testAnalyzeCMakeListsOpenCV3rdParty() throws AnalysisException, DatabaseException { final Dependency result = new Dependency(BaseTest.getResourceAsFile( this, "cmake/opencv/3rdparty/ffmpeg/ffmpeg_version.cmake")); - final Engine engine = new Engine(); + final Engine engine = new Engine(getSettings()); analyzer.analyze(result, engine); assertProductEvidence(result, "libavcodec"); assertVersionEvidence(result, "55.18.102"); @@ -151,12 +160,12 @@ public class CMakeAnalyzerTest extends BaseDBTestCase { assertProductEvidence(last, "libavresample"); assertVersionEvidence(last, "1.0.1"); } - + private void assertVersionEvidence(Dependency result, String version) { assertTrue("Expected version evidence to contain \"" + version + "\".", result.getVersionEvidence().toString().contains(version)); } - + @Test(expected = InitializationException.class) public void analyzerIsDisabledInCaseOfMissingMessageDigest() throws InitializationException { new MockUp() { @@ -165,12 +174,13 @@ public class CMakeAnalyzerTest extends BaseDBTestCase { throw new NoSuchAlgorithmException(); } }; - + analyzer = new CMakeAnalyzer(); analyzer.setFilesMatched(true); assertTrue(analyzer.isEnabled()); - analyzer.initialize(); - + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); + assertFalse(analyzer.isEnabled()); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CPEAnalyzerIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CPEAnalyzerIT.java index d0eee79c7..ee2115b20 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CPEAnalyzerIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/CPEAnalyzerIT.java @@ -24,8 +24,6 @@ import java.util.List; import java.util.Set; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.queryparser.classic.ParseException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseDBTestCase; @@ -58,9 +56,9 @@ public class CPEAnalyzerIT extends BaseDBTestCase { String vendor = "apache software foundation"; String product = "struts 2 core"; - - CPEAnalyzer instance = new CPEAnalyzer(); + CPEAnalyzer instance = new CPEAnalyzer(); + instance.initializeSettings(getSettings()); String queryText = instance.buildSearch(vendor, product, null, null); String expResult = " product:( struts 2 core ) AND vendor:( apache software foundation ) "; assertTrue(expResult.equals(queryText)); @@ -86,21 +84,26 @@ public class CPEAnalyzerIT extends BaseDBTestCase { @Test public void testDetermineCPE_full() throws Exception { //update needs to be performed so that xtream can be tested - Engine e = new Engine(); + Engine e = new Engine(getSettings()); e.doUpdates(); CPEAnalyzer cpeAnalyzer = new CPEAnalyzer(); try { - cpeAnalyzer.initialize(); + cpeAnalyzer.initializeSettings(getSettings()); + cpeAnalyzer.initialize(e); FileNameAnalyzer fnAnalyzer = new FileNameAnalyzer(); - fnAnalyzer.initialize(); + fnAnalyzer.initializeSettings(getSettings()); + fnAnalyzer.initialize(e); JarAnalyzer jarAnalyzer = new JarAnalyzer(); + jarAnalyzer.initializeSettings(getSettings()); jarAnalyzer.accept(new File("test.jar"));//trick analyzer into "thinking it is active" - jarAnalyzer.initialize(); + jarAnalyzer.initialize(e); HintAnalyzer hAnalyzer = new HintAnalyzer(); - hAnalyzer.initialize(); + hAnalyzer.initializeSettings(getSettings()); + hAnalyzer.initialize(e); FalsePositiveAnalyzer fp = new FalsePositiveAnalyzer(); - fp.initialize(); + fp.initializeSettings(getSettings()); + fp.initialize(e); callDetermineCPE_full("hazelcast-2.5.jar", null, cpeAnalyzer, fnAnalyzer, jarAnalyzer, hAnalyzer, fp); callDetermineCPE_full("spring-context-support-2.5.5.jar", "cpe:/a:springsource:spring_framework:2.5.5", cpeAnalyzer, fnAnalyzer, jarAnalyzer, hAnalyzer, fp); @@ -159,10 +162,12 @@ public class CPEAnalyzerIT extends BaseDBTestCase { fnAnalyzer.analyze(struts, null); HintAnalyzer hintAnalyzer = new HintAnalyzer(); - hintAnalyzer.initialize(); + hintAnalyzer.initializeSettings(getSettings()); + hintAnalyzer.initialize(null); JarAnalyzer jarAnalyzer = new JarAnalyzer(); + jarAnalyzer.initializeSettings(getSettings()); jarAnalyzer.accept(new File("test.jar"));//trick analyzer into "thinking it is active" - jarAnalyzer.initialize(); + jarAnalyzer.initialize(null); jarAnalyzer.analyze(struts, null); hintAnalyzer.analyze(struts, null); @@ -185,7 +190,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase { hintAnalyzer.analyze(spring3, null); CPEAnalyzer instance = new CPEAnalyzer(); - instance.open(); + Engine engine = new Engine(getSettings()); + engine.openDatabase(); + instance.initializeSettings(getSettings()); + instance.initialize(engine); instance.determineCPE(commonValidator); instance.determineCPE(struts); instance.determineCPE(spring); @@ -204,6 +212,7 @@ public class CPEAnalyzerIT extends BaseDBTestCase { assertTrue("Incorrect match size - spring3 - " + spring3.getIdentifiers().size(), spring3.getIdentifiers().size() >= 1); jarAnalyzer.close(); + engine.cleanup(); } /** @@ -219,7 +228,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase { openssl.getVersionEvidence().addEvidence("test", "version", "1.0.1c", Confidence.HIGHEST); CPEAnalyzer instance = new CPEAnalyzer(); - instance.open(); + Engine engine = new Engine(getSettings()); + engine.openDatabase(); + instance.initializeSettings(getSettings()); + instance.initialize(engine); instance.determineIdentifiers(openssl, "openssl", "openssl", Confidence.HIGHEST); instance.close(); @@ -227,7 +239,7 @@ public class CPEAnalyzerIT extends BaseDBTestCase { Identifier expIdentifier = new Identifier("cpe", expResult, expResult); assertTrue(openssl.getIdentifiers().contains(expIdentifier)); - + engine.cleanup(); } /** @@ -243,7 +255,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase { String expProduct = "struts"; CPEAnalyzer instance = new CPEAnalyzer(); - instance.open(); + Engine engine = new Engine(getSettings()); + engine.openDatabase(); + instance.initializeSettings(getSettings()); + instance.initialize(engine); Set productWeightings = Collections.singleton("struts2"); Set vendorWeightings = Collections.singleton("apache"); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java index 30c72b25a..fdb3d49dd 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzerTest.java @@ -55,10 +55,13 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new ComposerLockAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initialize(null); } /** @@ -67,9 +70,10 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** @@ -95,27 +99,27 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase { */ @Test public void testAnalyzePackageJson() throws Exception { - final Engine engine = new Engine(); + final Engine engine = new Engine(getSettings()); final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "composer.lock")); analyzer.analyze(result, engine); } - - + @Test(expected = InitializationException.class) public void analyzerIsDisabledInCaseOfMissingMessageDigest() throws InitializationException { new MockUp() { @Mock MessageDigest getInstance(String ignore) throws NoSuchAlgorithmException { - throw new NoSuchAlgorithmException(); + throw new NoSuchAlgorithmException("SHA1 is missing"); } }; - + analyzer = new ComposerLockAnalyzer(); analyzer.setFilesMatched(true); + analyzer.initializeSettings(getSettings()); assertTrue(analyzer.isEnabled()); - analyzer.initialize(); - + analyzer.initialize(null); + assertFalse(analyzer.isEnabled()); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/FileNameAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/FileNameAnalyzerTest.java index ff693fe5f..90416ed3f 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/FileNameAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/FileNameAnalyzerTest.java @@ -81,7 +81,8 @@ public class FileNameAnalyzerTest extends BaseTest { public void testInitialize() { FileNameAnalyzer instance = new FileNameAnalyzer(); try { - instance.initialize(); + instance.initializeSettings(getSettings()); + instance.initialize(null); } catch (InitializationException ex) { fail(ex.getMessage()); } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/HintAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/HintAnalyzerTest.java index 3ee58f893..55ef90163 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/HintAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/HintAnalyzerTest.java @@ -69,11 +69,11 @@ public class HintAnalyzerTest extends BaseDBTestCase { //File spring = new File(this.getClass().getClassLoader().getResource("spring-core-3.0.0.RELEASE.jar").getPath()); File spring = BaseTest.getResourceAsFile(this, "spring-core-3.0.0.RELEASE.jar"); //Dependency spring = new Dependency(files); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); - + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); + engine.scan(guice); engine.scan(spring); engine.analyzeDependencies(); @@ -91,14 +91,14 @@ public class HintAnalyzerTest extends BaseDBTestCase { final Evidence springTest3 = new Evidence("hint analyzer", "vendor", "vmware", Confidence.HIGH); final Evidence springTest4 = new Evidence("hint analyzer", "product", "springsource_spring_framework", Confidence.HIGH); final Evidence springTest5 = new Evidence("hint analyzer", "vendor", "vmware", Confidence.HIGH); - + Set evidence = gdep.getEvidence().getEvidence(); assertFalse(evidence.contains(springTest1)); assertFalse(evidence.contains(springTest2)); assertFalse(evidence.contains(springTest3)); assertFalse(evidence.contains(springTest4)); assertFalse(evidence.contains(springTest5)); - + evidence = sdep.getEvidence().getEvidence(); assertTrue(evidence.contains(springTest1)); assertTrue(evidence.contains(springTest2)); @@ -106,15 +106,17 @@ public class HintAnalyzerTest extends BaseDBTestCase { //assertTrue(evidence.contains(springTest4)); //assertTrue(evidence.contains(springTest5)); } + /** * Test of analyze method, of class HintAnalyzer. */ @Test public void testAnalyze_1() throws Exception { File path = BaseTest.getResourceAsFile(this, "hints_12.xml"); - Settings.setString(Settings.KEYS.HINTS_FILE, path.getPath()); + getSettings().setString(Settings.KEYS.HINTS_FILE, path.getPath()); HintAnalyzer instance = new HintAnalyzer(); - instance.initialize(); + instance.initializeSettings(getSettings()); + instance.initialize(null); Dependency d = new Dependency(); d.getVersionEvidence().addEvidence("version source", "given version name", "1.2.3", Confidence.HIGH); d.getVersionEvidence().addEvidence("hint analyzer", "remove version name", "value", Confidence.HIGH); @@ -124,14 +126,13 @@ public class HintAnalyzerTest extends BaseDBTestCase { d.getVendorEvidence().addEvidence("hint analyzer", "other vendor name", "vendor", Confidence.HIGH); d.getProductEvidence().addEvidence("hint analyzer", "other product name", "product", Confidence.HIGH); - assertEquals("vendor evidence mismatch",2, d.getVendorEvidence().size()); - assertEquals("product evidence mismatch",2, d.getProductEvidence().size()); - assertEquals("version evidence mismatch",3, d.getVersionEvidence().size()); + assertEquals("vendor evidence mismatch", 2, d.getVendorEvidence().size()); + assertEquals("product evidence mismatch", 2, d.getProductEvidence().size()); + assertEquals("version evidence mismatch", 3, d.getVersionEvidence().size()); instance.analyze(d, null); - assertEquals("vendor evidence mismatch",1, d.getVendorEvidence().size()); - assertEquals("product evidence mismatch",1, d.getProductEvidence().size()); - assertEquals("version evidence mismatch",2, d.getVersionEvidence().size()); - + assertEquals("vendor evidence mismatch", 1, d.getVendorEvidence().size()); + assertEquals("product evidence mismatch", 1, d.getProductEvidence().size()); + assertEquals("version evidence mismatch", 2, d.getVersionEvidence().size()); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java index 4d9684f3d..d66a30aff 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java @@ -50,7 +50,8 @@ public class JarAnalyzerTest extends BaseTest { File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar"); Dependency result = new Dependency(file); JarAnalyzer instance = new JarAnalyzer(); - instance.initializeFileTypeAnalyzer(); + instance.initializeSettings(getSettings()); + instance.initializeFileTypeAnalyzer(null); instance.analyze(result, null); assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache")); assertTrue(result.getVendorEvidence().getWeighting().contains("apache")); @@ -115,7 +116,8 @@ public class JarAnalyzerTest extends BaseTest { @Test public void testAcceptSupportedExtensions() throws Exception { JarAnalyzer instance = new JarAnalyzer(); - instance.initialize(); + instance.initializeSettings(getSettings()); + instance.initialize(null); instance.setEnabled(true); String[] files = {"test.jar", "test.war"}; for (String name : files) { @@ -181,12 +183,12 @@ public class JarAnalyzerTest extends BaseTest { JarAnalyzer instance = new JarAnalyzer(); Dependency macOSMetaDataFile = new Dependency(); macOSMetaDataFile - .setActualFilePath(FileUtils.getFile("src", "test", "resources", "._avro-ipc-1.5.0.jar").getAbsolutePath()); + .setActualFilePath(FileUtils.getFile("src", "test", "resources", "._avro-ipc-1.5.0.jar").getAbsolutePath()); macOSMetaDataFile.setFileName("._avro-ipc-1.5.0.jar"); Dependency actualJarFile = new Dependency(); actualJarFile.setActualFilePath(BaseTest.getResourceAsFile(this, "avro-ipc-1.5.0.jar").getAbsolutePath()); actualJarFile.setFileName("avro-ipc-1.5.0.jar"); - Engine engine = new Engine(); + Engine engine = new Engine(getSettings()); engine.setDependencies(Arrays.asList(macOSMetaDataFile, actualJarFile)); instance.analyzeDependency(macOSMetaDataFile, engine); } @@ -196,9 +198,9 @@ public class JarAnalyzerTest extends BaseTest { JarAnalyzer instance = new JarAnalyzer(); Dependency textFileWithJarExtension = new Dependency(); textFileWithJarExtension - .setActualFilePath(BaseTest.getResourceAsFile(this, "textFileWithJarExtension.jar").getAbsolutePath()); + .setActualFilePath(BaseTest.getResourceAsFile(this, "textFileWithJarExtension.jar").getAbsolutePath()); textFileWithJarExtension.setFileName("textFileWithJarExtension.jar"); - Engine engine = new Engine(); + Engine engine = new Engine(getSettings()); engine.setDependencies(Collections.singletonList(textFileWithJarExtension)); instance.analyzeDependency(textFileWithJarExtension, engine); } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzerTest.java index 50c93a3eb..b43c1e5bf 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzerTest.java @@ -48,10 +48,13 @@ public class NodePackageAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new NodePackageAnalyzer(); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); } /** @@ -60,9 +63,10 @@ public class NodePackageAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NspAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NspAnalyzerTest.java index 9dca7d643..598972782 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NspAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NspAnalyzerTest.java @@ -16,16 +16,20 @@ public class NspAnalyzerTest extends BaseTest { private NspAnalyzer analyzer; @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new NspAnalyzer(); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); } @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } @Test diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzerTest.java index 6d184dd2a..63445fe90 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzerTest.java @@ -31,9 +31,12 @@ public class NuspecAnalyzerTest extends BaseTest { private NuspecAnalyzer instance; @Before + @Override public void setUp() throws Exception { + super.setUp(); instance = new NuspecAnalyzer(); - instance.initialize(); + instance.initializeSettings(getSettings()); + instance.initialize(null); instance.setEnabled(true); } @@ -53,5 +56,3 @@ public class NuspecAnalyzerTest extends BaseTest { assertEquals(AnalysisPhase.INFORMATION_COLLECTION, instance.getAnalysisPhase()); } } - -// vim: cc=120:sw=4:ts=4:sts=4 diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java index b3cca4878..06205bbeb 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java @@ -47,10 +47,13 @@ public class OpenSSLAnalyzerTest extends BaseTest { * @throws Exception if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new OpenSSLAnalyzer(); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); } /** @@ -59,9 +62,10 @@ public class OpenSSLAnalyzerTest extends BaseTest { * @throws Exception if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** @@ -69,8 +73,7 @@ public class OpenSSLAnalyzerTest extends BaseTest { */ @Test public void testGetName() { - assertEquals("Analyzer name wrong.", "OpenSSL Source Analyzer", - analyzer.getName()); + assertEquals("Analyzer name wrong.", "OpenSSL Source Analyzer", analyzer.getName()); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java index f788b9965..599ca7051 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java @@ -49,10 +49,13 @@ public class PythonDistributionAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new PythonDistributionAnalyzer(); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); } /** @@ -61,9 +64,10 @@ public class PythonDistributionAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java index 74d594535..39354a515 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java @@ -48,10 +48,13 @@ public class PythonPackageAnalyzerTest extends BaseTest { * @throws Exception if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new PythonPackageAnalyzer(); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initializeSettings(getSettings()); + analyzer.initialize(null); } /** @@ -60,9 +63,10 @@ public class PythonPackageAnalyzerTest extends BaseTest { * @throws Exception if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java index b7b2b9b85..4d461aee5 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java @@ -54,7 +54,7 @@ import org.owasp.dependencycheck.exception.InitializationException; * @author Dale Visser */ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { - + private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzerTest.class); /** @@ -68,11 +68,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + super.setUp(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); analyzer = new RubyBundleAuditAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); } @@ -82,11 +85,13 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { if (analyzer != null) { analyzer.close(); analyzer = null; } + super.tearDown(); } /** @@ -113,14 +118,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { @Test public void testAnalysis() throws AnalysisException, DatabaseException { try { - analyzer.initialize(); + analyzer.initialize(null); final String resource = "ruby/vulnerable/gems/rails-4.1.15/Gemfile.lock"; final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, resource)); - final Engine engine = new Engine(); + final Engine engine = new Engine(getSettings()); analyzer.analyze(result, engine); int size = engine.getDependencies().size(); assertTrue(size >= 1); - + Dependency dependency = engine.getDependencies().get(0); assertTrue(dependency.getProductEvidence().toString().toLowerCase().contains("redcarpet")); assertTrue(dependency.getVersionEvidence().toString().toLowerCase().contains("2.2.2")); @@ -138,17 +143,17 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { @Test public void testAddCriticalityToVulnerability() throws AnalysisException, DatabaseException { try { - analyzer.initialize(); - + analyzer.initialize(null); + final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "ruby/vulnerable/gems/sinatra/Gemfile.lock")); - final Engine engine = new Engine(); + final Engine engine = new Engine(getSettings()); analyzer.analyze(result, engine); - + Dependency dependency = engine.getDependencies().get(0); Vulnerability vulnerability = dependency.getVulnerabilities().first(); assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0); - + } catch (InitializationException | DatabaseException | AnalysisException e) { LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\"."); Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e); @@ -163,10 +168,11 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { @Test public void testMissingBundleAudit() throws AnalysisException, DatabaseException { //set a non-exist bundle-audit - Settings.setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit"); + getSettings().setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit"); + analyzer.initializeSettings(getSettings()); try { //initialize should fail. - analyzer.initialize(); + analyzer.initialize(null); } catch (Exception e) { //expected, so ignore. assertNotNull(e); @@ -184,7 +190,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { */ @Test public void testDependenciesPath() throws AnalysisException, DatabaseException { - final Engine engine = new Engine(); + final Engine engine = new Engine(getSettings()); engine.scan(BaseTest.getResourceAsFile(this, "ruby/vulnerable/gems/rails-4.1.15/")); try { @@ -202,14 +208,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { while (dIterator.hasNext()) { Dependency dept = dIterator.next(); LOGGER.info("dept path: {}", dept.getActualFilePath()); - + Set identifiers = dept.getIdentifiers(); Iterator idIterator = identifiers.iterator(); while (idIterator.hasNext()) { Identifier id = idIterator.next(); LOGGER.info(" Identifier: {}, type={}, url={}, conf={}", id.getValue(), id.getType(), id.getUrl(), id.getConfidence()); } - + Set prodEv = dept.getProductEvidence().getEvidence(); Iterator it = prodEv.iterator(); while (it.hasNext()) { @@ -222,7 +228,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { Evidence e = vIt.next(); LOGGER.info(" version: name={}, value={}, source={}, confidence={}", e.getName(), e.getValue(), e.getSource(), e.getConfidence()); } - + Set vendorEv = dept.getVendorEvidence().getEvidence(); Iterator vendorIt = vendorEv.iterator(); while (vendorIt.hasNext()) { diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundlerAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundlerAnalyzerTest.java index cfab09c4e..fc5662d19 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundlerAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundlerAnalyzerTest.java @@ -48,10 +48,13 @@ public class RubyBundlerAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new RubyBundlerAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initialize(null); } /** @@ -60,9 +63,10 @@ public class RubyBundlerAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzerTest.java index 4521504be..96ceb9e80 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyGemspecAnalyzerTest.java @@ -48,10 +48,13 @@ public class RubyGemspecAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); analyzer = new RubyGemspecAnalyzer(); + analyzer.initializeSettings(getSettings()); analyzer.setFilesMatched(true); - analyzer.initialize(); + analyzer.initialize(null); } /** @@ -60,9 +63,10 @@ public class RubyGemspecAnalyzerTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { analyzer.close(); - analyzer = null; + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/SwiftAnalyzersTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/SwiftAnalyzersTest.java index 8b81bbe3e..7ca4a6852 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/SwiftAnalyzersTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/SwiftAnalyzersTest.java @@ -32,14 +32,18 @@ public class SwiftAnalyzersTest extends BaseTest { * @throws Exception thrown if there is a problem */ @Before + @Override public void setUp() throws Exception { + super.setUp(); podsAnalyzer = new CocoaPodsAnalyzer(); + podsAnalyzer.initializeSettings(getSettings()); podsAnalyzer.setFilesMatched(true); - podsAnalyzer.initialize(); + podsAnalyzer.initialize(null); spmAnalyzer = new SwiftPackageManagerAnalyzer(); + spmAnalyzer.initializeSettings(getSettings()); spmAnalyzer.setFilesMatched(true); - spmAnalyzer.initialize(); + spmAnalyzer.initialize(null); } /** @@ -48,12 +52,15 @@ public class SwiftAnalyzersTest extends BaseTest { * @throws Exception thrown if there is a problem */ @After + @Override public void tearDown() throws Exception { podsAnalyzer.close(); podsAnalyzer = null; spmAnalyzer.close(); spmAnalyzer = null; + + super.tearDown(); } /** diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VersionFilterAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VersionFilterAnalyzerTest.java index f92ea8809..d8c957f1c 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VersionFilterAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VersionFilterAnalyzerTest.java @@ -48,6 +48,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { @Test public void testGetAnalysisPhase() { VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); AnalysisPhase expResult = AnalysisPhase.POST_INFORMATION_COLLECTION; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); @@ -60,6 +61,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { @Test public void testGetAnalyzerEnabledSettingKey() { VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); String expResult = Settings.KEYS.ANALYZER_VERSION_FILTER_ENABLED; String result = instance.getAnalyzerEnabledSettingKey(); assertEquals(expResult, result); @@ -78,6 +80,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST); VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); instance.analyzeDependency(dependency, null); assertEquals(3, versions.size()); @@ -119,6 +122,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST); VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); instance.analyzeDependency(dependency, null); assertEquals(3, versions.size()); @@ -156,6 +160,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST); VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); instance.analyzeDependency(dependency, null); assertEquals(3, versions.size()); @@ -183,6 +188,7 @@ public class VersionFilterAnalyzerTest extends BaseTest { versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST); VersionFilterAnalyzer instance = new VersionFilterAnalyzer(); + instance.initializeSettings(getSettings()); instance.analyzeDependency(dependency, null); assertEquals(3, versions.size()); @@ -206,5 +212,4 @@ public class VersionFilterAnalyzerTest extends BaseTest { instance.analyzeDependency(dependency, null); assertEquals(4, versions.size()); } - } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VulnerabilitySuppressionAnalyzerIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VulnerabilitySuppressionAnalyzerIT.java index 807a84666..a7df7717f 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VulnerabilitySuppressionAnalyzerIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/VulnerabilitySuppressionAnalyzerIT.java @@ -42,17 +42,20 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase { @Test public void testGetName() { VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer(); + instance.initializeSettings(getSettings()); String expResult = "Vulnerability Suppression Analyzer"; String result = instance.getName(); assertEquals(expResult, result); } /** - * Test of getAnalysisPhase method, of class VulnerabilitySuppressionAnalyzer. + * Test of getAnalysisPhase method, of class + * VulnerabilitySuppressionAnalyzer. */ @Test public void testGetAnalysisPhase() { VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer(); + instance.initializeSettings(getSettings()); AnalysisPhase expResult = AnalysisPhase.POST_FINDING_ANALYSIS; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); @@ -68,10 +71,10 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase { File file = BaseTest.getResourceAsFile(this, "commons-fileupload-1.2.1.jar"); //File suppression = new File(this.getClass().getClassLoader().getResource("commons-fileupload-1.2.1.suppression.xml").getPath()); File suppression = BaseTest.getResourceAsFile(this, "commons-fileupload-1.2.1.suppression.xml"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); - Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false); + getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false); + Engine engine = new Engine(getSettings()); engine.scan(file); engine.analyzeDependencies(); Dependency dependency = getDependency(engine, file); @@ -79,9 +82,10 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase { int cpeSize = dependency.getIdentifiers().size(); assertTrue(cveSize > 0); assertTrue(cpeSize > 0); - Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppression.getAbsolutePath()); + getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, suppression.getAbsolutePath()); VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer(); - instance.initialize(); + instance.initializeSettings(getSettings()); + instance.initialize(engine); instance.analyze(dependency, engine); cveSize = cveSize > 1 ? cveSize - 2 : 0; cpeSize = cpeSize > 0 ? cpeSize - 1 : 0; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/central/CentralSearchTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/central/CentralSearchTest.java index a23f4e866..0cccfe79d 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/central/CentralSearchTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/central/CentralSearchTest.java @@ -22,10 +22,10 @@ public class CentralSearchTest extends BaseTest { private CentralSearch searcher; @Before + @Override public void setUp() throws Exception { - String centralUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL); - LOGGER.debug(centralUrl); - searcher = new CentralSearch(new URL(centralUrl)); + super.setUp(); + searcher = new CentralSearch(getSettings()); } @Test(expected = IllegalArgumentException.class) diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/composer/ComposerLockParserTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/composer/ComposerLockParserTest.java index b325decf0..162258db6 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/composer/ComposerLockParserTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/composer/ComposerLockParserTest.java @@ -35,7 +35,9 @@ public class ComposerLockParserTest extends BaseTest { private InputStream inputStream; @Before - public void setUp() { + @Override + public void setUp() throws Exception { + super.setUp(); inputStream = this.getClass().getClassLoader().getResourceAsStream("composer.lock"); } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nexus/NexusSearchTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nexus/NexusSearchTest.java index e565bf524..c77c90051 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nexus/NexusSearchTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nexus/NexusSearchTest.java @@ -18,7 +18,6 @@ package org.owasp.dependencycheck.data.nexus; import java.io.FileNotFoundException; -import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Assume; @@ -26,7 +25,6 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; -import org.owasp.dependencycheck.analyzer.NexusAnalyzer; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,10 +35,12 @@ public class NexusSearchTest extends BaseTest { private NexusSearch searcher; @Before + @Override public void setUp() throws Exception { - String nexusUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); + super.setUp(); + String nexusUrl = getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL); LOGGER.debug(nexusUrl); - searcher = new NexusSearch(new URL(nexusUrl), NexusAnalyzer.useProxy()); + searcher = new NexusSearch(getSettings(), false); Assume.assumeTrue(searcher.preflightRequest()); } @@ -78,5 +78,3 @@ public class NexusSearchTest extends BaseTest { searcher.searchSha1("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); } } - -// vim: cc=120:sw=4:ts=4:sts=4 diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/NspSearchTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/NspSearchTest.java index 57569224a..d1d6298e6 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/NspSearchTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/NspSearchTest.java @@ -22,7 +22,6 @@ import org.junit.Before; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; -import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.json.Json; @@ -30,7 +29,6 @@ import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import java.io.InputStream; -import java.net.URL; import java.util.List; import static org.junit.Assume.assumeFalse; import org.owasp.dependencycheck.utils.URLConnectionFailureException; @@ -41,10 +39,10 @@ public class NspSearchTest extends BaseTest { private NspSearch searcher; @Before + @Override public void setUp() throws Exception { - String url = Settings.getString(Settings.KEYS.ANALYZER_NSP_URL); - LOGGER.debug(url); - searcher = new NspSearch(new URL(url)); + super.setUp(); + searcher = new NspSearch(getSettings()); } @Test diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/SanitizePackageTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/SanitizePackageTest.java index 8f0c74d7b..45cace154 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/SanitizePackageTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nsp/SanitizePackageTest.java @@ -61,5 +61,4 @@ public class SanitizePackageTest { Assert.assertFalse(sanitized.containsKey("license")); Assert.assertFalse(sanitized.containsKey("main")); } - } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java index 4316c7311..18d1f778f 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java @@ -35,10 +35,11 @@ public class ConnectionFactoryTest extends BaseDBTestCase { */ @Test public void testInitialize() throws DatabaseException, SQLException { - ConnectionFactory.initialize(); - try (Connection result = ConnectionFactory.getConnection()) { + ConnectionFactory factory = new ConnectionFactory(getSettings()); + factory.initialize(); + try (Connection result = factory.getConnection()) { assertNotNull(result); } - ConnectionFactory.cleanup(); + factory.cleanup(); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBIT.java index 3ff98ee36..2ae6e8409 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBIT.java @@ -27,51 +27,47 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.junit.After; import org.junit.Test; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.junit.Before; /** * * @author Jeremy Long */ public class CveDBIT extends BaseDBTestCase { + + CveDB instance = null; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = new CveDB(getSettings()); + } + + @After + @Override + public void tearDown() throws Exception { + instance.close(); + super.tearDown(); + } /** * Pretty useless tests of open, commit, and close methods, of class CveDB. */ @Test public void testOpen() { - CveDB instance = null; + try { - instance = CveDB.getInstance(); instance.commit(); } catch (DatabaseException | SQLException ex) { fail(ex.getMessage()); - } finally { - int start = instance.getUsageCount(); - instance.close(); - int end = instance.getUsageCount(); - assertTrue( end < start); } } @@ -80,12 +76,10 @@ public class CveDBIT extends BaseDBTestCase { */ @Test public void testGetCPEs() throws Exception { - CveDB instance = CveDB.getInstance(); String vendor = "apache"; String product = "struts"; Set result = instance.getCPEs(vendor, product); assertTrue(result.size() > 5); - instance.close(); } /** @@ -93,10 +87,8 @@ public class CveDBIT extends BaseDBTestCase { */ @Test public void testgetVulnerability() throws Exception { - CveDB instance = CveDB.getInstance(); Vulnerability result = instance.getVulnerability("CVE-2014-0094"); assertEquals("The ParametersInterceptor in Apache Struts before 2.3.16.1 allows remote attackers to \"manipulate\" the ClassLoader via the class parameter, which is passed to the getClass method.", result.getDescription()); - instance.close(); } /** @@ -105,7 +97,6 @@ public class CveDBIT extends BaseDBTestCase { @Test public void testGetVulnerabilities() throws Exception { String cpeStr = "cpe:/a:apache:struts:2.1.2"; - CveDB instance = CveDB.getInstance(); List results; results = instance.getVulnerabilities(cpeStr); @@ -133,7 +124,6 @@ public class CveDBIT extends BaseDBTestCase { } } assertTrue("Expected " + expected + ", but was not identified", found); - instance.close(); } /** @@ -141,7 +131,6 @@ public class CveDBIT extends BaseDBTestCase { */ @Test public void testGetMatchingSoftware() throws Exception { - CveDB instance = CveDB.getInstance(); Map versions = new HashMap<>(); DependencyVersion identifiedVersion = new DependencyVersion("1.0.1o"); versions.put("cpe:/a:openssl:openssl:1.0.1e", Boolean.FALSE); @@ -189,6 +178,5 @@ public class CveDBIT extends BaseDBTestCase { identifiedVersion = new DependencyVersion("1.6.3"); results = instance.getMatchingSoftware(versions, "springsource", "spring_framework", identifiedVersion); assertNotNull(results); - instance.close(); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBMySqlIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBMySqlIT.java index f3e6657c8..343b1c02b 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBMySqlIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/CveDBMySqlIT.java @@ -17,8 +17,10 @@ */ package org.owasp.dependencycheck.data.nvdcve; +import java.sql.SQLException; import java.util.List; import java.util.Set; +import org.junit.After; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; @@ -26,6 +28,7 @@ import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.VulnerableSoftware; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.junit.Before; /** * @@ -33,22 +36,32 @@ import static org.junit.Assert.fail; */ public class CveDBMySqlIT extends BaseTest { + CveDB instance = null; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + instance = new CveDB(getSettings()); + } + + @After + @Override + public void tearDown() throws Exception { + instance.close(); + super.tearDown(); + } + /** * Pretty useless tests of open, commit, and close methods, of class CveDB. */ @Test public void testOpen() { - CveDB instance = null; try { - instance = CveDB.getInstance(); - } catch (DatabaseException ex) { + instance.commit(); + } catch (SQLException | DatabaseException ex) { System.out.println("Unable to connect to the My SQL database; verify that the db server is running and that the schema has been generated"); fail(ex.getMessage()); - } finally { - int start = instance.getUsageCount(); - instance.close(); - int end = instance.getUsageCount(); - assertTrue( end < start); } } @@ -57,7 +70,6 @@ public class CveDBMySqlIT extends BaseTest { */ @Test public void testGetCPEs() throws Exception { - CveDB instance = CveDB.getInstance(); try { String vendor = "apache"; String product = "struts"; @@ -66,8 +78,6 @@ public class CveDBMySqlIT extends BaseTest { } catch (Exception ex) { System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated"); throw ex; - } finally { - instance.close(); } } @@ -77,15 +87,12 @@ public class CveDBMySqlIT extends BaseTest { @Test public void testGetVulnerabilities() throws Exception { String cpeStr = "cpe:/a:apache:struts:2.1.2"; - CveDB instance = CveDB.getInstance(); try { List result = instance.getVulnerabilities(cpeStr); assertTrue(result.size() > 5); } catch (Exception ex) { System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated"); throw ex; - } finally { - instance.close(); } } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DatabasePropertiesIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DatabasePropertiesIT.java index 1d4b9ac1b..aa54294b1 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DatabasePropertiesIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DatabasePropertiesIT.java @@ -19,14 +19,13 @@ package org.owasp.dependencycheck.data.nvdcve; import org.owasp.dependencycheck.BaseDBTestCase; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import org.junit.After; import org.junit.Test; import org.owasp.dependencycheck.data.update.nvd.NvdCveInfo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import org.junit.Before; /** * @@ -34,17 +33,31 @@ import static org.junit.Assert.assertTrue; */ public class DatabasePropertiesIT extends BaseDBTestCase { + CveDB cveDb = null; + + @Before + @Override + public void setUp() throws Exception { + super.setUp(); + cveDb = new CveDB(getSettings()); + } + + @After + @Override + public void tearDown() throws Exception { + cveDb.close(); + super.tearDown(); + } + /** * Test of isEmpty method, of class DatabaseProperties. */ @Test public void testIsEmpty() throws Exception { - CveDB cveDB = CveDB.getInstance(); - DatabaseProperties instance = cveDB.getDatabaseProperties(); - assertNotNull(instance); + DatabaseProperties prop = cveDb.getDatabaseProperties(); + assertNotNull(prop); //no exception means the call worked... whether or not it is empty depends on if the db is new //assertEquals(expResult, result); - cveDB.close(); } /** @@ -57,13 +70,11 @@ public class DatabasePropertiesIT extends BaseDBTestCase { long expected = 1337; updatedValue.setId(key); updatedValue.setTimestamp(expected); - CveDB cveDB = CveDB.getInstance(); - DatabaseProperties instance = cveDB.getDatabaseProperties(); + DatabaseProperties instance = cveDb.getDatabaseProperties(); instance.save(updatedValue); - instance = cveDB.reloadProperties(); + instance = cveDb.reloadProperties(); long results = Long.parseLong(instance.getProperty("NVD CVE " + key)); assertEquals(expected, results); - cveDB.close(); } /** @@ -73,12 +84,10 @@ public class DatabasePropertiesIT extends BaseDBTestCase { public void testGetProperty_String_String() throws Exception { String key = "doesn't exist"; String defaultValue = "default"; - CveDB cveDB = CveDB.getInstance(); - DatabaseProperties instance = cveDB.getDatabaseProperties(); + DatabaseProperties instance = cveDb.getDatabaseProperties(); String expResult = "default"; String result = instance.getProperty(key, defaultValue); assertEquals(expResult, result); - cveDB.close(); } /** @@ -87,13 +96,11 @@ public class DatabasePropertiesIT extends BaseDBTestCase { @Test public void testGetProperty_String() throws DatabaseException { String key = "version"; - CveDB cveDB = CveDB.getInstance(); - DatabaseProperties instance = cveDB.getDatabaseProperties(); + DatabaseProperties instance = cveDb.getDatabaseProperties(); String result = instance.getProperty(key); double version = Double.parseDouble(result); assertTrue(version >= 2.8); assertTrue(version <= 10); - cveDB.close(); } /** @@ -101,10 +108,9 @@ public class DatabasePropertiesIT extends BaseDBTestCase { */ @Test public void testGetProperties() throws DatabaseException { - CveDB cveDB = CveDB.getInstance(); - DatabaseProperties instance = cveDB.getDatabaseProperties(); + DatabaseProperties instance = cveDb.getDatabaseProperties(); Properties result = instance.getProperties(); assertTrue(result.size() > 0); - cveDB.close(); + cveDb.close(); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/EngineVersionCheckTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/EngineVersionCheckTest.java index 600b8cd0d..78991f6a8 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/EngineVersionCheckTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/EngineVersionCheckTest.java @@ -66,31 +66,31 @@ public class EngineVersionCheckTest extends BaseTest { public void testShouldUpdate() throws Exception { DatabaseProperties properties = new MockUp() { final private Properties properties = new Properties(); - + @Mock public void save(String key, String value) throws UpdateException { properties.setProperty(key, value); } - + @Mock public String getProperty(String key) { return properties.getProperty(key); } - + }.getMockInstance(); - + String updateToVersion = "1.2.6"; String currentVersion = "1.2.6"; - + long lastChecked = dateToMilliseconds("2014-12-01"); long now = dateToMilliseconds("2014-12-01"); - - EngineVersionCheck instance = new EngineVersionCheck(); + + EngineVersionCheck instance = new EngineVersionCheck(getSettings()); boolean expResult = false; instance.setUpdateToVersion(updateToVersion); boolean result = instance.shouldUpdate(lastChecked, now, properties, currentVersion); assertEquals(expResult, result); - + updateToVersion = "1.2.5"; currentVersion = "1.2.5"; lastChecked = dateToMilliseconds("2014-10-01"); @@ -109,7 +109,7 @@ public class EngineVersionCheckTest extends BaseTest { instance.setUpdateToVersion(updateToVersion); result = instance.shouldUpdate(lastChecked, now, properties, currentVersion); assertEquals(expResult, result); - + updateToVersion = "1.2.6"; currentVersion = "1.2.5"; lastChecked = dateToMilliseconds("2014-12-01"); @@ -118,7 +118,7 @@ public class EngineVersionCheckTest extends BaseTest { instance.setUpdateToVersion(updateToVersion); result = instance.shouldUpdate(lastChecked, now, properties, currentVersion); assertEquals(expResult, result); - + updateToVersion = "1.2.5"; currentVersion = "1.2.6"; lastChecked = dateToMilliseconds("2014-12-01"); @@ -127,7 +127,7 @@ public class EngineVersionCheckTest extends BaseTest { instance.setUpdateToVersion(updateToVersion); result = instance.shouldUpdate(lastChecked, now, properties, currentVersion); assertEquals(expResult, result); - + updateToVersion = ""; currentVersion = "1.2.5"; lastChecked = dateToMilliseconds("2014-12-01"); @@ -136,7 +136,7 @@ public class EngineVersionCheckTest extends BaseTest { instance.setUpdateToVersion(updateToVersion); result = instance.shouldUpdate(lastChecked, now, properties, currentVersion); assertEquals(expResult, result); - + updateToVersion = ""; currentVersion = "1.2.5"; lastChecked = dateToMilliseconds("2014-12-01"); @@ -152,7 +152,7 @@ public class EngineVersionCheckTest extends BaseTest { */ @Test public void testGetCurrentReleaseVersion() { - EngineVersionCheck instance = new EngineVersionCheck(); + EngineVersionCheck instance = new EngineVersionCheck(getSettings()); DependencyVersion minExpResult = new DependencyVersion("1.2.6"); String release = instance.getCurrentReleaseVersion(); DependencyVersion result = new DependencyVersion(release); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIT.java index 2d398d02d..cf987ad39 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIT.java @@ -17,14 +17,13 @@ */ package org.owasp.dependencycheck.data.update; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import org.junit.Test; import org.owasp.dependencycheck.BaseDBTestCase; import org.owasp.dependencycheck.data.update.exception.UpdateException; import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import org.owasp.dependencycheck.Engine; /** * @@ -32,31 +31,14 @@ import static org.junit.Assert.fail; */ public class NvdCveUpdaterIT extends BaseDBTestCase { - public NvdCveUpdater getUpdater() { - NvdCveUpdater instance = new NvdCveUpdater(); - instance.initializeExecutorServices(); - return instance; - } - - /** - * Test of update method. - */ - @Test - public void testUpdate() { - try { - NvdCveUpdater instance = getUpdater(); - instance.update(); - } catch (UpdateException ex) { - fail(ex.getMessage()); - } - } - /** * Test of updatesNeeded method. */ @Test public void testUpdatesNeeded() throws Exception { - NvdCveUpdater instance = getUpdater(); + NvdCveUpdater instance = new NvdCveUpdater(); + instance.setSettings(getSettings()); + instance.initializeExecutorServices(); UpdateableNvdCve result = instance.getUpdatesNeeded(); assertNotNull(result); } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/DownloadTaskTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/DownloadTaskTest.java index 347cec97b..11cac7bef 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/DownloadTaskTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/DownloadTaskTest.java @@ -44,11 +44,11 @@ public class DownloadTaskTest extends BaseTest { NvdCveInfo cve = new NvdCveInfo(); cve.setId("modified"); cve.setNeedsUpdate(true); - cve.setUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL)); - cve.setOldSchemaVersionUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL)); + cve.setUrl(getSettings().getString(Settings.KEYS.CVE_MODIFIED_20_URL)); + cve.setOldSchemaVersionUrl(getSettings().getString(Settings.KEYS.CVE_MODIFIED_12_URL)); ExecutorService processExecutor = null; CveDB cveDB = null; - DownloadTask instance = new DownloadTask(cve, processExecutor, cveDB, Settings.getInstance()); + DownloadTask instance = new DownloadTask(cve, processExecutor, cveDB, getSettings()); Future result = instance.call(); assertNull(result); } @@ -62,6 +62,5 @@ public class DownloadTaskTest extends BaseTest { assertTrue(DownloadTask.isXml(f)); f = getResourceAsFile(this, "file.tar.gz"); assertFalse(DownloadTask.isXml(f)); - } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/reporting/ReportGeneratorIT.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/reporting/ReportGeneratorIT.java index 719ba17b6..9ea6b14af 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/reporting/ReportGeneratorIT.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/reporting/ReportGeneratorIT.java @@ -58,7 +58,7 @@ public class ReportGeneratorIT extends BaseDBTestCase { File writeTo = new File("target/test-reports/Report.xml"); File suppressionFile = BaseTest.getResourceAsFile(this, "incorrectSuppressions.xml"); - Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile.getAbsolutePath()); + getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile.getAbsolutePath()); //File struts = new File(this.getClass().getClassLoader().getResource("struts2-core-2.1.2.jar").getPath()); File struts = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar"); @@ -67,8 +67,8 @@ public class ReportGeneratorIT extends BaseDBTestCase { //File jetty = new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath()); File jetty = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar"); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Engine engine = new Engine(); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + Engine engine = new Engine(getSettings()); engine.scan(struts); engine.scan(axis); diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java index b64e0b489..b758d6676 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java @@ -151,7 +151,7 @@ public class AggregateMojo extends BaseDependencyCheckMojo { throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol); } engine.cleanup(); - Settings.cleanup(); + getSettings().cleanup(); } /** diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java index dbebb3ab6..55199165e 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java @@ -84,6 +84,10 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma * A flag indicating whether or not the Maven site is being generated. */ private boolean generatingSite = false; + /** + * The configured settings. + */ + private Settings settings = null; // // /** @@ -931,7 +935,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma */ protected Engine initializeEngine() throws DatabaseException { populateSettings(); - return new Engine(); + return new Engine(settings); } /** @@ -940,11 +944,11 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma * proxy url, port, and connection timeout. */ protected void populateSettings() { - Settings.initialize(); + settings = new Settings(); InputStream mojoProperties = null; try { mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE); - Settings.mergeProperties(mojoProperties); + settings.mergeProperties(mojoProperties); } catch (IOException ex) { getLog().warn("Unable to load the dependency-check ant task.properties file."); if (getLog().isDebugEnabled()) { @@ -961,9 +965,9 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma } } } - Settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); + settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental); if (externalReport != null) { getLog().warn("The 'externalReport' option was set; this configuration option has been removed. " @@ -975,50 +979,50 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma } final Proxy proxy = getMavenProxy(); if (proxy != null) { - Settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost()); - Settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort())); + settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost()); + settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort())); final String userName = proxy.getUsername(); final String password = proxy.getPassword(); - Settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName); - Settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password); - Settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts()); + settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName); + settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password); + settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts()); } final String[] suppressions = determineSuppressions(); - Settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressions); + settings.setArrayIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressions); - Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); - Settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); + settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout); + settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile); //File Type Analyzer Settings - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled); - Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); - Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled); + settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions); + settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, nspAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled); - Settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled); - Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NSP_PACKAGE_ENABLED, nspAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled); + settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled); + settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled); //Database configuration - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName); + settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath); + settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString); if (databaseUser == null && databasePassword == null && serverId != null) { final Server server = settingsXml.getServer(serverId); @@ -1060,15 +1064,15 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma } } - Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); - Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); - Settings.setStringIfNotEmpty(Settings.KEYS.DATA_DIRECTORY, dataDirectory); + settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser); + settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword); + settings.setStringIfNotEmpty(Settings.KEYS.DATA_DIRECTORY, dataDirectory); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); - Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); - Settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base); + settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base); + settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours); artifactScopeExcluded = new ArtifactScopeExcluded(skipTestScope, skipProvidedScope, skipSystemScope, skipRuntimeScope); artifactTypeExcluded = new ArtifactTypeExcluded(skipArtifactType); @@ -1161,6 +1165,15 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma return artifactScopeExcluded; } + /** + * Returns the configured settings. + * + * @return the configured settings + */ + protected Settings getSettings() { + return settings; + } + // /** * Checks to see if a vulnerability has been identified with a CVSS score diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java index 04d36feac..02cc39947 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java @@ -131,7 +131,7 @@ public class CheckMojo extends BaseDependencyCheckMojo { } engine.cleanup(); } - Settings.cleanup(); + getSettings().cleanup(); } /** diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java index 42960fd5f..22b5f9e8d 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java @@ -73,7 +73,7 @@ public class PurgeMojo extends BaseDependencyCheckMojo { populateSettings(); File db; try { - db = new File(Settings.getDataDirectory(), Settings.getString(Settings.KEYS.DB_FILE_NAME, "dc.h2.db")); + db = new File(getSettings().getDataDirectory(), getSettings().getString(Settings.KEYS.DB_FILE_NAME, "dc.h2.db")); if (db.exists()) { if (db.delete()) { getLog().info("Database file purged; local copy of the NVD has been removed"); @@ -98,7 +98,7 @@ public class PurgeMojo extends BaseDependencyCheckMojo { } getLog().error(msg); } - Settings.cleanup(); + getSettings().cleanup(); } } diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java index b212f6042..b11045a7b 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java @@ -83,7 +83,7 @@ public class UpdateMojo extends BaseDependencyCheckMojo { } getLog().error(msg); } finally { - Settings.cleanup(); + getSettings().cleanup(); } } diff --git a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java index 6ac427185..da3b0015a 100644 --- a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java +++ b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java @@ -90,10 +90,10 @@ public class BaseDependencyCheckMojoTest extends BaseTest { } }.getMockInstance(); - boolean autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false); - Engine engine = new Engine(); - Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); + boolean autoUpdate = getSettings().getBoolean(Settings.KEYS.AUTO_UPDATE); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false); + Engine engine = new Engine(getSettings()); + getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); assertTrue(engine.getDependencies().isEmpty()); BaseDependencyCheckMojoImpl instance = new BaseDependencyCheckMojoImpl(); diff --git a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java index 4181facd0..7892f7aa9 100644 --- a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java +++ b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java @@ -17,8 +17,11 @@ */ package org.owasp.dependencycheck.maven; +import java.io.IOException; import java.io.InputStream; +import org.junit.After; import org.junit.AfterClass; +import org.junit.Before; import org.junit.BeforeClass; import org.owasp.dependencycheck.utils.Settings; @@ -33,16 +36,36 @@ public class BaseTest { */ public static final String PROPERTIES_FILE = "mojo.properties"; - @BeforeClass - public static void setUpClass() throws Exception { - Settings.initialize(); + /** + * The configured settings. + */ + private Settings settings; + + /** + * Initialize the {@link Settings}. + */ + @Before + public void setUp() throws IOException { + settings = new Settings(); try (InputStream mojoProperties = BaseTest.class.getClassLoader().getResourceAsStream(BaseTest.PROPERTIES_FILE)) { - Settings.mergeProperties(mojoProperties); + settings.mergeProperties(mojoProperties); } } - @AfterClass - public static void tearDownClass() throws Exception { - Settings.cleanup(true); + /** + * Clean the {@link Settings}. + */ + @After + public void tearDown() { + settings.cleanup(true); + } + + /** + * Returns the settings for the test cases. + * + * @return + */ + protected Settings getSettings() { + return settings; } } diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java index 14dc720a3..c2687caf1 100755 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java @@ -62,9 +62,23 @@ public final class Downloader { private static final String GET = "GET"; /** - * Private constructor for utility class. + * The configured settings. */ - private Downloader() { + private final Settings settings; + + /** + * The URL connection facctory. + */ + private final URLConnectionFactory connFactory; + + /** + * Constructs a new downloader object. + * + * @param settings the configured settings + */ + public Downloader(Settings settings) { + this.settings = settings; + this.connFactory = new URLConnectionFactory(settings); } /** @@ -75,7 +89,7 @@ public final class Downloader { * @throws DownloadFailedException is thrown if there is an error * downloading the file */ - public static void fetchFile(URL url, File outputPath) throws DownloadFailedException { + public void fetchFile(URL url, File outputPath) throws DownloadFailedException { fetchFile(url, outputPath, true); } @@ -89,7 +103,7 @@ public final class Downloader { * @throws DownloadFailedException is thrown if there is an error * downloading the file */ - public static void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException { + public void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException { if ("file".equalsIgnoreCase(url.getProtocol())) { File file; try { @@ -113,7 +127,7 @@ public final class Downloader { HttpURLConnection conn = null; try { LOGGER.debug("Attempting download of {}", url.toString()); - conn = URLConnectionFactory.createHttpURLConnection(url, useProxy); + conn = connFactory.createHttpURLConnection(url, useProxy); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); int status = conn.getResponseCode(); @@ -129,7 +143,7 @@ public final class Downloader { conn = null; } LOGGER.debug("Download is being redirected from {} to {}", url.toString(), location); - conn = URLConnectionFactory.createHttpURLConnection(new URL(location), useProxy); + conn = connFactory.createHttpURLConnection(new URL(location), useProxy); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); status = conn.getResponseCode(); @@ -217,7 +231,7 @@ public final class Downloader { * @throws DownloadFailedException is thrown if an exception occurs making * the HTTP request */ - public static long getLastModified(URL url) throws DownloadFailedException { + public long getLastModified(URL url) throws DownloadFailedException { return getLastModified(url, false); } @@ -233,7 +247,7 @@ public final class Downloader { * @throws DownloadFailedException is thrown if an exception occurs making * the HTTP request */ - private static long getLastModified(URL url, boolean isRetry) throws DownloadFailedException { + private long getLastModified(URL url, boolean isRetry) throws DownloadFailedException { long timestamp = 0; //TODO add the FTP protocol? if ("file".equalsIgnoreCase(url.getProtocol())) { @@ -249,7 +263,7 @@ public final class Downloader { final String httpMethod = determineHttpMethod(); HttpURLConnection conn = null; try { - conn = URLConnectionFactory.createHttpURLConnection(url); + conn = connFactory.createHttpURLConnection(url); conn.setRequestMethod(httpMethod); conn.connect(); final int t = conn.getResponseCode(); @@ -269,8 +283,8 @@ public final class Downloader { } try { //retry - if (!isRetry && Settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP)) { - Settings.setBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, false); + if (!isRetry && settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP)) { + settings.setBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, false); return getLastModified(url, true); } } catch (InvalidSettingException ex1) { @@ -300,7 +314,7 @@ public final class Downloader { * @throws DownloadFailedException a wrapper exception that contains the * original exception as the cause */ - protected static synchronized void checkForCommonExceptionTypes(IOException ex) throws DownloadFailedException { + protected synchronized void checkForCommonExceptionTypes(IOException ex) throws DownloadFailedException { Throwable cause = ex; while (cause != null) { if (cause instanceof java.net.UnknownHostException) { @@ -328,7 +342,7 @@ public final class Downloader { * * @return the HTTP method to use */ - private static String determineHttpMethod() { + private String determineHttpMethod() { return isQuickQuery() ? HEAD : GET; } @@ -338,11 +352,11 @@ public final class Downloader { * * @return true if configured to use HEAD requests */ - private static boolean isQuickQuery() { + private boolean isQuickQuery() { boolean quickQuery; try { - quickQuery = Settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, true); + quickQuery = settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, true); } catch (InvalidSettingException e) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Invalid settings : {}", e.getMessage(), e); diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java index 50df24f14..88d8aa798 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/FileUtils.java @@ -101,25 +101,6 @@ public final class FileUtils { return tempDir; } - /** - * Generates a new temporary file name that is guaranteed to be unique. - * - * @param prefix the prefix for the file name to generate - * @param extension the extension of the generated file name - * @return a temporary File - * @throws java.io.IOException thrown if the temporary folder could not be - * created - */ - public static File getTempFile(String prefix, String extension) throws IOException { - final File dir = Settings.getTempDirectory(); - final String tempFileName = String.format("%s%s.%s", prefix, UUID.randomUUID().toString(), extension); - final File tempFile = new File(dir, tempFileName); - if (tempFile.exists()) { - return getTempFile(prefix, extension); - } - return tempFile; - } - /** * Return the bit bucket for the OS. '/dev/null' for Unix and 'NUL' for * Windows diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java index 4849de733..ff3663eaf 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java @@ -42,15 +42,21 @@ public class SSLSocketFactoryEx extends SSLSocketFactory { * The protocols. */ private String[] protocols; + /** + * The configured settings. + */ + private final Settings settings; /** * Constructs a new SSLSocketFactory. * + * @param settings reference to the configured settings * @throws NoSuchAlgorithmException thrown when an algorithm is not * supported * @throws KeyManagementException thrown if initialization fails */ - public SSLSocketFactoryEx() throws NoSuchAlgorithmException, KeyManagementException { + public SSLSocketFactoryEx(Settings settings) throws NoSuchAlgorithmException, KeyManagementException { + this.settings = settings; initSSLSocketFactoryEx(null, null, null); } @@ -60,11 +66,13 @@ public class SSLSocketFactoryEx extends SSLSocketFactory { * @param km the key manager * @param tm the trust manager * @param random secure random + * @param settings reference to the configured settings * @throws NoSuchAlgorithmException thrown when an algorithm is not * supported * @throws KeyManagementException thrown if initialization fails */ - public SSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { + public SSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random, Settings settings) throws NoSuchAlgorithmException, KeyManagementException { + this.settings = settings; initSSLSocketFactoryEx(km, tm, random); } @@ -72,11 +80,13 @@ public class SSLSocketFactoryEx extends SSLSocketFactory { * Constructs a new SSLSocketFactory. * * @param ctx the SSL context + * @param settings reference to the configured settings * @throws NoSuchAlgorithmException thrown when an algorithm is not * supported * @throws KeyManagementException thrown if initialization fails */ - public SSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { + public SSLSocketFactoryEx(SSLContext ctx, Settings settings) throws NoSuchAlgorithmException, KeyManagementException { + this.settings = settings; initSSLSocketFactoryEx(ctx); } @@ -254,7 +264,7 @@ public class SSLSocketFactoryEx extends SSLSocketFactory { protected String[] getProtocolList() { SSLSocket socket = null; String[] availableProtocols = null; - final String[] preferredProtocols = Settings.getString( + final String[] preferredProtocols = settings.getString( Settings.KEYS.DOWNLOADER_TLS_PROTOCOL_LIST, "TLSv1,TLSv1.1,TLSv1.2,TLSv1.3") .split(","); diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index f8bf932cc..91148f23c 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -32,6 +32,7 @@ import java.net.URLDecoder; import java.security.ProtectionDomain; import java.util.Enumeration; import java.util.Properties; +import java.util.UUID; import org.apache.commons.lang3.StringUtils; @@ -54,10 +55,6 @@ public final class Settings { * Array separator. */ private static final String ARRAY_SEP = ","; - /** - * Thread local settings. - */ - private static final ThreadLocal LOCAL_SETTINGS = new ThreadLocal<>(); /** * The properties. */ @@ -67,7 +64,7 @@ public final class Settings { * A reference to the temporary directory; used in case it needs to be * deleted during cleanup. */ - private static File tempDirectory = null; + private File tempDirectory = null; // /** @@ -448,13 +445,25 @@ public final class Settings { } // + public Settings() { + initialize(PROPERTIES_FILE); + } + /** - * Private constructor for the Settings class. This class loads the - * properties files. + * This class loads the settings from the given properties file. * * @param propertiesFilePath the path to the base properties file to load */ - private Settings(String propertiesFilePath) { + public Settings(String propertiesFilePath) { + initialize(propertiesFilePath); + } + + /** + * Initializes the settings object from the given file. + * + * @param propertiesFilePath the path to the settings property file + */ + private final void initialize(String propertiesFilePath) { props = new Properties(); try (InputStream in = FileUtils.getResourceAsStream(propertiesFilePath)) { props.load(in); @@ -468,54 +477,11 @@ public final class Settings { logProperties("Properties loaded", props); } - /** - *

- * Initializes the thread local settings object. Note, to use the settings - * object you must call this method. However, you must also call - * Settings.cleanup() to properly release resources.

- * - *

- * Note - Only an end user interface such as the CLI, Maven Plugin, - * etc. should call initialize. When called `initialize` will over-write any - * configured settings (i.e. configured via the maven plugin) and the - * default values from dependency-check-core will be used. If you are - * running into issues with the settings not being initialized it is likely - * due to multi-threading and you should use the `Settings.setInstance` - * method instead. See the `TimestampRetriever` class within NvdCveUpdater - * as an example.

- * - */ - public static void initialize() { - LOCAL_SETTINGS.set(new Settings(PROPERTIES_FILE)); - } - - /** - *

- * Initializes the thread local settings object. Note, to use the settings - * object you must call this method. However, you must also call - * Settings.cleanup() to properly release resources.

- * - *

- * Note - Only an end user interface such as the CLI, Maven Plugin, - * etc. should call initialize. When called `initialize` will over-write any - * configured settings (i.e. configured via the maven plugin) and the - * default values from dependency-check-core will be used. If you are - * running into issues with the settings not being initialized it is likely - * due to multi-threading and you should use the `Settings.setInstance` - * method instead. See the `TimestampRetriever` class within NvdCveUpdater - * as an example.

- * - * @param propertiesFilePath the path to the base properties file to load - */ - public static void initialize(String propertiesFilePath) { - LOCAL_SETTINGS.set(new Settings(propertiesFilePath)); - } - /** * Cleans up resources to prevent memory leaks. * */ - public static void cleanup() { + public void cleanup() { cleanup(true); } @@ -525,39 +491,11 @@ public final class Settings { * @param deleteTemporary flag indicating whether any temporary directories * generated should be removed */ - public static synchronized void cleanup(boolean deleteTemporary) { + public synchronized void cleanup(boolean deleteTemporary) { if (deleteTemporary && tempDirectory != null && tempDirectory.exists()) { FileUtils.delete(tempDirectory); tempDirectory = null; } - try { - LOCAL_SETTINGS.remove(); - } catch (Throwable ex) { - LOGGER.debug("Error cleaning up Settings", ex); - } - } - - /** - * Gets the underlying instance of the Settings object. - * - * @return the Settings object - */ - public static Settings getInstance() { - return LOCAL_SETTINGS.get(); - } - - /** - *

- * Sets the instance of the Settings object to use in this thread.

- *

- * Note - if using this method to enable multi-threading one must - * call `Settings.cleanup(false)`. See the `TimestampRetriever` class within - * NvdCveUpdater as an example.

- * - * @param instance the instance of the settings object to use in this thread - */ - public static void setInstance(Settings instance) { - LOCAL_SETTINGS.set(instance); } /** @@ -567,7 +505,7 @@ public final class Settings { * @param header the header to print with the log message * @param properties the properties to log */ - private static void logProperties(String header, Properties properties) { + private void logProperties(String header, Properties properties) { if (LOGGER.isDebugEnabled()) { final StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { @@ -597,8 +535,8 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setString(String key, String value) { - LOCAL_SETTINGS.get().props.setProperty(key, value); + public void setString(String key, String value) { + props.setProperty(key, value); LOGGER.debug("Setting: {}='{}'", key, value); } @@ -608,7 +546,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setStringIfNotNull(String key, String value) { + public void setStringIfNotNull(String key, String value) { if (null != value) { setString(key, value); } @@ -620,7 +558,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setStringIfNotEmpty(String key, String value) { + public void setStringIfNotEmpty(String key, String value) { if (null != value && !value.isEmpty()) { setString(key, value); } @@ -632,7 +570,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setArrayIfNotEmpty(String key, String[] value) { + public void setArrayIfNotEmpty(String key, String[] value) { if (null != value && value.length > 0) { setString(key, StringUtils.join(value, ARRAY_SEP)); } @@ -644,7 +582,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setBoolean(String key, boolean value) { + public void setBoolean(String key, boolean value) { setString(key, Boolean.toString(value)); } @@ -654,7 +592,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setBooleanIfNotNull(String key, Boolean value) { + public void setBooleanIfNotNull(String key, Boolean value) { if (null != value) { setBoolean(key, value); } @@ -666,8 +604,8 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setInt(String key, int value) { - LOCAL_SETTINGS.get().props.setProperty(key, String.valueOf(value)); + public void setInt(String key, int value) { + props.setProperty(key, String.valueOf(value)); LOGGER.debug("Setting: {}='{}'", key, value); } @@ -677,7 +615,7 @@ public final class Settings { * @param key the key for the property * @param value the value for the property */ - public static void setIntIfNotNull(String key, Integer value) { + public void setIntIfNotNull(String key, Integer value) { if (null != value) { setInt(key, value); } @@ -695,7 +633,7 @@ public final class Settings { * @throws IOException is thrown when there is an exception loading/merging * the properties */ - public static void mergeProperties(File filePath) throws FileNotFoundException, IOException { + public void mergeProperties(File filePath) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(filePath)) { mergeProperties(fis); } @@ -713,7 +651,7 @@ public final class Settings { * @throws IOException is thrown when there is an exception loading/merging * the properties */ - public static void mergeProperties(String filePath) throws FileNotFoundException, IOException { + public void mergeProperties(String filePath) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(filePath)) { mergeProperties(fis); } @@ -729,9 +667,9 @@ public final class Settings { * @throws IOException is thrown when there is an exception loading/merging * the properties */ - public static void mergeProperties(InputStream stream) throws IOException { - LOCAL_SETTINGS.get().props.load(stream); - logProperties("Properties updated via merge", LOCAL_SETTINGS.get().props); + public void mergeProperties(InputStream stream) throws IOException { + props.load(stream); + logProperties("Properties updated via merge", props); } /** @@ -743,7 +681,7 @@ public final class Settings { * @param key the key to lookup within the properties file * @return the property from the properties file converted to a File object */ - public static File getFile(String key) { + public File getFile(String key) { final String file = getString(key); if (file == null) { return null; @@ -765,7 +703,7 @@ public final class Settings { * @param key the key to lookup within the properties file * @return the property from the properties file converted to a File object */ - protected static File getDataFile(String key) { + protected File getDataFile(String key) { final String file = getString(key); LOGGER.debug("Settings.getDataFile() - file: '{}'", file); if (file == null) { @@ -788,7 +726,7 @@ public final class Settings { * * @return a File object */ - private static File getJarPath() { + private File getJarPath() { String decodedPath = "."; String jarPath = ""; final ProtectionDomain domain = Settings.class.getProtectionDomain(); @@ -819,8 +757,8 @@ public final class Settings { * @param defaultValue the default value for the requested property * @return the property from the properties file */ - public static String getString(String key, String defaultValue) { - return System.getProperty(key, LOCAL_SETTINGS.get().props.getProperty(key, defaultValue)); + public String getString(String key, String defaultValue) { + return System.getProperty(key, props.getProperty(key, defaultValue)); } /** @@ -830,9 +768,9 @@ public final class Settings { * @throws java.io.IOException thrown if the temporary directory does not * exist and cannot be created */ - public static synchronized File getTempDirectory() throws IOException { + public synchronized File getTempDirectory() throws IOException { if (tempDirectory == null) { - final File baseTemp = new File(Settings.getString(Settings.KEYS.TEMP_DIRECTORY, System.getProperty("java.io.tmpdir"))); + final File baseTemp = new File(getString(Settings.KEYS.TEMP_DIRECTORY, System.getProperty("java.io.tmpdir"))); tempDirectory = FileUtils.createTempDirectory(baseTemp); } return tempDirectory; @@ -847,19 +785,19 @@ public final class Settings { * @param key the key to lookup within the properties file * @return the property from the properties file */ - public static String getString(String key) { - return System.getProperty(key, LOCAL_SETTINGS.get().props.getProperty(key)); + public String getString(String key) { + return System.getProperty(key, props.getProperty(key)); } /** * Returns a list with the given key. * - * If the propery is not set then {@code null} will be returned. + * If the property is not set then {@code null} will be returned. * - * @param key the key to get from this {@link Settings} singleton. + * @param key the key to get from this {@link Settings}. * @return the list or {@code null} if the key wasn't present. */ - public static String[] getArray(final String key) { + public String[] getArray(final String key) { final String string = getString(key); if (string != null) { return string.split(ARRAY_SEP); @@ -873,8 +811,8 @@ public final class Settings { * * @param key the property key to remove */ - public static void removeProperty(String key) { - LOCAL_SETTINGS.get().props.remove(key); + public void removeProperty(String key) { + props.remove(key); } /** @@ -888,9 +826,9 @@ public final class Settings { * @throws InvalidSettingException is thrown if there is an error retrieving * the setting */ - public static int getInt(String key) throws InvalidSettingException { + public int getInt(String key) throws InvalidSettingException { try { - return Integer.parseInt(Settings.getString(key)); + return Integer.parseInt(getString(key)); } catch (NumberFormatException ex) { throw new InvalidSettingException("Could not convert property '" + key + "' to an int.", ex); } @@ -907,13 +845,13 @@ public final class Settings { * @return the property from the properties file or the defaultValue if the * property does not exist or cannot be converted to an integer */ - public static int getInt(String key, int defaultValue) { + public int getInt(String key, int defaultValue) { int value; try { - value = Integer.parseInt(Settings.getString(key)); + value = Integer.parseInt(getString(key)); } catch (NumberFormatException ex) { - if (!Settings.getString(key, "").isEmpty()) { - LOGGER.debug("Could not convert property '{}={}' to an int; using {} instead.", key, Settings.getString(key), defaultValue); + if (!getString(key, "").isEmpty()) { + LOGGER.debug("Could not convert property '{}={}' to an int; using {} instead.", key, getString(key), defaultValue); } value = defaultValue; } @@ -931,9 +869,9 @@ public final class Settings { * @throws InvalidSettingException is thrown if there is an error retrieving * the setting */ - public static long getLong(String key) throws InvalidSettingException { + public long getLong(String key) throws InvalidSettingException { try { - return Long.parseLong(Settings.getString(key)); + return Long.parseLong(getString(key)); } catch (NumberFormatException ex) { throw new InvalidSettingException("Could not convert property '" + key + "' to a long.", ex); } @@ -951,8 +889,8 @@ public final class Settings { * @throws InvalidSettingException is thrown if there is an error retrieving * the setting */ - public static boolean getBoolean(String key) throws InvalidSettingException { - return Boolean.parseBoolean(Settings.getString(key)); + public boolean getBoolean(String key) throws InvalidSettingException { + return Boolean.parseBoolean(getString(key)); } /** @@ -969,8 +907,8 @@ public final class Settings { * @throws InvalidSettingException is thrown if there is an error retrieving * the setting */ - public static boolean getBoolean(String key, boolean defaultValue) throws InvalidSettingException { - return Boolean.parseBoolean(Settings.getString(key, Boolean.toString(defaultValue))); + public boolean getBoolean(String key, boolean defaultValue) throws InvalidSettingException { + return Boolean.parseBoolean(getString(key, Boolean.toString(defaultValue))); } /** @@ -986,9 +924,9 @@ public final class Settings { * @throws IOException thrown the data directory cannot be created * @throws InvalidSettingException thrown if there is an invalid setting */ - public static String getConnectionString(String connectionStringKey, String dbFileNameKey) + public String getConnectionString(String connectionStringKey, String dbFileNameKey) throws IOException, InvalidSettingException { - final String connStr = Settings.getString(connectionStringKey); + final String connStr = getString(connectionStringKey); if (connStr == null) { final String msg = String.format("Invalid properties file; %s is missing.", connectionStringKey); throw new InvalidSettingException(msg); @@ -997,7 +935,7 @@ public final class Settings { final File directory = getDataDirectory(); String fileName = null; if (dbFileNameKey != null) { - fileName = Settings.getString(dbFileNameKey); + fileName = getString(dbFileNameKey); } if (fileName == null) { final String msg = String.format("Invalid properties file to get a file based connection string; '%s' must be defined.", @@ -1024,12 +962,32 @@ public final class Settings { * @return the data directory to store data files * @throws IOException is thrown if an IOException occurs of course... */ - public static File getDataDirectory() throws IOException { - final File path = Settings.getDataFile(Settings.KEYS.DATA_DIRECTORY); + public File getDataDirectory() throws IOException { + final File path = getDataFile(Settings.KEYS.DATA_DIRECTORY); if (path != null && (path.exists() || path.mkdirs())) { return path; } throw new IOException(String.format("Unable to create the data directory '%s'", (path == null) ? "unknown" : path.getAbsolutePath())); } + + + /** + * Generates a new temporary file name that is guaranteed to be unique. + * + * @param prefix the prefix for the file name to generate + * @param extension the extension of the generated file name + * @return a temporary File + * @throws java.io.IOException thrown if the temporary folder could not be + * created + */ + public File getTempFile(String prefix, String extension) throws IOException { + final File dir = getTempDirectory(); + final String tempFileName = String.format("%s%s.%s", prefix, UUID.randomUUID().toString(), extension); + final File tempFile = new File(dir, tempFileName); + if (tempFile.exists()) { + return getTempFile(prefix, extension); + } + return tempFile; + } } diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/URLConnectionFactory.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/URLConnectionFactory.java index e8557aad0..b0423ae0f 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/URLConnectionFactory.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/URLConnectionFactory.java @@ -48,11 +48,18 @@ public final class URLConnectionFactory { * The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(URLConnectionFactory.class); + /** + * The configured settings. + */ + private final Settings settings; /** * Private constructor for this factory. + * + * @param settings reference to the configured settings */ - private URLConnectionFactory() { + public URLConnectionFactory(Settings settings) { + this.settings = settings; } /** @@ -65,17 +72,17 @@ public final class URLConnectionFactory { * @throws URLConnectionFailureException thrown if there is an exception */ @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe") - public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException { + public HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException { HttpURLConnection conn = null; - final String proxyHost = Settings.getString(Settings.KEYS.PROXY_SERVER); + final String proxyHost = settings.getString(Settings.KEYS.PROXY_SERVER); try { if (proxyHost != null && !matchNonProxy(url)) { - final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT); + final int proxyPort = settings.getInt(Settings.KEYS.PROXY_PORT); final SocketAddress address = new InetSocketAddress(proxyHost, proxyPort); - final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME); - final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD); + final String username = settings.getString(Settings.KEYS.PROXY_USERNAME); + final String password = settings.getString(Settings.KEYS.PROXY_PASSWORD); if (username != null && password != null) { final Authenticator auth = new Authenticator() { @@ -84,7 +91,7 @@ public final class URLConnectionFactory { if (proxyHost.equals(getRequestingHost()) || getRequestorType().equals(Authenticator.RequestorType.PROXY)) { LOGGER.debug("Using the configured proxy username and password"); try { - if (Settings.getBoolean(Settings.KEYS.PROXY_DISABLE_SCHEMAS, true)) { + if (settings.getBoolean(Settings.KEYS.PROXY_DISABLE_SCHEMAS, true)) { System.setProperty("jdk.http.auth.tunneling.disabledSchemes", ""); } } catch (InvalidSettingException ex) { @@ -103,8 +110,8 @@ public final class URLConnectionFactory { } else { conn = (HttpURLConnection) url.openConnection(); } - final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000); - conn.setConnectTimeout(timeout); + final int connectionTimeout = settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000); + conn.setConnectTimeout(connectionTimeout); conn.setInstanceFollowRedirects(true); } catch (IOException ex) { if (conn != null) { @@ -126,11 +133,11 @@ public final class URLConnectionFactory { * @param url the url to connect to * @return matching result. true: match nonProxy */ - private static boolean matchNonProxy(final URL url) { + private boolean matchNonProxy(final URL url) { final String host = url.getHost(); // code partially from org.apache.maven.plugins.site.AbstractDeployMojo#getProxyInfo - final String nonProxyHosts = Settings.getString(Settings.KEYS.PROXY_NON_PROXY_HOSTS); + final String nonProxyHosts = settings.getString(Settings.KEYS.PROXY_NON_PROXY_HOSTS); if (null != nonProxyHosts) { final String[] nonProxies = nonProxyHosts.split("(,)|(;)|(\\|)"); for (final String nonProxyHost : nonProxies) { @@ -172,14 +179,14 @@ public final class URLConnectionFactory { * @return a newly constructed HttpURLConnection * @throws URLConnectionFailureException thrown if there is an exception */ - public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException { + public HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException { if (proxy) { return createHttpURLConnection(url); } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); - final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000); + final int timeout = settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000); conn.setConnectTimeout(timeout); conn.setInstanceFollowRedirects(true); } catch (IOException ioe) { @@ -197,11 +204,11 @@ public final class URLConnectionFactory { * @param url the URL * @param conn the connection */ - private static void configureTLS(URL url, URLConnection conn) { + private void configureTLS(URL url, URLConnection conn) { if ("https".equals(url.getProtocol())) { try { final HttpsURLConnection secCon = (HttpsURLConnection) conn; - final SSLSocketFactoryEx factory = new SSLSocketFactoryEx(); + final SSLSocketFactoryEx factory = new SSLSocketFactoryEx(settings); secCon.setSSLSocketFactory(factory); } catch (NoSuchAlgorithmException ex) { LOGGER.debug("Unsupported algorithm in SSLSocketFactoryEx", ex); diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/BaseTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/BaseTest.java index a776c9f07..b2fdb4149 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/BaseTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/BaseTest.java @@ -15,8 +15,8 @@ */ package org.owasp.dependencycheck.utils; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.After; +import org.junit.Before; /** * @@ -24,13 +24,33 @@ import org.junit.BeforeClass; */ public class BaseTest { - @BeforeClass - public static void setUpClass() throws Exception { - Settings.initialize(); + /** + * The configured settings. + */ + private Settings settings; + + /** + * Initialize the {@link Settings}. + */ + @Before + public void setUp() { + settings = new Settings(); } - @AfterClass - public static void tearDownClass() throws Exception { - Settings.cleanup(true); + /** + * Clean the {@link Settings}. + */ + @After + public void tearDown() { + settings.cleanup(true); + } + + /** + * Returns the settings for the test cases. + * + * @return + */ + protected Settings getSettings() { + return settings; } } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderIT.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderIT.java index a181249f6..1c8ce0733 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderIT.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderIT.java @@ -40,16 +40,18 @@ public class DownloaderIT extends BaseTest { // Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, "1000"); // Settings.setString(Settings.KEYS.PROXY_PORT, "8080"); // Settings.setString(Settings.KEYS.PROXY_SERVER, "127.0.0.1"); - URL url = new URL(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL)); + URL url = new URL(getSettings().getString(Settings.KEYS.CVE_MODIFIED_20_URL)); File outputPath = new File("target/downloaded_cve.xml"); - Downloader.fetchFile(url, outputPath); + Downloader downloader = new Downloader(getSettings()); + downloader.fetchFile(url, outputPath); assertTrue(outputPath.isFile()); } @Test public void testGetLastModified() throws Exception { - URL url = new URL(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL)); - long timestamp = Downloader.getLastModified(url); + URL url = new URL(getSettings().getString(Settings.KEYS.CVE_MODIFIED_20_URL)); + Downloader downloader = new Downloader(getSettings()); + long timestamp = downloader.getLastModified(url); assertTrue("timestamp equal to zero?", timestamp > 0); } } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java index 7bc487fde..718b536cf 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java @@ -25,11 +25,12 @@ import org.junit.Test; * * @author Jeremy Long */ -public class DownloaderTest { +public class DownloaderTest extends BaseTest { @Test public void testGetLastModified_file() throws Exception { - long timestamp = Downloader.getLastModified(new File("target/test-classes/dependencycheck.properties").toURI().toURL()); + Downloader instance = new Downloader(getSettings()); + long timestamp = instance.getLastModified(new File("target/test-classes/dependencycheck.properties").toURI().toURL()); assertTrue("timestamp equal to zero?", timestamp > 0); } } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java index f6fc832b7..f075573b0 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/FileUtilsTest.java @@ -50,7 +50,7 @@ public class FileUtilsTest extends BaseTest { @Test public void testDelete() throws Exception { - File file = File.createTempFile("tmp", "deleteme", Settings.getTempDirectory()); + File file = File.createTempFile("tmp", "deleteme", getSettings().getTempDirectory()); if (!file.exists()) { fail("Unable to create a temporary file."); } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/SettingsTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/SettingsTest.java index a9087f9e7..32db4f4ba 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/SettingsTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/SettingsTest.java @@ -26,9 +26,7 @@ import java.io.File; import java.io.IOException; import java.net.URISyntaxException; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; /** @@ -37,22 +35,6 @@ import org.junit.Test; */ public class SettingsTest extends BaseTest { - /** - * Initialize the {@link Settings} singleton. - */ - @Before - public void setUp() { - Settings.initialize(); - } - - /** - * Clean the {@link Settings} singleton. - */ - @After - public void tearDown() { - Settings.cleanup(); - } - /** * Test of getString method, of class Settings. */ @@ -60,7 +42,7 @@ public class SettingsTest extends BaseTest { public void testGetString() { String key = Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS; String expResult = "7"; - String result = Settings.getString(key); + String result = getSettings().getString(key); Assert.assertTrue(result.endsWith(expResult)); } @@ -71,21 +53,23 @@ public class SettingsTest extends BaseTest { public void testGetDataFile() throws IOException { String key = Settings.KEYS.DATA_DIRECTORY; String expResult = "data"; - File result = Settings.getDataFile(key); + File result = getSettings().getDataFile(key); Assert.assertTrue(result.getAbsolutePath().endsWith(expResult)); } /** * Test of mergeProperties method, of class Settings. + * @throws java.io.IOException thrown when the test fails + * @throws java.net.URISyntaxException thrown when the test fails */ @Test public void testMergeProperties_String() throws IOException, URISyntaxException { String key = Settings.KEYS.PROXY_PORT; - String expResult = Settings.getString(key); + String expResult = getSettings().getString(key); File f = new File(this.getClass().getClassLoader().getResource("test.properties").toURI()); //InputStream in = this.getClass().getClassLoader().getResourceAsStream("test.properties"); - Settings.mergeProperties(f.getAbsolutePath()); - String result = Settings.getString(key); + getSettings().mergeProperties(f.getAbsolutePath()); + String result = getSettings().getString(key); Assert.assertTrue("setting didn't change?", (expResult == null && result != null) || !expResult.equals(result)); } @@ -96,8 +80,8 @@ public class SettingsTest extends BaseTest { public void testSetString() { String key = "newProperty"; String value = "someValue"; - Settings.setString(key, value); - String expResults = Settings.getString(key); + getSettings().setString(key, value); + String expResults = getSettings().getString(key); Assert.assertEquals(expResults, value); } @@ -108,9 +92,9 @@ public class SettingsTest extends BaseTest { public void testSetStringIfNotNull() { String key = "nullableProperty"; String value = "someValue"; - Settings.setString(key, value); - Settings.setStringIfNotNull(key, null); // NO-OP - String expResults = Settings.getString(key); + getSettings().setString(key, value); + getSettings().setStringIfNotNull(key, null); // NO-OP + String expResults = getSettings().getString(key); Assert.assertEquals(expResults, value); } @@ -121,9 +105,9 @@ public class SettingsTest extends BaseTest { public void testSetStringIfNotEmpty() { String key = "optionalProperty"; String value = "someValue"; - Settings.setString(key, value); - Settings.setStringIfNotEmpty(key, ""); // NO-OP - String expResults = Settings.getString(key); + getSettings().setString(key, value); + getSettings().setStringIfNotEmpty(key, ""); // NO-OP + String expResults = getSettings().getString(key); Assert.assertEquals(expResults, value); } @@ -135,9 +119,9 @@ public class SettingsTest extends BaseTest { String key = "key That Doesn't Exist"; String defaultValue = "blue bunny"; String expResult = "blue bunny"; - String result = Settings.getString(key); + String result = getSettings().getString(key); Assert.assertTrue(result == null); - result = Settings.getString(key, defaultValue); + result = getSettings().getString(key, defaultValue); Assert.assertEquals(expResult, result); } @@ -147,7 +131,7 @@ public class SettingsTest extends BaseTest { @Test public void testGetString_String() { String key = Settings.KEYS.CONNECTION_TIMEOUT; - String result = Settings.getString(key); + String result = getSettings().getString(key); Assert.assertTrue(result == null); } @@ -158,8 +142,8 @@ public class SettingsTest extends BaseTest { public void testGetInt() throws InvalidSettingException { String key = "SomeNumber"; int expResult = 85; - Settings.setString(key, "85"); - int result = Settings.getInt(key); + getSettings().setString(key, "85"); + int result = getSettings().getInt(key); Assert.assertEquals(expResult, result); } @@ -170,8 +154,8 @@ public class SettingsTest extends BaseTest { public void testGetIntDefault() throws InvalidSettingException { String key = "SomeKey"; int expResult = 85; - Settings.setString(key, "blue"); - int result = Settings.getInt(key, expResult); + getSettings().setString(key, "blue"); + int result = getSettings().getInt(key, expResult); Assert.assertEquals(expResult, result); } @@ -182,8 +166,8 @@ public class SettingsTest extends BaseTest { public void testGetLong() throws InvalidSettingException { String key = "SomeNumber"; long expResult = 300L; - Settings.setString(key, "300"); - long result = Settings.getLong(key); + getSettings().setString(key, "300"); + long result = getSettings().getLong(key); Assert.assertEquals(expResult, result); } @@ -193,14 +177,14 @@ public class SettingsTest extends BaseTest { @Test public void testGetBoolean() throws InvalidSettingException { String key = "SomeBoolean"; - Settings.setString(key, "false"); + getSettings().setString(key, "false"); boolean expResult = false; - boolean result = Settings.getBoolean(key); + boolean result = getSettings().getBoolean(key); Assert.assertEquals(expResult, result); key = "something that does not exist"; expResult = true; - result = Settings.getBoolean(key, true); + result = getSettings().getBoolean(key, true); Assert.assertEquals(expResult, result); } @@ -212,11 +196,11 @@ public class SettingsTest extends BaseTest { String key = "SomeKey"; String value = "value"; String dfault = "default"; - Settings.setString(key, value); - String ret = Settings.getString(key); + getSettings().setString(key, value); + String ret = getSettings().getString(key); Assert.assertEquals(value, ret); - Settings.removeProperty(key); - ret = Settings.getString(key, dfault); + getSettings().removeProperty(key); + ret = getSettings().getString(key, dfault); Assert.assertEquals(dfault, ret); } @@ -225,11 +209,11 @@ public class SettingsTest extends BaseTest { */ @Test public void testGetConnectionString() throws Exception { - String value = Settings.getConnectionString(Settings.KEYS.DB_CONNECTION_STRING, Settings.KEYS.DB_FILE_NAME); + String value = getSettings().getConnectionString(Settings.KEYS.DB_CONNECTION_STRING, Settings.KEYS.DB_FILE_NAME); Assert.assertNotNull(value); String msg = null; try { - value = Settings.getConnectionString("invalidKey", null); + value = getSettings().getConnectionString("invalidKey", null); } catch (InvalidSettingException e) { msg = e.getMessage(); } @@ -241,7 +225,7 @@ public class SettingsTest extends BaseTest { */ @Test public void testGetTempDirectory() throws Exception { - File tmp = Settings.getTempDirectory(); + File tmp = getSettings().getTempDirectory(); Assert.assertTrue(tmp.exists()); } @@ -253,10 +237,10 @@ public class SettingsTest extends BaseTest { public void testGetArrayFromADelimitedString() { // GIVEN a delimited string final String delimitedString = "value1,value2"; - Settings.setString("key", delimitedString); + getSettings().setString("key", delimitedString); // WHEN getting the array - final String[] array = Settings.getArray("key"); + final String[] array = getSettings().getArray("key"); // THEN the split array is returned assertThat("Expected the array to be non-null", array, notNullValue()); @@ -272,7 +256,7 @@ public class SettingsTest extends BaseTest { @Test public void testGetArrayWhereThePropertyIsNotSet() { // WHEN getting the array - final String[] array = Settings.getArray("key"); + final String[] array = getSettings().getArray("key"); // THEN null is returned assertThat("Expected the array to be null", array, nullValue()); @@ -288,10 +272,10 @@ public class SettingsTest extends BaseTest { final String[] array = {}; // WHEN setting the array - Settings.setArrayIfNotEmpty("key", array); + getSettings().setArrayIfNotEmpty("key", array); // THEN the property was not set - assertThat("Expected the property to not be set", Settings.getString("key"), nullValue()); + assertThat("Expected the property to not be set", getSettings().getString("key"), nullValue()); } /** @@ -304,10 +288,10 @@ public class SettingsTest extends BaseTest { final String[] array = null; // WHEN setting the array - Settings.setArrayIfNotEmpty("key", array); + getSettings().setArrayIfNotEmpty("key", array); // THEN the property was not set - assertThat("Expected the property to not be set", Settings.getString("key"), nullValue()); + assertThat("Expected the property to not be set", getSettings().getString("key"), nullValue()); } /** @@ -320,10 +304,10 @@ public class SettingsTest extends BaseTest { final String[] array = {"value1", "value2"}; // WHEN setting the array - Settings.setArrayIfNotEmpty("key", array); + getSettings().setArrayIfNotEmpty("key", array); // THEN the property is set - assertThat("Expected the property to be set", Settings.getString("key"), is("value1,value2")); + assertThat("Expected the property to be set", getSettings().getString("key"), is("value1,value2")); } /** @@ -336,9 +320,9 @@ public class SettingsTest extends BaseTest { final String[] array = {"value1"}; // WHEN setting the array - Settings.setArrayIfNotEmpty("key", array); + getSettings().setArrayIfNotEmpty("key", array); // THEN the property is set - assertThat("Expected the property to be set", Settings.getString("key"), is("value1")); + assertThat("Expected the property to be set", getSettings().getString("key"), is("value1")); } }