diff --git a/.github/workflows/pull_requests.yml b/.github/workflows/pull_requests.yml index 377d2428a8a..0aebd854caf 100644 --- a/.github/workflows/pull_requests.yml +++ b/.github/workflows/pull_requests.yml @@ -10,6 +10,7 @@ jobs: test: name: Build and Test permissions: + security-events: write contents: read runs-on: ubuntu-latest steps: @@ -43,10 +44,31 @@ jobs: with: # Command to be sent to SARIF Multitool command: 'validate core/target/test-reports/Report.sarif' + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: utils/target/spotbugsSarif.json + category: spotbugs-utils + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: cli/target/spotbugsSarif.json + category: spotbugs-cli + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: ant/target/spotbugsSarif.json + category: spotbugs-ant + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: core/target/spotbugsSarif.json + category: spotbugs-core maven: name: Regression Test Maven Plugin permissions: + security-events: write contents: read runs-on: ubuntu-latest steps: @@ -76,7 +98,7 @@ jobs: env: NVD_API_KEY: ${{ secrets.NVD_API_KEY }} run: | - mvn -V -s settings.xml -pl utils,core,maven -am compile verify -DtestMavenPlugin -DreleaseTesting --no-transfer-progress --batch-mode + mvn -V -s settings.xml -pl maven -am compile verify -DtestMavenPlugin -DreleaseTesting --no-transfer-progress --batch-mode - name: Archive IT test logs id: archive-logs if: always() @@ -85,32 +107,40 @@ jobs: name: it-test-logs retention-days: 7 path: maven/target/it/**/build.log -# this action has been failing - so I'm disabling it; we never really found anything anyways -# audit: -# runs-on: ubuntu-latest -# permissions: -# contents: read -# pull-requests: write -# name: Audit -# steps: -# - uses: actions/checkout@v4 -# - name: Check Maven Cache -# id: maven-cache -# uses: actions/cache@v4 -# with: -# path: ~/.m2/repository/ -# key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} -# restore-keys: | -# ${{ runner.os }}-maven- -# - name: Semgrep -# id: semgrep -# run: | -# docker run --rm -v "${PWD}:/src" returntocorp/semgrep semgrep --config "p/ci" --sarif > semgrep.sarif -# - name: Maven Site -# if: always() -# run: | -# mvn -s settings.xml package site -DskipTests=true --no-transfer-progress --batch-mode -# - name: Publish Comments -# if: always() -# run: | -# mvn se.bjurr.violations:violation-comments-to-github-maven-plugin:violation-comments --no-transfer-progress --batch-mode -DpullRequestId=${{ github.event.pull_request.number }} -DoAuth2Token=${{ secrets.GITHUB_TOKEN }} + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: maven/target/spotbugsSarif.json + category: spotbugs-maven + + checkstyle: + name: Checkstyle Validation + permissions: + security-events: write + contents: read + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check Maven Cache + id: maven-cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository/ + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: Set up JDK 11 + id: jdk-11 + uses: actions/setup-java@v4 + with: + java-version: 11 + distribution: 'zulu' + - name: Checkstyle + id: checkstyle + run: | + mvn -V -s settings.xml checkstyle:checkstyle-aggregate --no-transfer-progress --batch-mode + - name: Upload SARIF file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: target/checkstyle-result.sarif + category: checkstyle \ No newline at end of file diff --git a/cli/src/main/java/org/owasp/dependencycheck/CliParser.java b/cli/src/main/java/org/owasp/dependencycheck/CliParser.java index 9d9f77cb6ec..f5826b12858 100644 --- a/cli/src/main/java/org/owasp/dependencycheck/CliParser.java +++ b/cli/src/main/java/org/owasp/dependencycheck/CliParser.java @@ -374,7 +374,7 @@ private void addAdvancedOptions(final Options options) { "Credentials for basic authentication to the NVD API Datafeed.")) .addOption(newOptionWithArg(ARGUMENT.NVD_API_DATAFEED_PASSWORD, "password", "Credentials for basic authentication to the NVD API Datafeed.")) - .addOption(newOptionWithArg(ARGUMENT.NVD_API_MAX_RETRY_COUNT,"count", + .addOption(newOptionWithArg(ARGUMENT.NVD_API_MAX_RETRY_COUNT, "count", "The maximum number of retry requests for a single call to the NVD API.")) .addOption(newOptionWithArg(ARGUMENT.NVD_API_VALID_FOR_HOURS, "hours", "The number of hours to wait before checking for new updates from the NVD.")) @@ -1144,7 +1144,7 @@ public static class ARGUMENT { */ public static final String DATA_DIRECTORY = "data"; /** - * The CLI argument name for setting the URL for the NVD API Endpoint + * The CLI argument name for setting the URL for the NVD API Endpoint. */ public static final String NVD_API_ENDPOINT = "nvdApiEndpoint"; /** @@ -1152,8 +1152,9 @@ public static class ARGUMENT { */ public static final String NVD_API_KEY = "nvdApiKey"; /** - * The CLI argument name for setting the maximum number of retry requests for a single call to the NVD API. - */ + * The CLI argument name for setting the maximum number of retry + * requests for a single call to the NVD API. + */ public static final String NVD_API_MAX_RETRY_COUNT = "nvdMaxRetryCount"; /** * The CLI argument name for setting the number of hours to wait before diff --git a/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java b/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java index 33c78c5243e..9b9acd34716 100644 --- a/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java +++ b/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java @@ -346,12 +346,14 @@ private List loadSuppressionFile(final SuppressionParser parser file = getSettings().getTempFile("suppression", "xml"); final URL url = new URL(suppressionFilePath); try { - Downloader.getInstance().fetchFile(url, file, false, Settings.KEYS.SUPPRESSION_FILE_USER, Settings.KEYS.SUPPRESSION_FILE_PASSWORD); + Downloader.getInstance().fetchFile(url, file, false, Settings.KEYS.SUPPRESSION_FILE_USER, + Settings.KEYS.SUPPRESSION_FILE_PASSWORD); } catch (DownloadFailedException ex) { LOGGER.trace("Failed download suppression file - first attempt", ex); try { Thread.sleep(500); - Downloader.getInstance().fetchFile(url, file, true, Settings.KEYS.SUPPRESSION_FILE_USER, Settings.KEYS.SUPPRESSION_FILE_PASSWORD); + Downloader.getInstance().fetchFile(url, file, true, Settings.KEYS.SUPPRESSION_FILE_USER, + Settings.KEYS.SUPPRESSION_FILE_PASSWORD); } catch (TooManyRequestsException ex1) { throw new SuppressionParseException("Unable to download supression file `" + file + "`; received 429 - too many requests", ex1); diff --git a/core/src/main/java/org/owasp/dependencycheck/analyzer/CarthageAnalyzer.java b/core/src/main/java/org/owasp/dependencycheck/analyzer/CarthageAnalyzer.java index 8e6e4730989..b21e6b944f9 100644 --- a/core/src/main/java/org/owasp/dependencycheck/analyzer/CarthageAnalyzer.java +++ b/core/src/main/java/org/owasp/dependencycheck/analyzer/CarthageAnalyzer.java @@ -86,15 +86,16 @@ public class CarthageAnalyzer extends AbstractFileTypeAnalyzer { private static final FileFilter CARTHAGE_FILTER = FileFilterBuilder.newInstance().addFilenames(CARTFILE_RESOLVED).build(); /** - * The capture group #1 is the dependency type, #2 is the name, #3 is dependency version. - * The version can be a commit ref, so we can't assume it's a number + * The capture group #1 is the dependency type, #2 is the name, #3 is + * dependency version. The version can be a commit ref, so we can't assume + * it's a number * - * Example values: - * - binary "https://dl.google.com/geosdk/GoogleMaps.json" "7.2.0" - * - git "https://gitlab.matrix.org/matrix-org/olm.git" "3.2.16" - * - github "alinradut/SwiftEntryKit" "95f4a08f41ddcf2c02e2b22789038774c8c94df5"" - * - github "CocoaLumberjack/CocoaLumberjack" "3.8.5" - * - github "realm/realm-swift" "v10.44.0" + * Example values: - binary "https://dl.google.com/geosdk/GoogleMaps.json" + * "7.2.0" - git "https://gitlab.matrix.org/matrix-org/olm.git" "3.2.16" - + * github "alinradut/SwiftEntryKit" + * "95f4a08f41ddcf2c02e2b22789038774c8c94df5"" - github + * "CocoaLumberjack/CocoaLumberjack" "3.8.5" - github "realm/realm-swift" + * "v10.44.0" */ private static final Pattern CARTFILE_RESOLVED_DEPENDENCY_PATTERN = Pattern.compile("(github|git|binary) \"([^\"]+)\" \"([^\"]+)\""); @@ -106,9 +107,8 @@ public class CarthageAnalyzer extends AbstractFileTypeAnalyzer { /** * Capture group #1 is the dependency name. * - * Example values: - * - robbiehanson/XMPPFramework - * - CocoaLumberjack/CocoaLumberjack + * Example values: - robbiehanson/XMPPFramework - + * CocoaLumberjack/CocoaLumberjack */ private static final Pattern CARTFILE_RESOLVED_GITHUB_DEPENDENCY = Pattern.compile("[a-zA-Z0-9-_]+/([a-zA-Z0-9\\-_\\.]+)"); @@ -120,11 +120,9 @@ public class CarthageAnalyzer extends AbstractFileTypeAnalyzer { /** * Capture group #1 is the dependency name. * - * Example values: - * - https://my.domain.com/release/MyFramework.json - * - file:///some/Path/MyFramework.json - * - relative/path/MyFramework.json - * - /absolute/path/MyFramework.json + * Example values: - https://my.domain.com/release/MyFramework.json - + * file:///some/Path/MyFramework.json - relative/path/MyFramework.json - + * /absolute/path/MyFramework.json */ private static final Pattern CARTFILE_RESOLVED_BINARY_DEPENDENCY = Pattern.compile("([a-zA-Z0-9\\-_\\.]+).json"); @@ -186,6 +184,7 @@ protected void analyzeDependency(Dependency dependency, Engine engine) * Analyzes the Cartfile.resolved and adds the evidence to the dependency. * * @param cartfileResolved the dependency + * @param engine a reference to the dependency-check engine * @throws AnalysisException thrown if there is an error analyzing the * Cartfile */ @@ -210,8 +209,7 @@ private void analyzeCartfileResolvedDependency(Dependency cartfileResolved, Engi final Matcher versionMatcher = CARTFILE_VERSION_PATTERN.matcher(version); if (versionMatcher.find()) { version = versionMatcher.group(1); - } - else { + } else { // this is probably a git commit reference, so we'll default to 0.0.0. // this will probably bubble up a ton of CVEs, but serves you right for // not using semantic versioning. @@ -224,15 +222,13 @@ private void analyzeCartfileResolvedDependency(Dependency cartfileResolved, Engi continue; } name = nameMatcher.group(1); - } - else if (type.contentEquals("github")) { + } else if (type.contentEquals("github")) { final Matcher nameMatcher = CARTFILE_RESOLVED_GITHUB_DEPENDENCY.matcher(name); if (!nameMatcher.find()) { continue; } name = nameMatcher.group(1); - } - else if (type.contentEquals("binary")) { + } else if (type.contentEquals("binary")) { final Matcher nameMatcher = CARTFILE_RESOLVED_BINARY_DEPENDENCY.matcher(name); if (!nameMatcher.find()) { continue; diff --git a/core/src/main/java/org/owasp/dependencycheck/analyzer/PinnedMavenInstallAnalyzer.java b/core/src/main/java/org/owasp/dependencycheck/analyzer/PinnedMavenInstallAnalyzer.java index c4d2f7349ae..b62e006681e 100644 --- a/core/src/main/java/org/owasp/dependencycheck/analyzer/PinnedMavenInstallAnalyzer.java +++ b/core/src/main/java/org/owasp/dependencycheck/analyzer/PinnedMavenInstallAnalyzer.java @@ -123,11 +123,11 @@ protected void analyzeDependency(Dependency dependency, Engine engine) throws An final DependencyTree tree; List deps; try { - JsonNode jsonNode = MAPPER.readTree(dependencyFile); - JsonNode v2Version = jsonNode.path("version"); - JsonNode v010Version = jsonNode.path("dependency_tree").path("version"); + final JsonNode jsonNode = MAPPER.readTree(dependencyFile); + final JsonNode v2Version = jsonNode.path("version"); + final JsonNode v010Version = jsonNode.path("dependency_tree").path("version"); - if (v2Version.isTextual()) { + if (v2Version.isTextual()) { final InstallFileV2 installFile = INSTALL_FILE_V2_READER.readValue(dependencyFile); if (!Objects.equals(installFile.getAutogeneratedSentinel(), "THERE_IS_NO_DATA_ONLY_ZUUL")) { return; @@ -155,7 +155,6 @@ protected void analyzeDependency(Dependency dependency, Engine engine) throws An return; } - } catch (IOException e) { System.out.println("e"); return; @@ -325,11 +324,12 @@ public String getVersion() { * {@code .dependency_tree.dependencies}. */ private static class MavenDependency { - public MavenDependency(String coord) { + + MavenDependency(String coord) { this.coord = coord; } - public MavenDependency() { + MavenDependency() { } /** * The standard Maven coordinate string @@ -352,7 +352,13 @@ public String getCoord() { * A reusable reader for {@link InstallFile}. */ private static final ObjectReader INSTALL_FILE_READER; + /** + * A reusable reader for {@link InstallFileV2}. + */ private static final ObjectReader INSTALL_FILE_V2_READER; + /** + * A reusable object mapper. + */ private static final ObjectMapper MAPPER; static { @@ -367,11 +373,12 @@ public String getCoord() { * file. * *

