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