Skip to content

Commit

Permalink
devonfw#103: url analyzer works and vulnerabilities are retrieved
Browse files Browse the repository at this point in the history
  • Loading branch information
MattesMrzik committed Nov 15, 2023
1 parent 5f162e2 commit e5c70e7
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 197 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,26 @@ protected String mapVersion(String version) {
return super.mapVersion(version);
}

protected String getCPEVendor() {
@Override
protected String getCpeVendor() {

// return "vikwp";
return "eclipse";
}

protected String getCPEProduct() {
@Override
protected String getCpeProduct() {

// return "vik_booking";
return "temurin";
}

@Override
protected String mapUrlVersionToCpeVersion(String version) {



// return "1.5.8";
return version;
}

@Override
protected void addVersion(UrlVersion urlVersion) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,18 @@ protected final String getToolWithEdition() {
return tool + "/" + edition;
}

protected String getCPEVendor() {
protected String getCpeVendor() {

return "";
}

protected String getCPEProduct() {
protected String getCpeProduct() {

return "";
}

protected String mapUrlVersionToCPEVersion(String version) {
protected String mapUrlVersionToCpeVersion(String version) {

return version;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,14 @@ public class UpdateManager extends AbstractProcessorWithTimeout {
private final UrlRepository urlRepository;

private final List<AbstractUrlUpdater> updaters = Arrays.asList(new AndroidStudioUrlUpdater(), new AwsUrlUpdater(),
new AzureUrlUpdater(), new CobigenUrlUpdater(), new DockerDesktopUrlUpdater() , new DotNetUrlUpdater(), new EclipseCppUrlUpdater(),
new EclipseJavaUrlUpdater(), new GCloudUrlUpdater(), new GcViewerUrlUpdater(), new GhUrlUpdater(),
new GraalVmCommunityUpdater(), new GraalVmOracleUrlUpdater(), new GradleUrlUpdater(), new HelmUrlUpdater(), new IntellijUrlUpdater(),
new JavaUrlUpdater(), new JenkinsUrlUpdater(), new JmcUrlUpdater(), new KotlincUrlUpdater(), new KotlincNativeUrlUpdater(),
new LazyDockerUrlUpdater(), new MvnUrlUpdater(), new NodeUrlUpdater(), new NpmUrlUpdater(), new OcUrlUpdater(),
new PipUrlUpdater(), new PythonUrlUpdater(), new QuarkusUrlUpdater(), new DockerRancherDesktopUrlUpdater(),
new SonarUrlUpdater(), new TerraformUrlUpdater(), new TomcatUrlUpdater(), new VsCodeUrlUpdater());
new AzureUrlUpdater(), new CobigenUrlUpdater(), new DockerDesktopUrlUpdater(), new DotNetUrlUpdater(),
new EclipseCppUrlUpdater(), new EclipseJavaUrlUpdater(), new GCloudUrlUpdater(), new GcViewerUrlUpdater(),
new GhUrlUpdater(), new GraalVmCommunityUpdater(), new GraalVmOracleUrlUpdater(), new GradleUrlUpdater(),
new HelmUrlUpdater(), new IntellijUrlUpdater(), new JavaUrlUpdater(), new JenkinsUrlUpdater(),
new JmcUrlUpdater(), new KotlincUrlUpdater(), new KotlincNativeUrlUpdater(), new LazyDockerUrlUpdater(),
new MvnUrlUpdater(), new NodeUrlUpdater(), new NpmUrlUpdater(), new OcUrlUpdater(), new PipUrlUpdater(),
new PythonUrlUpdater(), new QuarkusUrlUpdater(), new DockerRancherDesktopUrlUpdater(), new SonarUrlUpdater(),
new TerraformUrlUpdater(), new TomcatUrlUpdater(), new VsCodeUrlUpdater());

/**
* The constructor.
Expand Down Expand Up @@ -95,10 +96,22 @@ public void updateAll() {
}
}

public String getVendor(String tool) {
AbstractUrlUpdater matchedUpdater = (AbstractUrlUpdater) updaters.stream().filter(updater -> updater.getTool().equals(tool)).toArray()[0];
return matchedUpdater.getCPEVendor();
// updaters.stream().filter(updater -> updater.getTool().equals(tool)).findFirst().ifPresent(AbstractUrlUpdater::getVendor);
public String getCpeVendor(String tool) {

return updaters.stream().filter(updater -> updater.getTool().equals(tool)).findFirst()
.map(AbstractUrlUpdater::getCpeVendor).orElse(null);
}

public String getCpeProduct(String tool) {

return updaters.stream().filter(updater -> updater.getTool().equals(tool)).findFirst()
.map(AbstractUrlUpdater::getCpeProduct).orElse(null);
}

public String mapUrlVersionToCpeVersion(String tool, String urlVersion) {

return updaters.stream().filter(updater -> updater.getTool().equals(tool)).findFirst()
.map(updater -> updater.mapUrlVersionToCpeVersion(urlVersion)).orElse(null);
}

}
192 changes: 44 additions & 148 deletions security/src/main/java/com/devonfw/tools/security/Main.java
Original file line number Diff line number Diff line change
@@ -1,183 +1,79 @@
package com.devonfw.tools.security;

import java.util.List;
import java.util.stream.Collectors;

import com.devonfw.tools.ide.context.IdeContext;
import com.devonfw.tools.ide.context.IdeContextConsole;
import com.devonfw.tools.ide.log.IdeLogLevel;
import com.devonfw.tools.ide.tool.ToolCommandlet;
import com.devonfw.tools.ide.url.model.folder.UrlVersion;
import com.devonfw.tools.ide.url.updater.AbstractUrlUpdater;
import com.devonfw.tools.ide.url.updater.UpdateManager;
import com.devonfw.tools.ide.url.updater.UrlUpdater;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.AnalysisPhase;
import org.owasp.dependencycheck.analyzer.FileNameAnalyzer;
import org.owasp.dependencycheck.analyzer.FileTypeAnalyzer;
import org.owasp.dependencycheck.dependency.*;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.utils.Settings;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Main {
// TODO is owasp dependence i main pomxlm correc tor should i move it to security pomxml

public static void main(String[] args) throws ReportException {

// TODO edit depedency check properties file to switch off analysers, this file is currently read only
public static void main(String[] args) {
// TODO edit dependency check properties file to switch off analysers, this file is currently read only
// TODO maybe this can be done in pom.xml
// or simply remove it like FileNameAnalyzer was removed

//TODO, wenn eine cve gefunden wird. dann in ide cli prompten und auch die cve sagen, damit der user selbst entschienden kann ob es vielleicht doch nicht eine false positive is. weil zb der vendor nicht so richtig gemached worden ist
// TODO: note settings.setBoolean(Settings.KEYS.ANALYZER_NODE_AUDIT_USE_CACHE, false);

// TODO ~/.m2/repository/org/owasp/dependency-check-utils/8.4.2/data/7.0/odc.update.lock
// TODO ~/.m2/repository/org/owasp/dependency-check-utils/8.4.2/data/7.0/odc.update.lock
// why is this not in projects dir but in user dir?

Settings settings = new Settings();
File dir;


settings.setBoolean(Settings.KEYS.ANALYZER_NODE_AUDIT_USE_CACHE, false);


try (Engine engine = new Engine(settings)) {

// das brauche ich um die file endung zu akzeptieren
FileTypeAnalyzer myAnalyzer = new UrlAnalyzer();
// engine.getAnalyzers().add(myAnalyzer);
engine.getFileTypeAnalyzers().add(myAnalyzer);
// engine.getAnalyzers(AnalysisPhase.INFORMATION_COLLECTION).add(new UrlAnalyzer());
List<Dependency> dependencyList = engine.scan("C:\\projects\\_ide\\myUrls");
System.out.println("size of dependencyList is " + dependencyList.size());

// add my infos to dependency
for (Dependency dependency : dependencyList) {
// TODO soll ich auch noch die ulr splitten und die zu evidence machen?
String filePath = dependency.getFilePath();
Path parent = Paths.get(filePath).getParent();
String tool = parent.getParent().getParent().getFileName().toString();
String edition = parent.getParent().getFileName().toString();
String version = parent.getFileName().toString();


// TODO is versions od dependency updated when adding evidence?

// from the context I want to get the JavaUrlUpdater
// UpdateManager updateManager = new UpdateManager(ideContext.getUrlsPath(), null);
// String vendor = updateManager.getVendor("java");

Evidence productEvidence = new Evidence("mysoure", "myname", tool, Confidence.HIGH);
dependency.addEvidence(EvidenceType.PRODUCT, productEvidence);

Evidence editionEvidence = new Evidence("mysoure", "myname", edition, Confidence.HIGH);
dependency.addEvidence(EvidenceType.PRODUCT, editionEvidence);

Evidence versionEvidence = new Evidence("mysoure", "myname", version, Confidence.HIGH);
dependency.addEvidence(EvidenceType.VERSION, versionEvidence);

Evidence vendorEvidence = new Evidence("mysoure", "myname", "oracle", Confidence.HIGH);
dependency.addEvidence(EvidenceType.VENDOR, vendorEvidence);
Engine engine = new Engine(settings); // doesn't work with "try with resource"

IdeContext ideContext = new IdeContextConsole(IdeLogLevel.INFO, null, false);
UpdateManager updateManager = new UpdateManager(ideContext.getUrlsPath(), null);

}

// TODO oder kann ich doch manche analyzer weg machen?
// welche sollen weg?
try {
engine.analyzeDependencies();// needed for db stuff which is private
for (Dependency dependency : engine.getDependencies()) {
engine.removeDependency(dependency);
for (EvidenceType type : EvidenceType.values()) {
for (Evidence evidence : dependency.getEvidence(type)) {
if (!evidence.getName().equals("myname")) {
dependency.removeEvidence(type, evidence);
}
}
}
engine.addDependency(dependency);
}

} catch (ExceptionCollection e) {
throw new RuntimeException(e);
}

// TODO dont do this with this method but try to do it by hand, since i cant seem to add my URL analyzer to the map of engine
// look at path and them extract name and version and vendor maybe from url
List<Throwable> exceptionsList = new ArrayList<>();
ExceptionCollection exceptions = new ExceptionCollection(exceptionsList);

dir = new File("C:\\projects\\devonfw\\report");
engine.writeReports("applicationName", "groupId", "artifactId", "version", dir, "JSON", exceptions);
}
FileTypeAnalyzer myAnalyzer = new UrlAnalyzer(updateManager);
engine.getFileTypeAnalyzers().add(myAnalyzer);
engine.getAnalyzers(AnalysisPhase.INFORMATION_COLLECTION).add(myAnalyzer);
engine.getAnalyzers(AnalysisPhase.INFORMATION_COLLECTION)
.removeIf(analyzer -> analyzer instanceof FileNameAnalyzer);

engine.scan("C:\\projects\\_ide\\myUrls");

String filename = dir.toString() + "\\dependency-check-report.json";
Path filepath = Paths.get(filename);
// Read all lines from the file into a List
String formatted = "";
try {
List<String> lines = Files.readAllLines(filepath);
assert (lines.size() == 1);
formatted = formatJsonString(lines.get(0));

} catch (IOException e) {
throw new RuntimeException(e);
}

Path newfilepath = filepath.getParent().resolve("dependency-check-report2.json");
try {
Files.delete(filepath);
} catch (IOException e) {
engine.analyzeDependencies();// needed for db stuff which is private
} catch (ExceptionCollection e) {
throw new RuntimeException(e);
}
try {
if (Files.exists(newfilepath)) {
Files.delete(newfilepath);
float minV2Severity = 0.0f;
float minV3Severity = 0.0f;

for (Dependency dependency : engine.getDependencies()) {
List<Vulnerability> noSeverity = dependency.getVulnerabilities(true).stream()
.filter(v -> v.getCvssV2() == null && v.getCvssV3() == null).collect(Collectors.toList());
List<Vulnerability> onlyV2Severity = dependency.getVulnerabilities(true).stream()
.filter(v -> v.getCvssV2() != null && v.getCvssV3() == null).collect(Collectors.toList());
List<Vulnerability> hasV3Severity = dependency.getVulnerabilities(true).stream()
.filter(v -> v.getCvssV3() != null).collect(Collectors.toList());

if (!noSeverity.isEmpty()) {
System.out.println("no severity is not empty: " + dependency.getFileName());
System.exit(1);
}
} catch (IOException e) {
throw new RuntimeException(e);
}

try {
Files.write(newfilepath, formatted.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
onlyV2Severity.removeIf(v -> v.getCvssV2().getScore() < minV3Severity);
hasV3Severity.removeIf(v -> v.getCvssV3().getBaseScore() < minV2Severity);

public static String formatJsonString(String jsonString) {
int level = 0;
StringBuilder formattedJson = new StringBuilder();
int stringLength = jsonString.length();

for (int i = 0; i < stringLength; i++) {
char ch = jsonString.charAt(i);

if (ch == '{' || ch == '[') {
formattedJson.append(ch).append("\n").append(getIndent(++level));
} else if (ch == '}' || ch == ']') {
formattedJson.append("\n").append(getIndent(--level)).append(ch);
} else if (ch == ',') {
formattedJson.append(ch).append("\n").append(getIndent(level));
} else {
formattedJson.append(ch);
}
}
System.out.println("There were vulnerabilities found in: " + dependency.getFileName());
onlyV2Severity.forEach(v -> System.out.println("V2: " + v.getName() + " " + v.getCvssV2().getScore()));
hasV3Severity.forEach(v -> System.out.println("V3: " + v.getName() + " " + v.getCvssV3().getBaseScore()));

return formattedJson.toString();
}
// TODO read min levels from console
// TODO list all vulnerabilities, so maybe description, all fields of cvssv3 and cvssv2, cve name, source,
// url of vulnerabilityIds, and vulnerableSoftware
// TODO take all vulnerabilities, or ask for another min level und update the numbers of vulnerabilities
// TODO write vulnerabilities to file -> new format? that includes CVE name?

private static String getIndent(int level) {
StringBuilder indent = new StringBuilder();
for (int i = 0; i < level; i++) {
indent.append("\t");
}
return indent.toString();
}
}

0 comments on commit e5c70e7

Please sign in to comment.