Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate SARIF File Of Project Vulnerability Findings #3561

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,25 @@

import alpine.common.logging.Logger;
import alpine.event.framework.Event;
import alpine.model.About;
import alpine.persistence.PaginatedResult;
import alpine.server.auth.PermissionRequired;
import alpine.server.resources.AlpineResource;
import io.pebbletemplates.pebble.PebbleEngine;
import io.pebbletemplates.pebble.template.PebbleTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.ResponseHeader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.text.WordUtils;
import org.dependencytrack.auth.Permissions;
import org.dependencytrack.event.PolicyEvaluationEvent;
import org.dependencytrack.event.RepositoryMetaEvent;
Expand Down Expand Up @@ -67,12 +76,13 @@
public class FindingResource extends AlpineResource {

private static final Logger LOGGER = Logger.getLogger(FindingResource.class);
public static final String MEDIA_TYPE_SARIF_JSON = "application/sarif+json";

@GET
@Path("/project/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON, MEDIA_TYPE_SARIF_JSON})
@ApiOperation(
value = "Returns a list of all findings for a specific project",
value = "Returns a list of all findings for a specific project or generates SARIF file if Accept: application/sarif+json header is provided",
response = Finding.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of findings")
Expand All @@ -87,13 +97,24 @@ public Response getFindingsByProject(@PathParam("uuid") String uuid,
@ApiParam(value = "Optionally includes suppressed findings")
@QueryParam("suppressed") boolean suppressed,
@ApiParam(value = "Optionally limit findings to specific sources of vulnerability intelligence")
@QueryParam("source") Vulnerability.Source source) {
@QueryParam("source") Vulnerability.Source source,
@HeaderParam("accept") String acceptHeader) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (qm.hasAccess(super.getPrincipal(), project)) {
//final long totalCount = qm.getVulnerabilityCount(project, suppressed);
final List<Finding> findings = qm.getFindings(project, suppressed);
if (acceptHeader != null && acceptHeader.contains(MEDIA_TYPE_SARIF_JSON)) {
try {
return Response.ok(generateSARIF(findings), MEDIA_TYPE_SARIF_JSON)
.header("content-disposition","attachment; filename=\"findings-" + uuid + ".sarif\"")
.build();
} catch (IOException ioException) {
LOGGER.error(ioException.getMessage(), ioException);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("An error occurred while generating SARIF file").build();
}
}
if (source != null) {
final List<Finding> filteredList = findings.stream().filter(finding -> source.name().equals(finding.getVulnerability().get("source"))).collect(Collectors.toList());
return Response.ok(filteredList).header(TOTAL_COUNT_HEADER, filteredList.size()).build();
Expand Down Expand Up @@ -298,4 +319,45 @@ public Response getAllFindings(@ApiParam(value = "Show inactive projects")
}
}

private String generateSARIF(List<Finding> findings) throws IOException {
final PebbleEngine engine = new PebbleEngine.Builder()
.newLineTrimming(false)
.defaultEscapingStrategy("json")
.build();
final PebbleTemplate sarifTemplate = engine.getTemplate("templates/findings/sarif.peb");

final Map<String, Object> context = new HashMap<>();
final About about = new About();

// Using "vulnId" as key, forming a list of unique vulnerabilities across all findings
// Also converts cweName to PascalCase, since it will be used as rule.name in the SARIF file
List<Map<String, Object>> uniqueVulnerabilities = findings.stream()
.collect(Collectors.toMap(
finding -> finding.getVulnerability().get("vulnId"),
FindingResource::convertCweNameToPascalCase,
(existingVuln, replacementVuln) -> existingVuln))
.values()
.stream()
.toList();

context.put("findings", findings);
context.put("dependencyTrackVersion", about.getVersion());
context.put("uniqueVulnerabilities", uniqueVulnerabilities);

try (final Writer writer = new StringWriter()) {
sarifTemplate.evaluate(writer, context);
return writer.toString();
}
}

private static Map<String, Object> convertCweNameToPascalCase(Finding finding) {
final Object cweName = finding.getVulnerability()
.get("cweName");
if (cweName != null) {
final String pascalCasedCweName = WordUtils.capitalizeFully(cweName.toString()).replaceAll("\\s", "");
finding.getVulnerability().put("cweName", pascalCasedCweName);
}
return finding.getVulnerability();
}

}
58 changes: 58 additions & 0 deletions src/main/resources/templates/findings/sarif.peb
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"version": "2.1.0",
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json",
"runs": [
{
"tool": {
"driver": {
"name": "OWASP Dependency-Track",
"fullName": "OWASP Dependency-Track - {{ dependencyTrackVersion }}",
"version": "{{ dependencyTrackVersion }}",
"informationUri": "https://dependencytrack.org/",
"rules": [{% for vuln in uniqueVulnerabilities %}
{
"id": "{{ vuln.vulnId }}",
"name": "{{ vuln.cweName }}",
"shortDescription": {
"text": "{{ vuln.vulnId }}"
},
"fullDescription": {
"text": "{{ vuln.description | trim }}"
}
}{% if not loop.last %},{% endif %}{% endfor %}
]
}
},
"results": [{% for finding in findings %}
{
"ruleId": "{{ finding.vulnerability.vulnId }}",
"message": {
"text": "{{ finding.vulnerability.description | trim }}"
},
"locations": [
{
"logicalLocations": [
{
"fullyQualifiedName": "{{ finding.component.purl }}"
}
]
}
],
"level": {% if ['LOW', 'INFO'] contains finding.vulnerability.severity %}"note",{% elseif finding.vulnerability.severity == 'MEDIUM' %}"warning",{% elseif ['HIGH', 'CRITICAL'] contains finding.vulnerability.severity %}"error",{% else %}"none",{% endif %}
"properties": {
"name": "{{ finding.component.name }}",
"group": "{{ finding.component.group }}",
"version": "{{ finding.component.version }}",
"source": "{{ finding.vulnerability.source }}",
"cweId": "{{ finding.vulnerability.cweId }}",
"cvssV3BaseScore": "{{ finding.vulnerability.cvssV3BaseScore }}",
"epssScore": "{{ finding.vulnerability.epssScore }}",
"epssPercentile": "{{ finding.vulnerability.epssPercentile }}",
"severityRank": "{{ finding.vulnerability.severityRank }}",
"recommendation": "{{ finding.vulnerability.recommendation | trim }}"
}
}{% if not loop.last %},{% endif %}{% endfor %}
]
}
]
}
Loading