View Javadoc
1   /*
2    * This file is part of dependency-check-utils.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.utils;
19  
20  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  import com.fasterxml.jackson.core.JsonProcessingException;
25  import com.fasterxml.jackson.databind.ObjectMapper;
26  
27  import org.jetbrains.annotations.NotNull;
28  import org.jetbrains.annotations.Nullable;
29  
30  import java.io.File;
31  import java.io.FileInputStream;
32  import java.io.FileNotFoundException;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.PrintWriter;
36  import java.io.StringWriter;
37  import java.io.UnsupportedEncodingException;
38  import java.net.URLDecoder;
39  import java.nio.charset.StandardCharsets;
40  import java.security.ProtectionDomain;
41  import java.util.ArrayList;
42  import java.util.Arrays;
43  import java.util.Enumeration;
44  import java.util.List;
45  import java.util.Properties;
46  import java.util.UUID;
47  import java.util.function.Predicate;
48  import java.util.regex.Pattern;
49  import java.util.stream.Collectors;
50  
51  /**
52   * A simple settings container that wraps the dependencycheck.properties file.
53   *
54   * @author Jeremy Long
55   * @version $Id: $Id
56   */
57  public final class Settings {
58  
59      /**
60       * The logger.
61       */
62      private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
63      /**
64       * The properties file location.
65       */
66      private static final String PROPERTIES_FILE = "dependencycheck.properties";
67      /**
68       * Array separator.
69       */
70      private static final String ARRAY_SEP = ",";
71      /**
72       * The properties.
73       */
74      private Properties props = null;
75      /**
76       * The collection of properties that should be masked when logged.
77       */
78      private List<Predicate<String>> maskedKeys;
79      /**
80       * A reference to the temporary directory; used in case it needs to be
81       * deleted during cleanup.
82       */
83      private File tempDirectory = null;
84  
85      /**
86       * Reference to a utility class used to convert objects to json.
87       */
88      private final ObjectMapper objectMapper = new ObjectMapper();
89  
90      //<editor-fold defaultstate="collapsed" desc="KEYS used to access settings">
91      /**
92       * The collection of keys used within the properties file.
93       */
94      //suppress hard-coded password rule
95      @SuppressWarnings("squid:S2068")
96      public static final class KEYS {
97  
98          /**
99           * The key to obtain the application name.
100          */
101         public static final String APPLICATION_NAME = "odc.application.name";
102         /**
103          * The key to obtain the application version.
104          */
105         public static final String APPLICATION_VERSION = "odc.application.version";
106         /**
107          * The key to obtain the URL to retrieve the current release version
108          * from.
109          */
110         public static final String ENGINE_VERSION_CHECK_URL = "engine.version.url";
111         /**
112          * The properties key indicating whether or not the cached data sources
113          * should be updated.
114          */
115         public static final String AUTO_UPDATE = "odc.autoupdate";
116         /**
117          * The database driver class name. If this is not in the properties file
118          * the embedded database is used.
119          */
120         public static final String DB_DRIVER_NAME = "data.driver_name";
121         /**
122          * The database driver class name. If this is not in the properties file
123          * the embedded database is used.
124          */
125         public static final String DB_DRIVER_PATH = "data.driver_path";
126         /**
127          * The database connection string. If this is not in the properties file
128          * the embedded database is used.
129          */
130         public static final String DB_CONNECTION_STRING = "data.connection_string";
131         /**
132          * The username to use when connecting to the database.
133          */
134         public static final String DB_USER = "data.user";
135         /**
136          * The password to authenticate to the database.
137          */
138         public static final String DB_PASSWORD = "data.password";
139         /**
140          * The base path to use for the data directory (for embedded db and
141          * other cached resources from the Internet).
142          */
143         public static final String DATA_DIRECTORY = "data.directory";
144         /**
145          * The base path to use for the H2 data directory (for embedded db).
146          */
147         public static final String H2_DATA_DIRECTORY = "data.h2.directory";
148         /**
149          * The database file name.
150          */
151         public static final String DB_FILE_NAME = "data.file_name";
152         /**
153          * The database schema version.
154          */
155         public static final String DB_VERSION = "data.version";
156         /**
157          * The starts with filter used to exclude CVE entries from the database.
158          * By default this is set to 'cpe:2.3:a:' which limits the CVEs imported
159          * to just those that are related to applications. If this were set to
160          * just 'cpe:2.3:' the OS, hardware, and application related CVEs would
161          * be imported.
162          */
163         public static final String CVE_CPE_STARTS_WITH_FILTER = "cve.cpe.startswith.filter";
164         /**
165          * The NVD API Endpoint.
166          */
167         public static final String NVD_API_ENDPOINT = "nvd.api.endpoint";
168         /**
169          * API Key for the NVD API.
170          */
171         public static final String NVD_API_KEY = "nvd.api.key";
172         /**
173          * The delay between requests for the NVD API.
174          */
175         public static final String NVD_API_DELAY = "nvd.api.delay";
176         /**
177          * The maximum number of retry requests for a single call to the NVD
178          * API.
179          */
180         public static final String NVD_API_MAX_RETRY_COUNT = "nvd.api.max.retry.count";
181         /**
182          * The properties key to control the skipping of the check for NVD
183          * updates.
184          */
185         public static final String NVD_API_VALID_FOR_HOURS = "nvd.api.check.validforhours";
186         /**
187          * The properties key that indicates how often the NVD API data feed
188          * needs to be updated before a full refresh is evaluated.
189          */
190         public static final String NVD_API_DATAFEED_VALID_FOR_DAYS = "nvd.api.datafeed.validfordays";
191         /**
192          * The URL for the NVD API Data Feed.
193          */
194         public static final String NVD_API_DATAFEED_URL = "nvd.api.datafeed.url";
195         /**
196          * The username to use when connecting to the NVD Data feed.
197          */
198         public static final String NVD_API_DATAFEED_USER = "nvd.api.datafeed.user";
199         /**
200          * The password to authenticate to the NVD Data feed.
201          */
202         public static final String NVD_API_DATAFEED_PASSWORD = "nvd.api.datafeed.password";
203         /**
204          * The starting year for the NVD CVE Data feed cache.
205          */
206         public static final String NVD_API_DATAFEED_START_YEAR = "nvd.api.datafeed.startyear";
207         //END NEW
208         /**
209          * The key to determine if the NVD CVE analyzer is enabled.
210          */
211         public static final String ANALYZER_NVD_CVE_ENABLED = "analyzer.nvdcve.enabled";
212         /**
213          * The properties key that indicates how often the CPE data needs to be
214          * updated.
215          */
216         public static final String CPE_MODIFIED_VALID_FOR_DAYS = "cpe.validfordays";
217         /**
218          * The properties key for the URL to retrieve the CPE.
219          */
220         public static final String CPE_URL = "cpe.url";
221         /**
222          * The properties key for the URL to retrieve the Known Exploited
223          * Vulnerabilities..
224          */
225         public static final String KEV_URL = "kev.url";
226         /**
227          * The properties key to control the skipping of the check for Known
228          * Exploited Vulnerabilities updates.
229          */
230         public static final String KEV_CHECK_VALID_FOR_HOURS = "kev.check.validforhours";
231         /**
232          * Whether or not if using basic auth with a proxy the system setting
233          * 'jdk.http.auth.tunneling.disabledSchemes' should be set to an empty
234          * string.
235          */
236         public static final String PROXY_DISABLE_SCHEMAS = "proxy.disableSchemas";
237         /**
238          * The properties key for the proxy server.
239          */
240         public static final String PROXY_SERVER = "proxy.server";
241         /**
242          * The properties key for the proxy port - this must be an integer
243          * value.
244          */
245         public static final String PROXY_PORT = "proxy.port";
246         /**
247          * The properties key for the proxy username.
248          */
249         public static final String PROXY_USERNAME = "proxy.username";
250         /**
251          * The properties key for the proxy password.
252          */
253         public static final String PROXY_PASSWORD = "proxy.password";
254         /**
255          * The properties key for the non proxy hosts.
256          */
257         public static final String PROXY_NON_PROXY_HOSTS = "proxy.nonproxyhosts";
258         /**
259          * The properties key for the connection timeout.
260          */
261         public static final String CONNECTION_TIMEOUT = "connection.timeout";
262         /**
263          * The properties key for the connection read timeout.
264          */
265         public static final String CONNECTION_READ_TIMEOUT = "connection.read.timeout";
266         /**
267          * The location of the temporary directory.
268          */
269         public static final String TEMP_DIRECTORY = "temp.directory";
270         /**
271          * The maximum number of threads to allocate when downloading files.
272          */
273         public static final String MAX_DOWNLOAD_THREAD_POOL_SIZE = "max.download.threads";
274         /**
275          * The properties key for the analysis timeout.
276          */
277         public static final String ANALYSIS_TIMEOUT = "odc.analysis.timeout";
278         /**
279          * The key for the suppression file.
280          */
281         public static final String SUPPRESSION_FILE = "suppression.file";
282         /**
283          * The username used when connecting to the suppressionFiles.
284          */
285         public static final String SUPPRESSION_FILE_USER = "suppression.file.user";
286         /**
287          * The password used when connecting to the suppressionFiles.
288          */
289         public static final String SUPPRESSION_FILE_PASSWORD = "suppression.file.password";
290         /**
291          * The key for the whether the hosted suppressions file datasource is
292          * enabled.
293          */
294         public static final String HOSTED_SUPPRESSIONS_ENABLED = "hosted.suppressions.enabled";
295         /**
296          * The key for the hosted suppressions file URL.
297          */
298         public static final String HOSTED_SUPPRESSIONS_URL = "hosted.suppressions.url";
299 
300         /**
301          * The properties key for defining whether the hosted suppressions file
302          * will be updated regardless of the autoupdate settings.
303          */
304         public static final String HOSTED_SUPPRESSIONS_FORCEUPDATE = "hosted.suppressions.forceupdate";
305 
306         /**
307          * The properties key to control the skipping of the check for hosted
308          * suppressions file updates.
309          */
310         public static final String HOSTED_SUPPRESSIONS_VALID_FOR_HOURS = "hosted.suppressions.validforhours";
311 
312         /**
313          * The key for the hint file.
314          */
315         public static final String HINTS_FILE = "hints.file";
316         /**
317          * The key for the property that controls what CVSS scores are
318          * considered failing test cases for the JUNIT repor.
319          */
320         public static final String JUNIT_FAIL_ON_CVSS = "junit.fail.on.cvss";
321 
322         /**
323          * The properties key for whether the Jar Analyzer is enabled.
324          */
325         public static final String ANALYZER_JAR_ENABLED = "analyzer.jar.enabled";
326 
327         /**
328          * The properties key for whether the Known Exploited Vulnerability
329          * Analyzer is enabled.
330          */
331         public static final String ANALYZER_KNOWN_EXPLOITED_ENABLED = "analyzer.knownexploited.enabled";
332 
333         /**
334          * The properties key for whether experimental analyzers are loaded.
335          */
336         public static final String ANALYZER_EXPERIMENTAL_ENABLED = "analyzer.experimental.enabled";
337         /**
338          * The properties key for whether experimental analyzers are loaded.
339          */
340         public static final String ANALYZER_RETIRED_ENABLED = "analyzer.retired.enabled";
341         /**
342          * The properties key for whether the Archive analyzer is enabled.
343          */
344         public static final String ANALYZER_ARCHIVE_ENABLED = "analyzer.archive.enabled";
345         /**
346          * The properties key for whether the node.js package analyzer is
347          * enabled.
348          */
349         public static final String ANALYZER_NODE_PACKAGE_ENABLED = "analyzer.node.package.enabled";
350         /**
351          * The properties key for configure whether the Node Package analyzer
352          * should skip devDependencies.
353          */
354         public static final String ANALYZER_NODE_PACKAGE_SKIPDEV = "analyzer.node.package.skipdev";
355         /**
356          * The properties key for whether the Node Audit analyzer is enabled.
357          */
358         public static final String ANALYZER_NODE_AUDIT_ENABLED = "analyzer.node.audit.enabled";
359         /**
360          * The properties key for whether the Yarn Audit analyzer is enabled.
361          */
362         public static final String ANALYZER_YARN_AUDIT_ENABLED = "analyzer.yarn.audit.enabled";
363         /**
364          * The properties key for whether the Pnpm Audit analyzer is enabled.
365          */
366         public static final String ANALYZER_PNPM_AUDIT_ENABLED = "analyzer.pnpm.audit.enabled";
367         /**
368          * The properties key for supplying the URL to the Node Audit API.
369          */
370         public static final String ANALYZER_NODE_AUDIT_URL = "analyzer.node.audit.url";
371         /**
372          * The properties key for configure whether the Node Audit analyzer
373          * should skip devDependencies.
374          */
375         public static final String ANALYZER_NODE_AUDIT_SKIPDEV = "analyzer.node.audit.skipdev";
376         /**
377          * The properties key for whether node audit analyzer results will be
378          * cached.
379          */
380         public static final String ANALYZER_NODE_AUDIT_USE_CACHE = "analyzer.node.audit.use.cache";
381         /**
382          * The properties key for whether the RetireJS analyzer is enabled.
383          */
384         public static final String ANALYZER_RETIREJS_ENABLED = "analyzer.retirejs.enabled";
385         /**
386          * The properties key for whether the RetireJS analyzer file content
387          * filters.
388          */
389         public static final String ANALYZER_RETIREJS_FILTERS = "analyzer.retirejs.filters";
390         /**
391          * The properties key for whether the RetireJS analyzer should filter
392          * out non-vulnerable dependencies.
393          */
394         public static final String ANALYZER_RETIREJS_FILTER_NON_VULNERABLE = "analyzer.retirejs.filternonvulnerable";
395         /**
396          * The properties key for defining the URL to the RetireJS repository.
397          */
398         public static final String ANALYZER_RETIREJS_REPO_JS_URL = "analyzer.retirejs.repo.js.url";
399         /**
400          * The properties key for the Nexus search credentials username.
401          */
402         public static final String ANALYZER_RETIREJS_REPO_JS_USER = "analyzer.retirejs.repo.js.username";
403         /**
404          * The properties key for the Nexus search credentials password.
405          */
406         public static final String ANALYZER_RETIREJS_REPO_JS_PASSWORD = "analyzer.retirejs.repo.js.password";
407         /**
408          * The properties key for defining whether the RetireJS repository will
409          * be updated regardless of the autoupdate settings.
410          */
411         public static final String ANALYZER_RETIREJS_FORCEUPDATE = "analyzer.retirejs.forceupdate";
412         /**
413          * The properties key to control the skipping of the check for CVE
414          * updates.
415          */
416         public static final String ANALYZER_RETIREJS_REPO_VALID_FOR_HOURS = "analyzer.retirejs.repo.validforhours";
417         /**
418          * The properties key for whether the PHP composer lock file analyzer is
419          * enabled.
420          */
421         public static final String ANALYZER_COMPOSER_LOCK_ENABLED = "analyzer.composer.lock.enabled";
422         /**
423          * The properties key for whether the Perl CPAN file file analyzer is
424          * enabled.
425          */
426         public static final String ANALYZER_CPANFILE_ENABLED = "analyzer.cpanfile.enabled";
427         /**
428          * The properties key for whether the Python Distribution analyzer is
429          * enabled.
430          */
431         public static final String ANALYZER_PYTHON_DISTRIBUTION_ENABLED = "analyzer.python.distribution.enabled";
432         /**
433          * The properties key for whether the Python Package analyzer is
434          * enabled.
435          */
436         public static final String ANALYZER_PYTHON_PACKAGE_ENABLED = "analyzer.python.package.enabled";
437         /**
438          * The properties key for whether the Elixir mix audit analyzer is
439          * enabled.
440          */
441         public static final String ANALYZER_MIX_AUDIT_ENABLED = "analyzer.mix.audit.enabled";
442         /**
443          * The path to mix_audit, if available.
444          */
445         public static final String ANALYZER_MIX_AUDIT_PATH = "analyzer.mix.audit.path";
446         /**
447          * The properties key for whether the Golang Mod analyzer is enabled.
448          */
449         public static final String ANALYZER_GOLANG_MOD_ENABLED = "analyzer.golang.mod.enabled";
450         /**
451          * The path to go, if available.
452          */
453         public static final String ANALYZER_GOLANG_PATH = "analyzer.golang.path";
454         /**
455          * The path to go, if available.
456          */
457         public static final String ANALYZER_YARN_PATH = "analyzer.yarn.path";
458         /**
459          * The path to pnpm, if available.
460          */
461         public static final String ANALYZER_PNPM_PATH = "analyzer.pnpm.path";
462         /**
463          * The properties key for whether the Golang Dep analyzer is enabled.
464          */
465         public static final String ANALYZER_GOLANG_DEP_ENABLED = "analyzer.golang.dep.enabled";
466         /**
467          * The properties key for whether the Ruby Gemspec Analyzer is enabled.
468          */
469         public static final String ANALYZER_RUBY_GEMSPEC_ENABLED = "analyzer.ruby.gemspec.enabled";
470         /**
471          * The properties key for whether the Autoconf analyzer is enabled.
472          */
473         public static final String ANALYZER_AUTOCONF_ENABLED = "analyzer.autoconf.enabled";
474         /**
475          * The properties key for whether the maven_install.json analyzer is
476          * enabled.
477          */
478         public static final String ANALYZER_MAVEN_INSTALL_ENABLED = "analyzer.maveninstall.enabled";
479         /**
480          * The properties key for whether the pip analyzer is enabled.
481          */
482         public static final String ANALYZER_PIP_ENABLED = "analyzer.pip.enabled";
483         /**
484          * The properties key for whether the pipfile analyzer is enabled.
485          */
486         public static final String ANALYZER_PIPFILE_ENABLED = "analyzer.pipfile.enabled";
487         /**
488          * The properties key for whether the Poetry analyzer is enabled.
489          */
490         public static final String ANALYZER_POETRY_ENABLED = "analyzer.poetry.enabled";
491         /**
492          * The properties key for whether the CMake analyzer is enabled.
493          */
494         public static final String ANALYZER_CMAKE_ENABLED = "analyzer.cmake.enabled";
495         /**
496          * The properties key for whether the Ruby Bundler Audit analyzer is
497          * enabled.
498          */
499         public static final String ANALYZER_BUNDLE_AUDIT_ENABLED = "analyzer.bundle.audit.enabled";
500         /**
501          * The properties key for whether the .NET Assembly analyzer is enabled.
502          */
503         public static final String ANALYZER_ASSEMBLY_ENABLED = "analyzer.assembly.enabled";
504         /**
505          * The properties key for whether the .NET Nuspec analyzer is enabled.
506          */
507         public static final String ANALYZER_NUSPEC_ENABLED = "analyzer.nuspec.enabled";
508         /**
509          * The properties key for whether the .NET Nuget packages.config
510          * analyzer is enabled.
511          */
512         public static final String ANALYZER_NUGETCONF_ENABLED = "analyzer.nugetconf.enabled";
513         /**
514          * The properties key for whether the Libman analyzer is enabled.
515          */
516         public static final String ANALYZER_LIBMAN_ENABLED = "analyzer.libman.enabled";
517         /**
518          * The properties key for whether the .NET MSBuild Project analyzer is
519          * enabled.
520          */
521         public static final String ANALYZER_MSBUILD_PROJECT_ENABLED = "analyzer.msbuildproject.enabled";
522         /**
523          * The properties key for whether the Nexus analyzer is enabled.
524          */
525         public static final String ANALYZER_NEXUS_ENABLED = "analyzer.nexus.enabled";
526         /**
527          * The properties key for the Nexus search URL.
528          */
529         public static final String ANALYZER_NEXUS_URL = "analyzer.nexus.url";
530         /**
531          * The properties key for the Nexus search credentials username.
532          */
533         public static final String ANALYZER_NEXUS_USER = "analyzer.nexus.username";
534         /**
535          * The properties key for the Nexus search credentials password.
536          */
537         public static final String ANALYZER_NEXUS_PASSWORD = "analyzer.nexus.password";
538         /**
539          * The properties key for using the proxy to reach Nexus.
540          */
541         public static final String ANALYZER_NEXUS_USES_PROXY = "analyzer.nexus.proxy";
542         /**
543          * The properties key for whether the Artifactory analyzer is enabled.
544          */
545         public static final String ANALYZER_ARTIFACTORY_ENABLED = "analyzer.artifactory.enabled";
546         /**
547          * The properties key for the Artifactory search URL.
548          */
549         public static final String ANALYZER_ARTIFACTORY_URL = "analyzer.artifactory.url";
550         /**
551          * The properties key for the Artifactory username.
552          */
553         public static final String ANALYZER_ARTIFACTORY_API_USERNAME = "analyzer.artifactory.api.username";
554         /**
555          * The properties key for the Artifactory API token.
556          */
557         public static final String ANALYZER_ARTIFACTORY_API_TOKEN = "analyzer.artifactory.api.token";
558         /**
559          * The properties key for the Artifactory bearer token
560          * (https://www.jfrog.com/confluence/display/RTF/Access+Tokens). It can
561          * be generated using:
562          * <pre>curl -u yourUserName -X POST \
563          *    "https://artifactory.techno.ingenico.com/artifactory/api/security/token" \
564          *    -d "username=yourUserName"</pre>.
565          */
566         public static final String ANALYZER_ARTIFACTORY_BEARER_TOKEN = "analyzer.artifactory.bearer.token";
567         /**
568          * The properties key for using the proxy to reach Artifactory.
569          */
570         public static final String ANALYZER_ARTIFACTORY_USES_PROXY = "analyzer.artifactory.proxy";
571         /**
572          * The properties key for whether the Artifactory analyzer should use
573          * parallel processing.
574          */
575         public static final String ANALYZER_ARTIFACTORY_PARALLEL_ANALYSIS = "analyzer.artifactory.parallel.analysis";
576         /**
577          * The properties key for whether the Central analyzer is enabled.
578          */
579         public static final String ANALYZER_CENTRAL_ENABLED = "analyzer.central.enabled";
580         /**
581          * Key for the path to the local Maven repository.
582          */
583         public static final String MAVEN_LOCAL_REPO = "odc.maven.local.repo";
584         /**
585          * Key for the URL to obtain content from Maven Central.
586          */
587         public static final String CENTRAL_CONTENT_URL = "central.content.url";
588         /**
589          * The properties key for whether the Central analyzer should use
590          * parallel processing.
591          */
592         public static final String ANALYZER_CENTRAL_PARALLEL_ANALYSIS = "analyzer.central.parallel.analysis";
593         /**
594          * The properties key for whether the Central analyzer should use
595          * parallel processing.
596          */
597         public static final String ANALYZER_CENTRAL_RETRY_COUNT = "analyzer.central.retry.count";
598         /**
599          * The properties key for whether the OpenSSL analyzer is enabled.
600          */
601         public static final String ANALYZER_OPENSSL_ENABLED = "analyzer.openssl.enabled";
602         /**
603          * The properties key for whether the cocoapods analyzer is enabled.
604          */
605         public static final String ANALYZER_COCOAPODS_ENABLED = "analyzer.cocoapods.enabled";
606         /**
607          * The properties key for whether the carthage analyzer is enabled.
608          */
609         public static final String ANALYZER_CARTHAGE_ENABLED = "analyzer.carthage.enabled";
610         /**
611          * The properties key for whether the SWIFT package manager analyzer is
612          * enabled.
613          */
614         public static final String ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED = "analyzer.swift.package.manager.enabled";
615         /**
616          * The properties key for whether the SWIFT package resolved analyzer is
617          * enabled.
618          */
619         public static final String ANALYZER_SWIFT_PACKAGE_RESOLVED_ENABLED = "analyzer.swift.package.resolved.enabled";
620         /**
621          * The properties key for the Central search URL.
622          */
623         public static final String ANALYZER_CENTRAL_URL = "analyzer.central.url";
624         /**
625          * The properties key for the Central search query.
626          */
627         public static final String ANALYZER_CENTRAL_QUERY = "analyzer.central.query";
628         /**
629          * The properties key for whether Central search results will be cached.
630          */
631         public static final String ANALYZER_CENTRAL_USE_CACHE = "analyzer.central.use.cache";
632         /**
633          * The path to dotnet core, if available.
634          */
635         public static final String ANALYZER_ASSEMBLY_DOTNET_PATH = "analyzer.assembly.dotnet.path";
636         /**
637          * The path to bundle-audit, if available.
638          */
639         public static final String ANALYZER_BUNDLE_AUDIT_PATH = "analyzer.bundle.audit.path";
640         /**
641          * The path to bundle-audit, if available.
642          */
643         public static final String ANALYZER_BUNDLE_AUDIT_WORKING_DIRECTORY = "analyzer.bundle.audit.working.directory";
644         /**
645          * The additional configured zip file extensions, if available.
646          */
647         public static final String ADDITIONAL_ZIP_EXTENSIONS = "extensions.zip";
648         /**
649          * The key to obtain the path to the VFEED data file.
650          */
651         public static final String VFEED_DATA_FILE = "vfeed.data_file";
652         /**
653          * The key to obtain the VFEED connection string.
654          */
655         public static final String VFEED_CONNECTION_STRING = "vfeed.connection_string";
656         /**
657          * The key to obtain the base download URL for the VFeed data file.
658          */
659         public static final String VFEED_DOWNLOAD_URL = "vfeed.download_url";
660         /**
661          * The key to obtain the download file name for the VFeed data.
662          */
663         public static final String VFEED_DOWNLOAD_FILE = "vfeed.download_file";
664         /**
665          * The key to obtain the VFeed update status.
666          */
667         public static final String VFEED_UPDATE_STATUS = "vfeed.update_status";
668         /**
669          * The key to the HTTP request method for query last modified date.
670          */
671         public static final String DOWNLOADER_QUICK_QUERY_TIMESTAMP = "downloader.quick.query.timestamp";
672         /**
673          * The key to HTTP protocol list to use.
674          */
675         public static final String DOWNLOADER_TLS_PROTOCOL_LIST = "downloader.tls.protocols";
676         /**
677          * The key to determine if the CPE analyzer is enabled.
678          */
679         public static final String ANALYZER_CPE_ENABLED = "analyzer.cpe.enabled";
680         /**
681          * The key to determine if the NPM CPE analyzer is enabled.
682          */
683         public static final String ANALYZER_NPM_CPE_ENABLED = "analyzer.npm.cpe.enabled";
684         /**
685          * The key to determine if the CPE Suppression analyzer is enabled.
686          */
687         public static final String ANALYZER_CPE_SUPPRESSION_ENABLED = "analyzer.cpesuppression.enabled";
688         /**
689          * The key to determine if the Dependency Bundling analyzer is enabled.
690          */
691         public static final String ANALYZER_DEPENDENCY_BUNDLING_ENABLED = "analyzer.dependencybundling.enabled";
692         /**
693          * The key to determine if the Dependency Merging analyzer is enabled.
694          */
695         public static final String ANALYZER_DEPENDENCY_MERGING_ENABLED = "analyzer.dependencymerging.enabled";
696         /**
697          * The key to determine if the False Positive analyzer is enabled.
698          */
699         public static final String ANALYZER_FALSE_POSITIVE_ENABLED = "analyzer.falsepositive.enabled";
700         /**
701          * The key to determine if the File Name analyzer is enabled.
702          */
703         public static final String ANALYZER_FILE_NAME_ENABLED = "analyzer.filename.enabled";
704         /**
705          * The key to determine if the File Version analyzer is enabled.
706          */
707         public static final String ANALYZER_PE_ENABLED = "analyzer.pe.enabled";
708         /**
709          * The key to determine if the Hint analyzer is enabled.
710          */
711         public static final String ANALYZER_HINT_ENABLED = "analyzer.hint.enabled";
712         /**
713          * The key to determine if the Version Filter analyzer is enabled.
714          */
715         public static final String ANALYZER_VERSION_FILTER_ENABLED = "analyzer.versionfilter.enabled";
716         /**
717          * The key to determine if the Vulnerability Suppression analyzer is
718          * enabled.
719          */
720         public static final String ANALYZER_VULNERABILITY_SUPPRESSION_ENABLED = "analyzer.vulnerabilitysuppression.enabled";
721         /**
722          * The key to determine if the NVD CVE updater should be enabled.
723          */
724         public static final String UPDATE_NVDCVE_ENABLED = "updater.nvdcve.enabled";
725         /**
726          * The key to determine if dependency-check should check if there is a
727          * new version available.
728          */
729         public static final String UPDATE_VERSION_CHECK_ENABLED = "updater.versioncheck.enabled";
730         /**
731          * The key to determine which ecosystems should skip the CPE analysis.
732          */
733         public static final String ECOSYSTEM_SKIP_CPEANALYZER = "ecosystem.skip.cpeanalyzer";
734         /**
735          * Adds capabilities to batch insert. Tested on PostgreSQL and H2.
736          */
737         public static final String ENABLE_BATCH_UPDATES = "database.batchinsert.enabled";
738         /**
739          * Size of database batch inserts.
740          */
741         public static final String MAX_BATCH_SIZE = "database.batchinsert.maxsize";
742         /**
743          * The key that specifies the class name of the Write Lock shutdown
744          * hook.
745          */
746         public static final String WRITELOCK_SHUTDOWN_HOOK = "data.writelock.shutdownhook";
747         /**
748          * The properties key for whether the Sonatype OSS Index analyzer is
749          * enabled.
750          */
751         public static final String ANALYZER_OSSINDEX_ENABLED = "analyzer.ossindex.enabled";
752         /**
753          * The properties key for whether the Sonatype OSS Index should use a
754          * local cache.
755          */
756         public static final String ANALYZER_OSSINDEX_USE_CACHE = "analyzer.ossindex.use.cache";
757         /**
758          * The properties key for the Sonatype OSS Index URL.
759          */
760         public static final String ANALYZER_OSSINDEX_URL = "analyzer.ossindex.url";
761         /**
762          * The properties key for the Sonatype OSS Index user.
763          */
764         public static final String ANALYZER_OSSINDEX_USER = "analyzer.ossindex.user";
765         /**
766          * The properties key for the Sonatype OSS Index password.
767          */
768         public static final String ANALYZER_OSSINDEX_PASSWORD = "analyzer.ossindex.password";
769         /**
770          * The properties key for the Sonatype OSS batch-size.
771          */
772         public static final String ANALYZER_OSSINDEX_BATCH_SIZE = "analyzer.ossindex.batch.size";
773         /**
774          * The properties key for the Sonatype OSS Request Delay. Amount of time
775          * in seconds to wait before executing a request against the Sonatype
776          * OSS Rest API
777          */
778         public static final String ANALYZER_OSSINDEX_REQUEST_DELAY = "analyzer.ossindex.request.delay";
779         /**
780          * The properties key for only warning about Sonatype OSS Index remote
781          * errors instead of failing the request.
782          */
783         public static final String ANALYZER_OSSINDEX_WARN_ONLY_ON_REMOTE_ERRORS = "analyzer.ossindex.remote-error.warn-only";
784         /**
785          * The properties key setting whether or not the JSON and XML reports
786          * will be pretty printed.
787          */
788 
789         /**
790          * The properties key for whether the Dart analyzer is enabled.
791          */
792         public static final String ANALYZER_DART_ENABLED = "analyzer.dart.enabled";
793 
794         /**
795          * The properties key for whether to pretty print the XML/JSON reports.
796          */
797         public static final String PRETTY_PRINT = "odc.reports.pretty.print";
798         /**
799          * The properties key setting which other keys should be considered
800          * sensitive and subsequently masked when logged.
801          */
802         public static final String MASKED_PROPERTIES = "odc.settings.mask";
803         /**
804          * The properties key for the default max query size for Lucene query
805          * results.
806          */
807         public static final String MAX_QUERY_SIZE_DEFAULT = "odc.ecosystem.maxquerylimit.default";
808         /**
809          * The properties key prefix for the default max query size for Lucene
810          * query results; append the ecosystem to obtain the default query size.
811          */
812         public static final String MAX_QUERY_SIZE_PREFIX = "odc.ecosystem.maxquerylimit.";
813 
814         /**
815          * private constructor because this is a "utility" class containing
816          * constants
817          */
818         private KEYS() {
819             //do nothing
820         }
821     }
822     //</editor-fold>
823 
824     /**
825      * Initialize the settings object.
826      */
827     public Settings() {
828         initialize(PROPERTIES_FILE);
829     }
830 
831     /**
832      * Initialize the settings object using the given properties.
833      *
834      * @param properties the properties to be used with this Settings instance
835      * @since 4.0.3
836      */
837     public Settings(final Properties properties) {
838         props = properties;
839         logProperties("Properties loaded", props);
840     }
841 
842     /**
843      * Initialize the settings object using the given properties file.
844      *
845      * @param propertiesFilePath the path to the base properties file to load
846      */
847     public Settings(@NotNull final String propertiesFilePath) {
848         initialize(propertiesFilePath);
849     }
850 
851     /**
852      * Initializes the settings object from the given file.
853      *
854      * @param propertiesFilePath the path to the settings property file
855      */
856     private void initialize(@NotNull final String propertiesFilePath) {
857         props = new Properties();
858         try (InputStream in = FileUtils.getResourceAsStream(propertiesFilePath)) {
859             props.load(in);
860         } catch (NullPointerException ex) {
861             LOGGER.error("Did not find settings file '{}'.", propertiesFilePath);
862             LOGGER.debug("", ex);
863         } catch (IOException ex) {
864             LOGGER.error("Unable to load settings from '{}'.", propertiesFilePath);
865             LOGGER.debug("", ex);
866         }
867         logProperties("Properties loaded", props);
868     }
869 
870     /**
871      * Cleans up resources to prevent memory leaks.
872      */
873     public void cleanup() {
874         cleanup(true);
875     }
876 
877     /**
878      * Cleans up resources to prevent memory leaks.
879      *
880      * @param deleteTemporary flag indicating whether any temporary directories
881      * generated should be removed
882      */
883     public synchronized void cleanup(boolean deleteTemporary) {
884         if (deleteTemporary && tempDirectory != null && tempDirectory.exists()) {
885             LOGGER.debug("Deleting ALL temporary files from `{}`", tempDirectory.toString());
886             FileUtils.delete(tempDirectory);
887             tempDirectory = null;
888         }
889     }
890 
891     /**
892      * Check if a given key is considered to have a value with sensitive data.
893      *
894      * @param key the key to determine if the property should be masked
895      * @return <code>true</code> if the key is for a sensitive property value;
896      * otherwise <code>false</code>
897      */
898     private boolean isKeyMasked(@NotNull String key) {
899         if (maskedKeys == null || maskedKeys.isEmpty()) {
900             initMaskedKeys();
901         }
902         return maskedKeys.stream().anyMatch(maskExp -> maskExp.test(key));
903     }
904 
905     /**
906      * Obtains the printable/loggable value for a given key/value pair. This
907      * will mask some values so as to not leak sensitive information.
908      *
909      * @param key the property key
910      * @param value the property value
911      * @return the printable value
912      */
913     String getPrintableValue(@NotNull String key, String value) {
914         String printableValue = null;
915         if (value != null) {
916             printableValue = isKeyMasked(key) ? "********" : value;
917         }
918         return printableValue;
919     }
920 
921     /**
922      * Initializes the masked keys collection. This is done outside of the
923      * {@link #initialize(java.lang.String)} method because a caller may use the
924      * {@link #mergeProperties(java.io.File)} to add additional properties after
925      * the call to initialize.
926      */
927     void initMaskedKeys() {
928         final String[] masked = getArray(Settings.KEYS.MASKED_PROPERTIES);
929         if (masked == null) {
930             maskedKeys = new ArrayList<>();
931         } else {
932             maskedKeys = Arrays.stream(masked)
933                     .map(v -> Pattern.compile(v).asPredicate())
934                     .collect(Collectors.toList());
935         }
936     }
937 
938     /**
939      * Logs the properties. This will not log any properties that contain
940      * 'password' in the key.
941      *
942      * @param header the header to print with the log message
943      * @param properties the properties to log
944      */
945     private void logProperties(@NotNull final String header, @NotNull final Properties properties) {
946         if (LOGGER.isDebugEnabled()) {
947             initMaskedKeys();
948             final StringWriter sw = new StringWriter();
949             try (PrintWriter pw = new PrintWriter(sw)) {
950                 pw.format("%s:%n%n", header);
951                 final Enumeration<?> e = properties.propertyNames();
952                 while (e.hasMoreElements()) {
953                     final String key = (String) e.nextElement();
954                     final String value = getPrintableValue(key, properties.getProperty(key));
955                     if (value != null) {
956                         pw.format("%s='%s'%n", key, value);
957                     }
958                 }
959                 pw.flush();
960                 LOGGER.debug(sw.toString());
961             }
962         }
963     }
964 
965     /**
966      * Sets a property value.
967      *
968      * @param key the key for the property
969      * @param value the value for the property
970      */
971     public void setString(@NotNull final String key, @NotNull final String value) {
972         props.setProperty(key, value);
973         LOGGER.debug("Setting: {}='{}'", key, getPrintableValue(key, value));
974     }
975 
976     /**
977      * Sets a property value only if the value is not null.
978      *
979      * @param key the key for the property
980      * @param value the value for the property
981      */
982     public void setStringIfNotNull(@NotNull final String key, @Nullable final String value) {
983         if (null != value) {
984             setString(key, value);
985         }
986     }
987 
988     /**
989      * Sets a property value only if the value is not null and not empty.
990      *
991      * @param key the key for the property
992      * @param value the value for the property
993      */
994     public void setStringIfNotEmpty(@NotNull final String key, @Nullable final String value) {
995         if (null != value && !value.isEmpty()) {
996             setString(key, value);
997         }
998     }
999 
1000     /**
1001      * Sets a property value only if the array value is not null and not empty.
1002      *
1003      * @param key the key for the property
1004      * @param value the value for the property
1005      */
1006     public void setArrayIfNotEmpty(@NotNull final String key, @Nullable final String[] value) {
1007         if (null != value && value.length > 0) {
1008             try {
1009                 setString(key, objectMapper.writeValueAsString(value));
1010             } catch (JsonProcessingException e) {
1011                 throw new IllegalArgumentException();
1012             }
1013         }
1014     }
1015 
1016     /**
1017      * Sets a property value only if the array value is not null and not empty.
1018      *
1019      * @param key the key for the property
1020      * @param value the value for the property
1021      */
1022     public void setArrayIfNotEmpty(@NotNull final String key, @Nullable final List<String> value) {
1023         if (null != value && !value.isEmpty()) {
1024             try {
1025                 setString(key, objectMapper.writeValueAsString(value));
1026             } catch (JsonProcessingException e) {
1027                 throw new IllegalArgumentException();
1028             }
1029         }
1030     }
1031 
1032     /**
1033      * Sets a property value.
1034      *
1035      * @param key the key for the property
1036      * @param value the value for the property
1037      */
1038     public void setBoolean(@NotNull final String key, boolean value) {
1039         setString(key, Boolean.toString(value));
1040     }
1041 
1042     /**
1043      * Sets a property value only if the value is not null.
1044      *
1045      * @param key the key for the property
1046      * @param value the value for the property
1047      */
1048     public void setBooleanIfNotNull(@NotNull final String key, @Nullable final Boolean value) {
1049         if (null != value) {
1050             setBoolean(key, value);
1051         }
1052     }
1053 
1054     /**
1055      * Sets a float property value.
1056      *
1057      * @param key the key for the property
1058      * @param value the value for the property
1059      */
1060     public void setFloat(@NotNull final String key, final float value) {
1061         setString(key, Float.toString(value));
1062     }
1063 
1064     /**
1065      * Sets a property value.
1066      *
1067      * @param key the key for the property
1068      * @param value the value for the property
1069      */
1070     public void setInt(@NotNull final String key, final int value) {
1071         props.setProperty(key, String.valueOf(value));
1072         LOGGER.debug("Setting: {}='{}'", key, value);
1073     }
1074 
1075     /**
1076      * Sets a property value only if the value is not null.
1077      *
1078      * @param key the key for the property
1079      * @param value the value for the property
1080      */
1081     public void setIntIfNotNull(@NotNull final String key, @Nullable final Integer value) {
1082         if (null != value) {
1083             setInt(key, value);
1084         }
1085     }
1086 
1087     /**
1088      * Merges a new properties file into the current properties. This method
1089      * allows for the loading of a user provided properties file.<br><br>
1090      * <b>Note</b>: even if using this method - system properties will be loaded
1091      * before properties loaded from files.
1092      *
1093      * @param filePath the path to the properties file to merge.
1094      * @throws java.io.FileNotFoundException is thrown when the filePath points
1095      * to a non-existent file
1096      * @throws java.io.IOException is thrown when there is an exception
1097      * loading/merging the properties
1098      */
1099     @SuppressFBWarnings(justification = "try with resource will clenaup the resources", value = {"OBL_UNSATISFIED_OBLIGATION"})
1100     public void mergeProperties(@NotNull final File filePath) throws FileNotFoundException, IOException {
1101         try (FileInputStream fis = new FileInputStream(filePath)) {
1102             mergeProperties(fis);
1103         }
1104     }
1105 
1106     /**
1107      * Merges a new properties file into the current properties. This method
1108      * allows for the loading of a user provided properties file.<br><br>
1109      * Note: even if using this method - system properties will be loaded before
1110      * properties loaded from files.
1111      *
1112      * @param filePath the path to the properties file to merge.
1113      * @throws java.io.FileNotFoundException is thrown when the filePath points
1114      * to a non-existent file
1115      * @throws java.io.IOException is thrown when there is an exception
1116      * loading/merging the properties
1117      */
1118     @SuppressFBWarnings(justification = "try with resource will clenaup the resources", value = {"OBL_UNSATISFIED_OBLIGATION"})
1119     public void mergeProperties(@NotNull final String filePath) throws FileNotFoundException, IOException {
1120         try (FileInputStream fis = new FileInputStream(filePath)) {
1121             mergeProperties(fis);
1122         }
1123     }
1124 
1125     /**
1126      * Merges a new properties file into the current properties. This method
1127      * allows for the loading of a user provided properties file.<br><br>
1128      * <b>Note</b>: even if using this method - system properties will be loaded
1129      * before properties loaded from files.
1130      *
1131      * @param stream an Input Stream pointing at a properties file to merge
1132      * @throws java.io.IOException is thrown when there is an exception
1133      * loading/merging the properties
1134      */
1135     public void mergeProperties(@NotNull final InputStream stream) throws IOException {
1136         props.load(stream);
1137         logProperties("Properties updated via merge", props);
1138     }
1139 
1140     /**
1141      * Returns a value from the properties file as a File object. If the value
1142      * was specified as a system property or passed in via the -Dprop=value
1143      * argument - this method will return the value from the system properties
1144      * before the values in the contained configuration file.
1145      *
1146      * @param key the key to lookup within the properties file
1147      * @return the property from the properties file converted to a File object
1148      */
1149     @Nullable
1150     public File getFile(@NotNull final String key) {
1151         final String file = getString(key);
1152         if (file == null) {
1153             return null;
1154         }
1155         return new File(file);
1156     }
1157 
1158     /**
1159      * Returns a value from the properties file as a File object. If the value
1160      * was specified as a system property or passed in via the -Dprop=value
1161      * argument - this method will return the value from the system properties
1162      * before the values in the contained configuration file.
1163      * <p>
1164      * This method will check the configured base directory and will use this as
1165      * the base of the file path. Additionally, if the base directory begins
1166      * with a leading "[JAR]\" sequence with the path to the folder containing
1167      * the JAR file containing this class.
1168      *
1169      * @param key the key to lookup within the properties file
1170      * @return the property from the properties file converted to a File object
1171      */
1172     File getDataFile(@NotNull final String key) {
1173         final String file = getString(key);
1174         LOGGER.debug("Settings.getDataFile() - file: '{}'", file);
1175         if (file == null) {
1176             return null;
1177         }
1178         if (file.startsWith("[JAR]")) {
1179             LOGGER.debug("Settings.getDataFile() - transforming filename");
1180             final File jarPath = getJarPath();
1181             LOGGER.debug("Settings.getDataFile() - jar file: '{}'", jarPath.toString());
1182             final File retVal = new File(jarPath, file.substring(6));
1183             LOGGER.debug("Settings.getDataFile() - returning: '{}'", retVal);
1184             return retVal;
1185         }
1186         return new File(file);
1187     }
1188 
1189     /**
1190      * Attempts to retrieve the folder containing the Jar file containing the
1191      * Settings class.
1192      *
1193      * @return a File object
1194      */
1195     private File getJarPath() {
1196         String decodedPath = ".";
1197         String jarPath = "";
1198         final ProtectionDomain domain = Settings.class.getProtectionDomain();
1199         if (domain != null && domain.getCodeSource() != null && domain.getCodeSource().getLocation() != null) {
1200             jarPath = Settings.class.getProtectionDomain().getCodeSource().getLocation().getPath();
1201         }
1202         try {
1203             decodedPath = URLDecoder.decode(jarPath, StandardCharsets.UTF_8.name());
1204         } catch (UnsupportedEncodingException ex) {
1205             LOGGER.trace("", ex);
1206         }
1207 
1208         final File path = new File(decodedPath);
1209         if (path.getName().toLowerCase().endsWith(".jar")) {
1210             return path.getParentFile();
1211         } else {
1212             return new File(".");
1213         }
1214     }
1215 
1216     /**
1217      * Returns a value from the properties file. If the value was specified as a
1218      * system property or passed in via the -Dprop=value argument - this method
1219      * will return the value from the system properties before the values in the
1220      * contained configuration file.
1221      *
1222      * @param key the key to lookup within the properties file
1223      * @param defaultValue the default value for the requested property
1224      * @return the property from the properties file
1225      */
1226     public String getString(@NotNull final String key, @Nullable final String defaultValue) {
1227         return System.getProperty(key, props.getProperty(key, defaultValue));
1228     }
1229 
1230     /**
1231      * Returns the temporary directory.
1232      *
1233      * @return the temporary directory
1234      * @throws java.io.IOException if any.
1235      */
1236     public synchronized File getTempDirectory() throws IOException {
1237         if (tempDirectory == null) {
1238             final File baseTemp = new File(getString(Settings.KEYS.TEMP_DIRECTORY, System.getProperty("java.io.tmpdir")));
1239             tempDirectory = FileUtils.createTempDirectory(baseTemp);
1240         }
1241         return tempDirectory;
1242     }
1243 
1244     /**
1245      * Returns a value from the properties file. If the value was specified as a
1246      * system property or passed in via the -Dprop=value argument - this method
1247      * will return the value from the system properties before the values in the
1248      * contained configuration file.
1249      *
1250      * @param key the key to lookup within the properties file
1251      * @return the property from the properties file
1252      */
1253     public String getString(@NotNull final String key) {
1254         return System.getProperty(key, props.getProperty(key));
1255     }
1256 
1257     /**
1258      * Returns a list with the given key.
1259      * <p>
1260      * If the property is not set then {@code null} will be returned.
1261      *
1262      * @param key the key to get from this
1263      * {@link org.owasp.dependencycheck.utils.Settings}.
1264      * @return the list or {@code null} if the key wasn't present.
1265      */
1266     public String[] getArray(@NotNull final String key) {
1267         final String string = getString(key);
1268         if (string != null) {
1269             if (string.charAt(0) == '{' || string.charAt(0) == '[') {
1270                 try {
1271                     return objectMapper.readValue(string, String[].class);
1272                 } catch (JsonProcessingException e) {
1273                     throw new IllegalStateException("Unable to read value '" + string + "' as an array");
1274                 }
1275             } else {
1276                 return string.split(ARRAY_SEP);
1277             }
1278         }
1279         return null;
1280     }
1281 
1282     /**
1283      * Removes a property from the local properties collection. This is mainly
1284      * used in test cases.
1285      *
1286      * @param key the property key to remove
1287      */
1288     public void removeProperty(@NotNull final String key) {
1289         props.remove(key);
1290     }
1291 
1292     /**
1293      * Returns an int value from the properties file. If the value was specified
1294      * as a system property or passed in via the -Dprop=value argument - this
1295      * method will return the value from the system properties before the values
1296      * in the contained configuration file.
1297      *
1298      * @param key the key to lookup within the properties file
1299      * @return the property from the properties file
1300      * @throws org.owasp.dependencycheck.utils.InvalidSettingException is thrown
1301      * if there is an error retrieving the setting
1302      */
1303     public int getInt(@NotNull final String key) throws InvalidSettingException {
1304         try {
1305             return Integer.parseInt(getString(key));
1306         } catch (NumberFormatException ex) {
1307             throw new InvalidSettingException("Could not convert property '" + key + "' to an int.", ex);
1308         }
1309     }
1310 
1311     /**
1312      * Returns an int value from the properties file. If the value was specified
1313      * as a system property or passed in via the -Dprop=value argument - this
1314      * method will return the value from the system properties before the values
1315      * in the contained configuration file.
1316      *
1317      * @param key the key to lookup within the properties file
1318      * @param defaultValue the default value to return
1319      * @return the property from the properties file or the defaultValue if the
1320      * property does not exist or cannot be converted to an integer
1321      */
1322     public int getInt(@NotNull final String key, int defaultValue) {
1323         int value;
1324         try {
1325             value = Integer.parseInt(getString(key));
1326         } catch (NumberFormatException ex) {
1327             if (!getString(key, "").isEmpty()) {
1328                 LOGGER.debug("Could not convert property '{}={}' to an int; using {} instead.",
1329                         key, getPrintableValue(key, getString(key)), defaultValue);
1330             }
1331             value = defaultValue;
1332         }
1333         return value;
1334     }
1335 
1336     /**
1337      * Returns a long value from the properties file. If the value was specified
1338      * as a system property or passed in via the -Dprop=value argument - this
1339      * method will return the value from the system properties before the values
1340      * in the contained configuration file.
1341      *
1342      * @param key the key to lookup within the properties file
1343      * @return the property from the properties file
1344      * @throws org.owasp.dependencycheck.utils.InvalidSettingException is thrown
1345      * if there is an error retrieving the setting
1346      */
1347     public long getLong(@NotNull final String key) throws InvalidSettingException {
1348         try {
1349             return Long.parseLong(getString(key));
1350         } catch (NumberFormatException ex) {
1351             throw new InvalidSettingException("Could not convert property '" + key + "' to a long.", ex);
1352         }
1353     }
1354 
1355     /**
1356      * Returns a boolean value from the properties file. If the value was
1357      * specified as a system property or passed in via the
1358      * <code>-Dprop=value</code> argument this method will return the value from
1359      * the system properties before the values in the contained configuration
1360      * file.
1361      *
1362      * @param key the key to lookup within the properties file
1363      * @return the property from the properties file
1364      * @throws org.owasp.dependencycheck.utils.InvalidSettingException is thrown
1365      * if there is an error retrieving the setting
1366      */
1367     public boolean getBoolean(@NotNull final String key) throws InvalidSettingException {
1368         return Boolean.parseBoolean(getString(key));
1369     }
1370 
1371     /**
1372      * Returns a boolean value from the properties file. If the value was
1373      * specified as a system property or passed in via the
1374      * <code>-Dprop=value</code> argument this method will return the value from
1375      * the system properties before the values in the contained configuration
1376      * file.
1377      *
1378      * @param key the key to lookup within the properties file
1379      * @param defaultValue the default value to return if the setting does not
1380      * exist
1381      * @return the property from the properties file
1382      */
1383     public boolean getBoolean(@NotNull final String key, boolean defaultValue) {
1384         return Boolean.parseBoolean(getString(key, Boolean.toString(defaultValue)));
1385     }
1386 
1387     /**
1388      * Returns a float value from the properties file. If the value was
1389      * specified as a system property or passed in via the
1390      * <code>-Dprop=value</code> argument this method will return the value from
1391      * the system properties before the values in the contained configuration
1392      * file.
1393      *
1394      * @param key the key to lookup within the properties file
1395      * @param defaultValue the default value to return if the setting does not
1396      * exist
1397      * @return the property from the properties file
1398      */
1399     public float getFloat(@NotNull final String key, float defaultValue) {
1400         float retValue = defaultValue;
1401         try {
1402             retValue = Float.parseFloat(getString(key));
1403         } catch (Throwable ex) {
1404             LOGGER.trace("ignore", ex);
1405         }
1406         return retValue;
1407     }
1408 
1409     /**
1410      * Returns a connection string from the configured properties. If the
1411      * connection string contains a %s, this method will determine the 'data'
1412      * directory and replace the %s with the path to the data directory. If the
1413      * data directory does not exist it will be created.
1414      *
1415      * @param connectionStringKey the property file key for the connection
1416      * string
1417      * @param dbFileNameKey the settings key for the db filename
1418      * @return the connection string
1419      * @throws IOException thrown the data directory cannot be created
1420      * @throws InvalidSettingException thrown if there is an invalid setting
1421      */
1422     public String getConnectionString(String connectionStringKey, String dbFileNameKey)
1423             throws IOException, InvalidSettingException {
1424         final String connStr = getString(connectionStringKey);
1425         if (connStr == null) {
1426             final String msg = String.format("Invalid properties file; %s is missing.", connectionStringKey);
1427             throw new InvalidSettingException(msg);
1428         }
1429         if (connStr.contains("%s")) {
1430             final File directory = getH2DataDirectory();
1431             LOGGER.debug("Data directory: {}", directory);
1432             String fileName = null;
1433             if (dbFileNameKey != null) {
1434                 fileName = getString(dbFileNameKey);
1435             }
1436             if (fileName == null) {
1437                 final String msg = String.format("Invalid properties file to get a file based connection string; '%s' must be defined.",
1438                         dbFileNameKey);
1439                 throw new InvalidSettingException(msg);
1440             }
1441             if (connStr.startsWith("jdbc:h2:file:") && fileName.endsWith(".mv.db")) {
1442                 fileName = fileName.substring(0, fileName.length() - 6);
1443             }
1444             // yes, for H2 this path won't actually exists - but this is sufficient to get the value needed
1445             final File dbFile = new File(directory, fileName);
1446             final String cString = String.format(connStr, dbFile.getCanonicalPath());
1447             LOGGER.debug("Connection String: '{}'", cString);
1448             return cString;
1449         }
1450         return connStr;
1451     }
1452 
1453     /**
1454      * Retrieves the primary data directory that is used for caching web
1455      * content.
1456      *
1457      * @return the data directory to store data files
1458      * @throws java.io.IOException is thrown if an java.io.IOException occurs of
1459      * course...
1460      */
1461     public File getDataDirectory() throws IOException {
1462         final File path = getDataFile(Settings.KEYS.DATA_DIRECTORY);
1463         if (path != null && (path.exists() || path.mkdirs())) {
1464             return path;
1465         }
1466         throw new IOException(String.format("Unable to create the data directory '%s'",
1467                 (path == null) ? "unknown" : path.getAbsolutePath()));
1468     }
1469 
1470     /**
1471      * Retrieves the H2 data directory - if the database has been moved to the
1472      * temp directory this method will return the temp directory.
1473      *
1474      * @return the data directory to store data files
1475      * @throws java.io.IOException is thrown if an java.io.IOException occurs of
1476      * course...
1477      */
1478     public File getH2DataDirectory() throws IOException {
1479         final String h2Test = getString(Settings.KEYS.H2_DATA_DIRECTORY);
1480         final File path;
1481         if (h2Test != null && !h2Test.isEmpty()) {
1482             path = getDataFile(Settings.KEYS.H2_DATA_DIRECTORY);
1483         } else {
1484             path = getDataFile(Settings.KEYS.DATA_DIRECTORY);
1485         }
1486         if (path != null && (path.exists() || path.mkdirs())) {
1487             return path;
1488         }
1489         throw new IOException(String.format("Unable to create the h2 data directory '%s'",
1490                 (path == null) ? "unknown" : path.getAbsolutePath()));
1491     }
1492 
1493     /**
1494      * Generates a new temporary file name that is guaranteed to be unique.
1495      *
1496      * @param prefix the prefix for the file name to generate
1497      * @param extension the extension of the generated file name
1498      * @return a temporary File
1499      * @throws java.io.IOException if any.
1500      */
1501     public File getTempFile(@NotNull final String prefix, @NotNull final String extension) throws IOException {
1502         final File dir = getTempDirectory();
1503         final String tempFileName = String.format("%s%s.%s", prefix, UUID.randomUUID(), extension);
1504         final File tempFile = new File(dir, tempFileName);
1505         if (tempFile.exists()) {
1506             return getTempFile(prefix, extension);
1507         }
1508         return tempFile;
1509     }
1510 }