- * At the time of writing, the latest version is 2, and the dependencies - * are stored in {@code .artifacts}. + * At the time of writing, the latest version is 2, and the dependencies are + * stored in {@code .artifacts}. * *

- * The top-level keys we care about are {@code .artifacts}. {@code .version}. + * The top-level keys we care about are {@code .artifacts}. + * {@code .version}. */ private static class InstallFileV2 { @@ -382,8 +389,9 @@ private static class InstallFileV2 { private String version; /** - * A list of Maven dependencies made available. Note that this map is transitively closed and - * pinned to a specific version of each artifact. + * A list of Maven dependencies made available. Note that this map is + * transitively closed and pinned to a specific version of each + * artifact. *

* The key is the Maven coordinate string, less the version * {@code group:artifact[:optional classifier][:optional packaging]}. @@ -394,8 +402,8 @@ private static class InstallFileV2 { private Map artifacts; /** - * A sentinel value placed in the file to indicate that it is an auto-generated pinned maven - * install file. + * A sentinel value placed in the file to indicate that it is an + * auto-generated pinned maven install file. */ @JsonProperty("__AUTOGENERATED_FILE_DO_NOT_MODIFY_THIS_FILE_MANUALLY") private String autogeneratedSentinel; @@ -427,23 +435,23 @@ public String getAutogeneratedSentinel() { return autogeneratedSentinel; } } + private static class Artifactv2 { - /** - * The version of the artifact. - */ - @JsonProperty("version") - private String version; - - /** - * Returns the value of version. - * - * @return the value of version - */ - public String getVersion() { - return version; - } - } + /** + * The version of the artifact. + */ + @JsonProperty("version") + private String version; + /** + * Returns the value of version. + * + * @return the value of version + */ + public String getVersion() { + return version; + } + } } diff --git a/core/src/main/java/org/owasp/dependencycheck/analyzer/YarnAuditAnalyzer.java b/core/src/main/java/org/owasp/dependencycheck/analyzer/YarnAuditAnalyzer.java index 69089290d85..1632c876c16 100644 --- a/core/src/main/java/org/owasp/dependencycheck/analyzer/YarnAuditAnalyzer.java +++ b/core/src/main/java/org/owasp/dependencycheck/analyzer/YarnAuditAnalyzer.java @@ -280,7 +280,7 @@ private List analyzePackage(final File lockFile, final File packageFil final JsonObject lockJson = fetchYarnAuditJson(dependency, skipDevDependencies); // Retrieves the contents of package-lock.json from the Dependency final JsonObject packageJson; - try (final JsonReader packageReader = Json.createReader(Files.newInputStream(packageFile.toPath()))) { + try (JsonReader packageReader = Json.createReader(Files.newInputStream(packageFile.toPath()))) { packageJson = packageReader.readObject(); } // Modify the payload to meet the NPM Audit API requirements diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NodeAuditSearch.java b/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NodeAuditSearch.java index e3032ab1a67..c5ddc360067 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NodeAuditSearch.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NodeAuditSearch.java @@ -51,7 +51,6 @@ import org.owasp.dependencycheck.data.cache.DataCache; import org.owasp.dependencycheck.data.cache.DataCacheFactory; import org.owasp.dependencycheck.utils.Checksum; -import org.owasp.dependencycheck.utils.URLConnectionFailureException; /** * Class of methods to search via Node Audit API. @@ -163,7 +162,8 @@ private List submitPackage(JsonObject packageJson, String key, int cou additionalHeaders.add(new BasicHeader("npm-session", generateRandomSession())); try { - final String response = Downloader.getInstance().postBasedFetchContent(nodeAuditUrl.toURI(), packageJson.toString(), ContentType.APPLICATION_JSON, additionalHeaders); + final String response = Downloader.getInstance().postBasedFetchContent(nodeAuditUrl.toURI(), + packageJson.toString(), ContentType.APPLICATION_JSON, additionalHeaders); final JSONObject jsonResponse = new JSONObject(response); final NpmAuditParser parser = new NpmAuditParser(); final List advisories = parser.parse(jsonResponse); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmPayloadBuilder.java b/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmPayloadBuilder.java index ce9c64bd354..d12265f2d2b 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmPayloadBuilder.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmPayloadBuilder.java @@ -40,6 +40,7 @@ */ @ThreadSafe public final class NpmPayloadBuilder { + /** * Private constructor for utility class. */ @@ -119,12 +120,12 @@ public static JsonObject build(JsonObject lockJson, JsonObject packageJson, //After Version 3, dependencies can't be taken directly from package-lock.json if (lockJsonVersion > 2 && dep.containsKey("dependencies") && dep.get("dependencies") instanceof JsonObject) { - JsonObjectBuilder depBuilder = Json.createObjectBuilder(dep); + final JsonObjectBuilder depBuilder = Json.createObjectBuilder(dep); depBuilder.remove("dependencies"); depBuilder.add("requires", dep.get("dependencies")); dep = depBuilder.build(); } - + final String version = dep.getString("version", ""); final boolean isDev = dep.getBoolean("dev", false); if (skipDevDependencies && isDev) { @@ -154,7 +155,7 @@ public static JsonObject build(JsonObject lockJson, JsonObject packageJson, * @return the JSON payload for NPN Audit */ public static JsonObject build(JsonObject packageJson, MultiValuedMap dependencyMap, - final boolean skipDevDependencies) { + final boolean skipDevDependencies) { final JsonObjectBuilder payloadBuilder = Json.createObjectBuilder(); addProjectInfo(packageJson, payloadBuilder); @@ -246,8 +247,8 @@ private static void addConstantElements(final JsonObjectBuilder payloadBuilder) private static JsonObject buildDependencies(JsonObject dep, MultiValuedMap dependencyMap) { final JsonObjectBuilder depBuilder = Json.createObjectBuilder(); Optional.ofNullable(dep.getJsonString("version")) - .map(JsonString::getString) - .ifPresent(version -> depBuilder.add("version", version)); + .map(JsonString::getString) + .ifPresent(version -> depBuilder.add("version", version)); //not installed package (like, dependency of an optional dependency) doesn't contains integrity if (dep.containsKey("integrity")) { diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java index 6b0ac1e46f7..5b32590e0f7 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java @@ -799,21 +799,21 @@ public Vulnerability getVulnerability(String cve, Connection conn) throws Databa final CvssV3 cvss = new CvssV3(null, null, cvssData, rsV.getDouble(19), rsV.getDouble(20)); vuln.setCvssV3(cvss); } -// 32.v4version, 33.v4attackVector, 34.v4attackComplexity, 35.v4attackRequirements, 36.v4privilegesRequired, -// 37.v4userInteraction, 38.v4vulnConfidentialityImpact, 39.v4vulnIntegrityImpact, 40.v4vulnAvailabilityImpact, -// 41.v4subConfidentialityImpact, 42.v4subIntegrityImpact, 43.v4subAvailabilityImpact, 44.v4exploitMaturity, -// 45.v4confidentialityRequirement, 46.v4integrityRequirement, 47.v4availabilityRequirement, 48.v4modifiedAttackVector, -// 49.v4modifiedAttackComplexity, 50.v4modifiedAttackRequirements, 51.v4modifiedPrivilegesRequired, 52.v4modifiedUserInteraction, -// 53.v4modifiedVulnConfidentialityImpact, 54.v4modifiedVulnIntegrityImpact, 55.v4modifiedVulnAvailabilityImpact, -// 56.v4modifiedSubConfidentialityImpact, 57.v4modifiedSubIntegrityImpact, 58.v4modifiedSubAvailabilityImpact, -// 59.v4safety, 60.v4automatable, 61.v4recovery, 62.v4valueDensity, 63.v4vulnerabilityResponseEffort, 64.v4providerUrgency, +// 32.v4version, 33.v4attackVector, 34.v4attackComplexity, 35.v4attackRequirements, 36.v4privilegesRequired, +// 37.v4userInteraction, 38.v4vulnConfidentialityImpact, 39.v4vulnIntegrityImpact, 40.v4vulnAvailabilityImpact, +// 41.v4subConfidentialityImpact, 42.v4subIntegrityImpact, 43.v4subAvailabilityImpact, 44.v4exploitMaturity, +// 45.v4confidentialityRequirement, 46.v4integrityRequirement, 47.v4availabilityRequirement, 48.v4modifiedAttackVector, +// 49.v4modifiedAttackComplexity, 50.v4modifiedAttackRequirements, 51.v4modifiedPrivilegesRequired, 52.v4modifiedUserInteraction, +// 53.v4modifiedVulnConfidentialityImpact, 54.v4modifiedVulnIntegrityImpact, 55.v4modifiedVulnAvailabilityImpact, +// 56.v4modifiedSubConfidentialityImpact, 57.v4modifiedSubIntegrityImpact, 58.v4modifiedSubAvailabilityImpact, +// 59.v4safety, 60.v4automatable, 61.v4recovery, 62.v4valueDensity, 63.v4vulnerabilityResponseEffort, 64.v4providerUrgency, // 65.v4baseScore, 66.v4baseSeverity, 67.v4threatScore, 68.v4threatSeverity, 69.v4environmentalScore, 70.v4environmentalSeverity // 71.v4source, 72.v4type if (rsV.getObject(33) != null) { String vectorString = null; - + String value = rsV.getString(32); - CvssV4Data.Version version = CvssV4Data.Version.fromValue(value); + final CvssV4Data.Version version = CvssV4Data.Version.fromValue(value); CvssV4Data.AttackVectorType attackVector = null; value = rsV.getString(33); if (value != null) { @@ -1002,35 +1002,33 @@ public Vulnerability getVulnerability(String cve, Connection conn) throws Databa environmentalSeverity = CvssV4Data.SeverityType.fromValue(value); } //initializing data twice to get the vector string. I really should have designed the object better... - CvssV4Data data = new CvssV4Data(version, vectorString, attackVector, attackComplexity, attackRequirements, privilegesRequired, - userInteraction, vulnConfidentialityImpact, vulnIntegrityImpact, vulnAvailabilityImpact, subConfidentialityImpact, - subIntegrityImpact, subAvailabilityImpact, exploitMaturity, confidentialityRequirement, integrityRequirement, - availabilityRequirement, modifiedAttackVector, modifiedAttackComplexity, modifiedAttackRequirements, - modifiedPrivilegesRequired, modifiedUserInteraction, modifiedVulnConfidentialityImpact, modifiedVulnIntegrityImpact, - modifiedVulnAvailabilityImpact, modifiedSubConfidentialityImpact, modifiedSubIntegrityImpact, modifiedSubAvailabilityImpact, - safety, automatable, recovery, valueDensity, vulnerabilityResponseEffort, providerUrgency, baseScore, baseSeverity, - threatScore, threatSeverity, environmentalScore, environmentalSeverity); + CvssV4Data data = new CvssV4Data(version, vectorString, attackVector, attackComplexity, attackRequirements, privilegesRequired, + userInteraction, vulnConfidentialityImpact, vulnIntegrityImpact, vulnAvailabilityImpact, subConfidentialityImpact, + subIntegrityImpact, subAvailabilityImpact, exploitMaturity, confidentialityRequirement, integrityRequirement, + availabilityRequirement, modifiedAttackVector, modifiedAttackComplexity, modifiedAttackRequirements, + modifiedPrivilegesRequired, modifiedUserInteraction, modifiedVulnConfidentialityImpact, modifiedVulnIntegrityImpact, + modifiedVulnAvailabilityImpact, modifiedSubConfidentialityImpact, modifiedSubIntegrityImpact, + modifiedSubAvailabilityImpact, safety, automatable, recovery, valueDensity, vulnerabilityResponseEffort, + providerUrgency, baseScore, baseSeverity, threatScore, threatSeverity, environmentalScore, environmentalSeverity); vectorString = data.toString(); - data = new CvssV4Data(version, vectorString, attackVector, attackComplexity, attackRequirements, privilegesRequired, - userInteraction, vulnConfidentialityImpact, vulnIntegrityImpact, vulnAvailabilityImpact, subConfidentialityImpact, - subIntegrityImpact, subAvailabilityImpact, exploitMaturity, confidentialityRequirement, integrityRequirement, - availabilityRequirement, modifiedAttackVector, modifiedAttackComplexity, modifiedAttackRequirements, - modifiedPrivilegesRequired, modifiedUserInteraction, modifiedVulnConfidentialityImpact, modifiedVulnIntegrityImpact, - modifiedVulnAvailabilityImpact, modifiedSubConfidentialityImpact, modifiedSubIntegrityImpact, modifiedSubAvailabilityImpact, - safety, automatable, recovery, valueDensity, vulnerabilityResponseEffort, providerUrgency, baseScore, baseSeverity, - threatScore, threatSeverity, environmentalScore, environmentalSeverity); - - String source = rsV.getString(71); + data = new CvssV4Data(version, vectorString, attackVector, attackComplexity, attackRequirements, privilegesRequired, + userInteraction, vulnConfidentialityImpact, vulnIntegrityImpact, vulnAvailabilityImpact, subConfidentialityImpact, + subIntegrityImpact, subAvailabilityImpact, exploitMaturity, confidentialityRequirement, integrityRequirement, + availabilityRequirement, modifiedAttackVector, modifiedAttackComplexity, modifiedAttackRequirements, + modifiedPrivilegesRequired, modifiedUserInteraction, modifiedVulnConfidentialityImpact, modifiedVulnIntegrityImpact, + modifiedVulnAvailabilityImpact, modifiedSubConfidentialityImpact, modifiedSubIntegrityImpact, + modifiedSubAvailabilityImpact, safety, automatable, recovery, valueDensity, vulnerabilityResponseEffort, + providerUrgency, baseScore, baseSeverity, threatScore, threatSeverity, environmentalScore, environmentalSeverity); + + final String source = rsV.getString(71); CvssV4.Type cvssType = null; value = rsV.getString(72); if (value != null) { cvssType = CvssV4.Type.fromValue(value); } - - CvssV4 cvssv4 = new CvssV4(source, cvssType, data); + final CvssV4 cvssv4 = new CvssV4(source, cvssType, data); vuln.setCvssV4(cvssv4); } - } else { LOGGER.debug(cve + " does not exist in the database"); return null; @@ -1183,9 +1181,9 @@ private int updateOrInsertVulnerability(DefCveItem cve, String description) { // String 23.v3PrivilegesRequired, String 24.v3UserInteraction, String 25.v3Scope, // String 26.v3ConfidentialityImpact, String 27.v3IntegrityImpact, String 28.v3AvailabilityImpact, // Float 29.v3BaseScore, String 30.v3BaseSeverity, String 31.v3Version -// . String 32.v4version, String 33.v4attackVector, String 34.v4attackComplexity, String 35.v4attackRequirements, -// String 36.v4privilegesRequired, String 37.v4userInteraction, String 38.v4vulnConfidentialityImpact, -// String 39.v4vulnIntegrityImpact, String 40.v4vulnAvailabilityImpact, String 41.v4subConfidentialityImpact, +// . String 32.v4version, String 33.v4attackVector, String 34.v4attackComplexity, String 35.v4attackRequirements, +// String 36.v4privilegesRequired, String 37.v4userInteraction, String 38.v4vulnConfidentialityImpact, +// String 39.v4vulnIntegrityImpact, String 40.v4vulnAvailabilityImpact, String 41.v4subConfidentialityImpact, // String 42.v4subIntegrityImpact, String 43.v4subAvailabilityImpact, String 44.v4exploitMaturity, // String 45.v4confidentialityRequirement, String 46.v4integrityRequirement, String 47.v4availabilityRequirement, // String 48.v4modifiedAttackVector, String 49.v4modifiedAttackComplexity, String 50.v4modifiedAttackRequirements, @@ -1297,7 +1295,7 @@ private int updateOrInsertVulnerability(DefCveItem cve, String description) { optCvssv4 = cve.getCve().getMetrics().getCvssMetricV40().stream().sorted(Comparator.comparing(CvssV4::getType)).findFirst(); } if (optCvssv4 != null && optCvssv4.isPresent()) { - CvssV4 cvssv4 = optCvssv4.get(); + final CvssV4 cvssv4 = optCvssv4.get(); setUpdateColumn(callUpdate, 32, cvssv4.getCvssData().getVersion()); setUpdateColumn(callUpdate, 33, cvssv4.getCvssData().getAttackVector()); setUpdateColumn(callUpdate, 34, cvssv4.getCvssData().getAttackComplexity()); @@ -1993,7 +1991,7 @@ private void setUpdateColumn(PreparedStatement ps, int i, String value) throws S ps.setString(i, value); } } - + private void setUpdateColumn(PreparedStatement ps, int i, CvssV4.Type value) throws SQLException { if (value == null) { ps.setNull(i, java.sql.Types.VARCHAR); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveItemOperator.java b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveItemOperator.java index 601c7a7d0d7..113d3a12679 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveItemOperator.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveItemOperator.java @@ -219,7 +219,7 @@ public boolean isRejected(String description) { boolean testCveCpeStartWithFilter(final DefCveItem cve) { if (cve.getCve().getConfigurations() != null) { //cycle through to see if this is a CPE we care about (use the CPE filters - boolean result = cve.getCve().getConfigurations().stream() + final boolean result = cve.getCve().getConfigurations().stream() .map(Config::getNodes) .flatMap(List::stream) .filter(node -> node != null) diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseManager.java b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseManager.java index 951a7a122cf..b067cc93891 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseManager.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseManager.java @@ -147,7 +147,8 @@ private void initialize() throws DatabaseException { driver = DriverLoader.load(driverName, driverPath); } else { driver = DriverLoader.load(driverName); - LOGGER.warn("Explicitly loaded driver {} from classpath; if JDBCv4 service loading is supported by the driver you should remove the dbDriver configuration", driverName); + LOGGER.warn("Explicitly loaded driver {} from classpath; if JDBCv4 service loading is supported " + + "by the driver you should remove the dbDriver configuration", driverName); } } catch (DriverLoadException ex) { LOGGER.debug("Unable to load database driver", ex); @@ -199,7 +200,8 @@ private void initialize() throws DatabaseException { throw new DatabaseException("Unable to connect to the database", ex); } } else if (isH2 && ex.getMessage().contains("file version or invalid file header")) { - LOGGER.error("Incompatible or corrupt database found. To resolve this issue please remove the existing database by running purge"); + LOGGER.error("Incompatible or corrupt database found. To resolve this issue please remove the existing " + + "database by running purge"); throw new DatabaseException("Incompatible or corrupt database found; run the purge command to resolve the issue"); } else { LOGGER.debug("Unable to connect to the database", ex); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java index 9b8449b1664..698e0bcd749 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java @@ -17,8 +17,6 @@ */ package org.owasp.dependencycheck.data.nvdcve; -import java.time.Instant; -import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Map; @@ -27,7 +25,6 @@ import java.util.TreeMap; import javax.annotation.concurrent.ThreadSafe; -import org.owasp.dependencycheck.data.update.exception.UpdateException; import org.owasp.dependencycheck.utils.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/H2Functions.java b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/H2Functions.java index b254aafa5f4..edb46a4efe2 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/H2Functions.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/H2Functions.java @@ -233,10 +233,10 @@ public static ResultSet updateVulnerability(final Connection conn, String cve, Float v3ImpactScore, String v3AttackVector, String v3AttackComplexity, String v3PrivilegesRequired, String v3UserInteraction, String v3Scope, String v3ConfidentialityImpact, String v3IntegrityImpact, String v3AvailabilityImpact, - Float v3BaseScore, String v3BaseSeverity, String v3Version, String v4version, - String v4attackVector, String v4attackComplexity, String v4attackRequirements, - String v4privilegesRequired, String v4userInteraction, String v4vulnConfidentialityImpact, - String v4vulnIntegrityImpact, String v4vulnAvailabilityImpact, String v4subConfidentialityImpact, + Float v3BaseScore, String v3BaseSeverity, String v3Version, String v4version, + String v4attackVector, String v4attackComplexity, String v4attackRequirements, + String v4privilegesRequired, String v4userInteraction, String v4vulnConfidentialityImpact, + String v4vulnIntegrityImpact, String v4vulnAvailabilityImpact, String v4subConfidentialityImpact, String v4subIntegrityImpact, String v4subAvailabilityImpact, String v4exploitMaturity, String v4confidentialityRequirement, String v4integrityRequirement, String v4availabilityRequirement, String v4modifiedAttackVector, String v4modifiedAttackComplexity, String v4modifiedAttackRequirements, @@ -245,7 +245,7 @@ public static ResultSet updateVulnerability(final Connection conn, String cve, String v4modifiedSubIntegrityImpact, String v4modifiedSubAvailabilityImpact, String v4safety, String v4automatable, String v4recovery, String v4valueDensity, String v4vulnerabilityResponseEffort, String v4providerUrgency, Float v4baseScore, String v4baseSeverity, Float v4threatScore, - String v4threatSeverity, Float v4environmentalScore, String v4environmentalSeverity, + String v4threatSeverity, Float v4environmentalScore, String v4environmentalSeverity, String v4source, String v4type) throws SQLException { final SimpleResultSet ret = new SimpleResultSet(); @@ -374,8 +374,6 @@ public static ResultSet updateVulnerability(final Connection conn, String cve, setFloatOrNull(merge, 28, v3BaseScore); setStringOrNull(merge, 29, v3BaseSeverity); setStringOrNull(merge, 30, v3Version); - - setStringOrNull(merge, 31, v4version); setStringOrNull(merge, 32, v4attackVector); @@ -425,7 +423,7 @@ public static ResultSet updateVulnerability(final Connection conn, String cve, } else { merge.setInt(72, vulnerabilityId); } - + final int count = merge.executeUpdate(); if (vulnerabilityId == 0) { try (ResultSet rs = merge.getGeneratedKeys()) { @@ -458,7 +456,8 @@ public static ResultSet updateVulnerability(final Connection conn, String cve, * @param requiredAction the action required * @param dueDate the due date * @param notes notes - * @throws SQLException thrown if there is a database error merging the Known Exploited information to the database + * @throws SQLException thrown if there is a database error merging the + * Known Exploited information to the database */ public static void mergeKnownExploited(final Connection conn, String cveId, String vendorProject, String product, String vulnerabilityName, diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/HostedSuppressionsDataSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/HostedSuppressionsDataSource.java index fd498dbbcb1..e50d12af9ad 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/HostedSuppressionsDataSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/HostedSuppressionsDataSource.java @@ -33,7 +33,6 @@ import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; -import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; public class HostedSuppressionsDataSource extends LocalDataSource { @@ -104,7 +103,7 @@ protected boolean shouldUpdate(File repo) throws NumberFormatException { boolean proceed = true; if (repo != null && repo.isFile()) { final int validForHours = settings.getInt(Settings.KEYS.HOSTED_SUPPRESSIONS_VALID_FOR_HOURS, 2); - long lastUpdatedOn = getLastUpdated(repo); + final long lastUpdatedOn = getLastUpdated(repo); final long now = System.currentTimeMillis(); LOGGER.debug("Last updated: {}", lastUpdatedOn); LOGGER.debug("Now: {}", now); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/LocalDataSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/LocalDataSource.java index bf30737861e..88d51840668 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/LocalDataSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/LocalDataSource.java @@ -1,17 +1,19 @@ /* - * Copyright 2024 OWASP. + * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * Copyright (c) 2024 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck.data.update; @@ -22,7 +24,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; -import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,9 +45,9 @@ public abstract class LocalDataSource implements CachedWebDataSource { * @param timestamp the epoch timestamp to store */ protected void saveLastUpdated(File repo, long timestamp) { - File timestampFile = new File(repo + ".properties"); + final File timestampFile = new File(repo + ".properties"); try (OutputStream out = new FileOutputStream(timestampFile)) { - Properties prop = new Properties(); + final Properties prop = new Properties(); prop.setProperty("LAST_UPDATED", String.valueOf(timestamp)); prop.store(out, null); } catch (IOException ex) { @@ -63,10 +64,10 @@ protected void saveLastUpdated(File repo, long timestamp) { */ protected long getLastUpdated(File repo) { long lastUpdatedOn = 0; - File timestampFile = new File(repo + ".properties"); + final File timestampFile = new File(repo + ".properties"); if (timestampFile.isFile()) { try (InputStream is = new FileInputStream(timestampFile)) { - Properties props = new Properties(); + final Properties props = new Properties(); props.load(is); lastUpdatedOn = Integer.parseInt(props.getProperty("LAST_UPDATED", "0")); } catch (IOException | NumberFormatException ex) { diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java index dd51c47b7a3..1e1b62c42ef 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/NvdApiDataSource.java @@ -139,7 +139,7 @@ private boolean processDatafeed(String nvdDataFeedUrl) throws UpdateException { dbProperties = cveDb.getDatabaseProperties(); if (checkUpdate()) { final UrlData data = extractUrlData(nvdDataFeedUrl); - String url = data.getUrl(); + final String url = data.getUrl(); String pattern = data.getPattern(); final Properties cacheProperties = getRemoteCacheProperties(url, pattern); if (pattern == null) { @@ -220,7 +220,7 @@ private boolean processDatafeed(String nvdDataFeedUrl) throws UpdateException { private void storeLastModifiedDates(final ZonedDateTime now, final Properties cacheProperties, final Map updateable) throws UpdateException { - ZonedDateTime lastModifiedRequest = DatabaseProperties.getTimestamp(cacheProperties, + final ZonedDateTime lastModifiedRequest = DatabaseProperties.getTimestamp(cacheProperties, NVD_API_CACHE_MODIFIED_DATE + ".modified"); dbProperties.save(DatabaseProperties.NVD_CACHE_LAST_CHECKED, now); dbProperties.save(DatabaseProperties.NVD_CACHE_LAST_MODIFIED, lastModifiedRequest); @@ -350,7 +350,7 @@ private boolean processApi() throws UpdateException { int ctr = 0; try (NvdCveClient api = builder.build()) { while (api.hasNext()) { - Collection items = api.next(); + final Collection items = api.next(); max = api.getTotalAvailable(); if (ctr == 0) { LOGGER.info(String.format("NVD API has %,d records in this update", max)); @@ -380,7 +380,8 @@ private boolean processApi() throws UpdateException { } } catch (Exception e) { - if (e instanceof NvdApiException && (e.getMessage().equals("NVD Returned Status Code: 404") || e.getMessage().equals("NVD Returned Status Code: 403"))) { + if (e instanceof NvdApiException && (e.getMessage().equals("NVD Returned Status Code: 404") + || e.getMessage().equals("NVD Returned Status Code: 403"))) { final String msg; if (key != null) { msg = "Error updating the NVD Data; the NVD returned a 403 or 404 error\n\nPlease ensure your API Key is valid; " @@ -607,7 +608,7 @@ protected final Properties getRemoteCacheProperties(String url, String pattern) } catch (URISyntaxException ex) { throw new UpdateException("Invalid NVD Cache URL", ex); } catch (DownloadFailedException | ResourceNotFoundException ex) { - String metaPattern; + final String metaPattern; if (pattern == null) { metaPattern = "nvdcve-{0}.meta"; } else { @@ -616,7 +617,7 @@ protected final Properties getRemoteCacheProperties(String url, String pattern) try { URL metaUrl = new URI(url + MessageFormat.format(metaPattern, "modified")).toURL(); String content = Downloader.getInstance().fetchContent(metaUrl, StandardCharsets.UTF_8); - Properties props = new Properties(); + final Properties props = new Properties(); props.load(new StringReader(content)); ZonedDateTime lmd = DatabaseProperties.getIsoTimestamp(props, "lastModifiedDate"); DatabaseProperties.setTimestamp(properties, "lastModifiedDate.modified", lmd); @@ -645,8 +646,14 @@ protected final Properties getRemoteCacheProperties(String url, String pattern) protected static class UrlData { + /** + * The URL to download resources from. + */ private final String url; + /** + * The pattern to construct the file names for resources from. + */ private final String pattern; public UrlData(String url, String pattern) { diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java index b2d04273c14..7dcbf994b0d 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java @@ -110,7 +110,7 @@ protected boolean shouldUpdate(File repo) throws NumberFormatException { boolean proceed = true; if (repo != null && repo.isFile()) { final int validForHours = settings.getInt(Settings.KEYS.ANALYZER_RETIREJS_REPO_VALID_FOR_HOURS, 0); - long lastUpdatedOn = getLastUpdated(repo); + final long lastUpdatedOn = getLastUpdated(repo); final long now = System.currentTimeMillis(); LOGGER.debug("Last updated: {}", lastUpdatedOn); LOGGER.debug("Now: {}", now); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveApiJson20CveItemSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveApiJson20CveItemSource.java index 618bdc86676..cfe7d5d5b60 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveApiJson20CveItemSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveApiJson20CveItemSource.java @@ -29,12 +29,34 @@ public class CveApiJson20CveItemSource implements CveItemSource { + /** + * The object mapper. + */ private final ObjectMapper mapper; + /** + * The input stream. + */ private final InputStream inputStream; + /** + * The JSON Parser + */ private final JsonParser jsonParser; + /** + * The current item. + */ private DefCveItem currentItem; + /** + * The next item. + */ private DefCveItem nextItem; + /** + * Constructs a CVE Item Source record. + * + * @param inputStream the input source to read from + * @throws IOException thrown if there is an issue reading from the input + * stream + */ public CveApiJson20CveItemSource(InputStream inputStream) throws IOException { mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); @@ -45,8 +67,8 @@ public CveApiJson20CveItemSource(InputStream inputStream) throws IOException { do { token = jsonParser.nextToken(); if (token == JsonToken.FIELD_NAME) { - String fieldName = jsonParser.currentName(); - if (fieldName.equals("vulnerabilities") && (jsonParser.nextToken() == JsonToken.START_ARRAY)) { + final String fieldName = jsonParser.currentName(); + if ("vulnerabilities".equals(fieldName) && (jsonParser.nextToken() == JsonToken.START_ARRAY)) { nextItem = readItem(jsonParser); } } diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveItemSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveItemSource.java index c347d63edfe..18bab1fcf21 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveItemSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/CveItemSource.java @@ -23,7 +23,19 @@ public interface CveItemSource extends AutoCloseable { + /** + * Returns whether there is another item. + * + * @return truefalse. + */ boolean hasNext(); + /** + * Returns the next item. + * + * @return the next item + * @throws IOException thrown if there is an error reading from the source + */ T next() throws IOException; } diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/JsonArrayCveItemSource.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/JsonArrayCveItemSource.java index 38ee6b9e086..caf2c99fca6 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/JsonArrayCveItemSource.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/JsonArrayCveItemSource.java @@ -22,19 +22,40 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.github.jeremylong.openvulnerability.client.nvd.DefCveItem; -import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; public class JsonArrayCveItemSource implements CveItemSource { + /** + * The object mapper. + */ private final ObjectMapper mapper; + /** + * The input stream. + */ private final InputStream inputStream; + /** + * The JSON parser. + */ private final JsonParser jsonParser; + /** + * The current item. + */ private DefCveItem currentItem; + /** + * The next item. + */ private DefCveItem nextItem; + /** + * Constructs a new Item Source. + * + * @param inputStream the input stream to read from + * @throws IOException thrown if there is a problem reading from the input + * stream + */ public JsonArrayCveItemSource(InputStream inputStream) throws IOException { mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); diff --git a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java index 6585da2df58..6dde51bbd87 100644 --- a/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java +++ b/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/api/NvdApiProcessor.java @@ -114,7 +114,7 @@ public NvdApiProcessor call() throws Exception { private void updateCveDb(CveItemSource itemSource) throws IOException { while (itemSource.hasNext()) { - DefCveItem entry = itemSource.next(); + final DefCveItem entry = itemSource.next(); try { cveDB.updateVulnerability(entry, mapper.getEcosystem(entry)); } catch (Exception ex) { diff --git a/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java b/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java index d79b75ecfe6..aa2625befde 100644 --- a/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java +++ b/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java @@ -117,7 +117,7 @@ public enum Source { * The CVSS V3 scoring information. */ private CvssV3 cvssV3; - + /** * The CVSS V4 scoring information. */ @@ -255,6 +255,7 @@ public void addReference(String referenceSource, String referenceName, String re public void setKnownExploitedVulnerability(org.owasp.dependencycheck.data.knownexploited.json.Vulnerability kev) { this.knownExploitedVulnerability = kev; } + /** * Get the value of knownExploitedVulnerability. * @@ -263,6 +264,7 @@ public void setKnownExploitedVulnerability(org.owasp.dependencycheck.data.knowne public org.owasp.dependencycheck.data.knownexploited.json.Vulnerability getKnownExploitedVulnerability() { return knownExploitedVulnerability; } + /** * Get the value of vulnerableSoftware. * @@ -343,8 +345,8 @@ public CvssV3 getCvssV3() { public void setCvssV3(CvssV3 cvssV3) { this.cvssV3 = cvssV3; } - - /** + + /** * Get the CVSS V3 scoring information. * * @return the CVSS V3 scoring information @@ -477,8 +479,7 @@ public String toString() { * on both sides. If any of the vulnerabilities does not have a CVSSv3 score * the sort order may be off, but it will be consistent. *
- * The ranking (high to low) of severity can be informally represented as - * {@code <CVSSv3 critical> >> <Unscored recognized critical> >> + * The ranking (high to low) of severity can be informally represented as {@code <CVSSv3 critical> >> <Unscored recognized critical> >> * <Unscored unrecognized (assumed Critical)> >> <Score-based comparison for high-or-lower scoring severities with * recognized unscored severities taking the lower bound of the comparable CVSSv3 range> * } diff --git a/core/src/main/java/org/owasp/dependencycheck/processing/BundlerAuditProcessor.java b/core/src/main/java/org/owasp/dependencycheck/processing/BundlerAuditProcessor.java index 4eef0b1dea9..f962db627ce 100644 --- a/core/src/main/java/org/owasp/dependencycheck/processing/BundlerAuditProcessor.java +++ b/core/src/main/java/org/owasp/dependencycheck/processing/BundlerAuditProcessor.java @@ -304,6 +304,7 @@ private Vulnerability createVulnerability(String parentName, Dependency dependen * Creates the dependency based off of the gem. * * @param engine the engine used for scanning + * @param gemFile the gem file * @param parentName the gem parent * @param fileName the file name * @param filePath the file path @@ -311,7 +312,8 @@ private Vulnerability createVulnerability(String parentName, Dependency dependen * @return the dependency to add * @throws IOException thrown if a temporary gem file could not be written */ - private Dependency createDependencyForGem(Engine engine, File gemFile, String parentName, String fileName, String filePath, String gem) throws IOException { + private Dependency createDependencyForGem(Engine engine, File gemFile, String parentName, String fileName, + String filePath, String gem) throws IOException { final String displayFileName = String.format("%s%c%s:%s", parentName, File.separatorChar, fileName, gem); final Dependency dependency = new Dependency(gemFile, true); dependency.setSha1sum(Checksum.getSHA1Checksum(displayFileName)); diff --git a/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java b/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java index f792e558b38..640fbfbdf4a 100644 --- a/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java +++ b/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java @@ -124,10 +124,10 @@ public enum Format { */ JUNIT, /** - * Generate Report in GitLab dependency check format: + * Generate Report in GitLab dependency check format. * * @see format definition - * @see additional explantions on the format + * @see additional explanations on the format */ GITLAB } diff --git a/core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java b/core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java index 7cca0fbaf09..27cb3245df7 100644 --- a/core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java +++ b/core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java @@ -122,6 +122,11 @@ private String determineScore(Vulnerability vuln) { return "unknown"; } + /** + * Map severity names from various sources to a standard set of severity names. + * @param sev the severity name + * @return the standardized severity name (critical, high, medium, low, unknown) + */ public String normalizeSeverity(String sev) { switch (sev.toLowerCase()) { case "critical": diff --git a/core/src/main/java/org/owasp/dependencycheck/utils/Utils.java b/core/src/main/java/org/owasp/dependencycheck/utils/Utils.java index 4f4c826a281..e422a848e8f 100644 --- a/core/src/main/java/org/owasp/dependencycheck/utils/Utils.java +++ b/core/src/main/java/org/owasp/dependencycheck/utils/Utils.java @@ -63,7 +63,7 @@ public static int getJavaVersion() { */ public static int getJavaUpdateVersion() { //"1.8.0_144" "11.0.2+9" "17.0.8.1" - String runtimeVersion = System.getProperty("java.version"); + final String runtimeVersion = System.getProperty("java.version"); return parseUpdate(runtimeVersion); } @@ -76,7 +76,7 @@ public static int getJavaUpdateVersion() { protected static int parseUpdate(String runtimeVersion) { LOGGER.debug(runtimeVersion); try { - String[] parts = runtimeVersion.split("\\."); + final String[] parts = runtimeVersion.split("\\."); if (parts.length == 4 && isNumeric(parts)) { return Integer.parseInt(parts[2]); } @@ -117,11 +117,4 @@ private static boolean isNumeric(String[] parts) { } return true; } - - public static void main(String[] args) { - System.out.println("Java runtime : " + System.getProperty("java.runtime.version")); - System.out.println("Java version : " + getJavaVersion()); - System.out.println("Java update : " + getJavaUpdateVersion()); - - } } diff --git a/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java b/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java index 19b169c219f..0e3b2a7c0d6 100644 --- a/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java +++ b/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java @@ -919,7 +919,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma @Parameter(property = "serverId") private String serverId; /** - * The NVD API Key. The parameters {@link #nvdApiKeyEnvironmentVariable} or {@link #nvdApiServerId} should be used instead otherwise + * The NVD API Key. The parameters {@link #nvdApiKeyEnvironmentVariable} or {@link #nvdApiServerId} should be used instead otherwise * Maven debug logging could expose the API Key (see GHSA-qqhq-8r2c-c3f5). * This takes precedence over {@link #nvdApiServerId} and {@link #nvdApiKeyEnvironmentVariable}. */ diff --git a/pom.xml b/pom.xml index 0f764b9e625..feffca696bd 100644 --- a/pom.xml +++ b/pom.xml @@ -365,11 +365,6 @@ Copyright (c) 2012 - Jeremy Long - - se.bjurr.violations - violation-comments-to-github-maven-plugin - 1.67 - @@ -761,50 +756,45 @@ Copyright (c) 2012 - Jeremy Long - se.bjurr.violations - violation-comments-to-github-maven-plugin - - - se.bjurr.violations - violation-comments-to-github-lib - 1.83.1 - - - se.bjurr.violations - violations-lib - 1.157.1 - - + org.apache.maven.plugins + maven-checkstyle-plugin + ${reporting.checkstyle-plugin.version} + + + false + verify + + checkstyle-aggregate + + + - false - jeremylong - DependencyCheck - https://api.github.com/ - false - true - true - - INFO - - - FINDBUGS - Spotbugs - . - .*/spotbugsXml.xml$ - - - CHECKSTYLE - Checkstyle - . - .*/checkstyle-result.xml$ - - - SARIF - Sarif - . - .*/semgrep.sarif$ - - + ${project.build.directory}/checkstyle-result.sarif + sarif + false + false + **/HelpMojo.java + ${project.basedir}/src/main/config/checkstyle-checks.xml + ${project.basedir}/src/main/config/checkstyle-header.txt + ${project.basedir}/src/main/config/checkstyle-suppressions.xml + checkstyle.suppressions.file + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.maven.plugin.version} + + + verify + + spotbugs + + + + + true + ${odc.config}/spotbugs_excludes.xml @@ -828,7 +818,7 @@ Copyright (c) 2012 - Jeremy Long false - Copyright© 2012-21 Jeremy Long. All Rights Reserved. + Copyright© 2012-24 Jeremy Long. All Rights Reserved. **/generated-sources/**/*.java diff --git a/src/main/config/checkstyle-checks.xml b/src/main/config/checkstyle-checks.xml index 8180fe46698..2f73e1754b0 100644 --- a/src/main/config/checkstyle-checks.xml +++ b/src/main/config/checkstyle-checks.xml @@ -203,9 +203,9 @@ - +