Search in sources :

Example 1 with Package

use of com.checkmarx.sdk.dto.sca.report.Package in project cx-flow by checkmarx-ltd.

the class SarifIssueTracker method generateScaResults.

private void generateScaResults(ScanResults results, List<SarifVulnerability> run) {
    List<Rule> scaScanrules = Lists.newArrayList();
    List<Result> scaScanresultList = Lists.newArrayList();
    Map<String, List<Finding>> findingsMap = results.getScaResults().getFindings().stream().collect(Collectors.groupingBy(Finding::getPackageId));
    List<Package> packages = new ArrayList<>(results.getScaResults().getPackages());
    Map<String, Package> map = new HashMap<>();
    for (Package p : packages) map.put(p.getId(), p);
    for (Map.Entry<String, List<Finding>> entry : findingsMap.entrySet()) {
        String key = entry.getKey();
        StringBuilder markDownValue = new StringBuilder();
        markDownValue.append(String.format(MARKDOWN_TABLE_FORMAT, "CVE Name", "Description", "Score", "References")).append("\r");
        markDownValue.append(String.format(MARKDOWN_TABLE_FORMAT, "---", "---", "---", "---")).append("\r");
        List<Finding> val = entry.getValue();
        List<String> tags = new ArrayList<>();
        val.forEach(v -> {
            markDownValue.append(String.format(MARKDOWN_TABLE_FORMAT, v.getCveName(), v.getDescription(), v.getScore(), v.getReferences())).append("\r");
            if (!tags.contains(String.valueOf(v.getScore())))
                tags.add(String.valueOf(v.getScore()));
        });
        tags.replaceAll(s -> "CVSS-" + s);
        tags.add("security");
        Rule rule = Rule.builder().id(key).shortDescription(ShortDescription.builder().text(key).build()).fullDescription(FullDescription.builder().text(key).build()).help(Help.builder().markdown(String.valueOf(markDownValue).replace("\n", " ").replace("[", "").replace("]", "")).text(String.valueOf(markDownValue).replace("\n", " ")).build()).properties(Properties.builder().tags(tags).build()).build();
        List<Location> locations = Lists.newArrayList();
        List<String> locationString = Lists.newArrayList();
        map.get(key).getLocations().forEach(k -> {
            if (!locationString.contains(k)) {
                locationString.add(k);
            }
        });
        locations.add(Location.builder().physicalLocation(PhysicalLocation.builder().artifactLocation(ArtifactLocation.builder().uri(locationString.stream().map(String::valueOf).collect(Collectors.joining(","))).build()).build()).build());
        // Build collection of the results -> locations
        scaScanresultList.add(Result.builder().level(properties.getSeverityMap().get(map.get(key).getSeverity()) != null ? properties.getSeverityMap().get(map.get(key).getSeverity().toString()) : DEFAULT_LEVEL).locations(locations).message(Message.builder().text(key).build()).ruleId(key).build());
        scaScanrules.add(rule);
    }
    run.add(SarifVulnerability.builder().tool(Tool.builder().driver(Driver.builder().name(properties.getScaScannerName()).organization(properties.getScaOrganization()).semanticVersion(properties.getSemanticVersion()).rules(scaScanrules).build()).build()).results(scaScanresultList).build());
}
Also used : Finding(com.checkmarx.sdk.dto.sca.report.Finding) Package(com.checkmarx.sdk.dto.sca.report.Package)

Example 2 with Package

use of com.checkmarx.sdk.dto.sca.report.Package in project cx-flow by checkmarx-ltd.

the class GitLabSecurityDashboard method getScaResultsDashboard.

private void getScaResultsDashboard(ScanRequest request, ScanResults results) throws MachinaException {
    List<Vulnerability> vulns = new ArrayList<>();
    Scanner scanner = Scanner.builder().id("Checkmarx-SCA").name("Checkmarx-SCA").build();
    List<Finding> findings = results.getScaResults().getFindings();
    List<Package> packages = new ArrayList<>(results.getScaResults().getPackages());
    Map<String, Package> map = new HashMap<>();
    for (Package p : packages) map.put(p.getId(), p);
    for (Finding finding : findings) {
        // for each finding, get the associated package list.
        // for each object of the associated list, check the occurences of locations
        // if multiple locations exist, construct multiple objects.
        // if only single location exist, construct single object
        Package indPackage = map.get(finding.getPackageId());
        for (String loc : indPackage.getLocations()) {
            vulns.add(Vulnerability.builder().category("dependency_scanning").id(UUID.nameUUIDFromBytes(finding.getPackageId().concat("@").concat(loc).concat(":").concat(finding.getCveName()).getBytes()).toString()).name(finding.getPackageId().concat("@").concat(loc).concat(":").concat(finding.getCveName())).message(finding.getPackageId().concat("@").concat(loc).concat(":").concat(finding.getCveName())).description(finding.getDescription()).severity(String.valueOf(finding.getSeverity())).confidence(String.valueOf(finding.getSeverity())).solution(finding.getFixResolutionText()).location(Location.builder().file(loc).dependency(Dependency.builder().pkg(Name.builder().dependencyname(finding.getPackageId()).build()).version(finding.getPackageId().split("-")[finding.getPackageId().split("-").length - 1]).build()).build()).identifiers(getScaIdentifiers(results.getScaResults(), finding)).scanner(scanner).build());
        }
    }
    SecurityDashboard report = SecurityDashboard.builder().vulnerabilities(vulns).build();
    writeJsonOutput(request, report, log);
}
Also used : Finding(com.checkmarx.sdk.dto.sca.report.Finding) Package(com.checkmarx.sdk.dto.sca.report.Package)

Example 3 with Package

use of com.checkmarx.sdk.dto.sca.report.Package in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class ScaClientHelper method getScanResults.

private SCAResults getScanResults() {
    SCAResults result;
    log.debug("Getting results for scan ID {}", scanId);
    try {
        result = new SCAResults();
        result.setScanId(this.scanId);
        ScaSummaryBaseFormat summaryBaseFormat = getSummaryReport(scanId);
        printSummary(summaryBaseFormat, this.scanId);
        ModelMapper mapper = new ModelMapper();
        Summary summary = mapper.map(summaryBaseFormat, Summary.class);
        Map<Filter.Severity, Integer> findingCountsPerSeverity = getFindingCountMap(summaryBaseFormat);
        summary.setFindingCounts(findingCountsPerSeverity);
        result.setSummary(summary);
        List<Finding> findings = getFindings(scanId);
        result.setFindings(findings);
        List<Package> packages = getPackages(scanId);
        result.setPackages(packages);
        String reportLink = getWebReportLink(config.getScaConfig().getWebAppUrl());
        result.setWebReportLink(reportLink);
        printWebReportLink(result);
        result.setScaResultReady(true);
        String riskReportId = getRiskReportByProjectId(this.projectId);
        List<PolicyEvaluation> policyEvaluationsByReportId = getPolicyEvaluationByReportId(riskReportId);
        List<String> scanViolatedPolicies = getScanViolatedPolicies(policyEvaluationsByReportId);
        result.setPolicyViolated(!scanViolatedPolicies.isEmpty());
        result.setViolatedPolicies(scanViolatedPolicies);
        if (scaProperties.isPreserveXml()) {
            String path = String.format(REPORT_IN_XML_WITH_SCANID, URLEncoder.encode(scanId, ENCODING));
            String xml = httpClient.getRequest(path, ContentType.CONTENT_TYPE_APPLICATION_JSON, String.class, HttpStatus.SC_OK, "CxSCA findings", false);
            xml = xml.trim().replaceFirst("^([\\W]+)<", "<");
            String xml2 = ScanUtils.cleanStringUTF8_2(xml);
            result.setOutput(xml2);
        }
        log.info("Retrieved SCA results successfully.");
    } catch (IOException e) {
        throw new ScannerRuntimeException("Error retrieving CxSCA scan results.", e);
    }
    return result;
}
Also used : Severity(com.checkmarx.sdk.dto.scansummary.Severity) IOException(java.io.IOException) ScannerRuntimeException(com.checkmarx.sdk.exception.ScannerRuntimeException) ModelMapper(org.modelmapper.ModelMapper) Package(com.checkmarx.sdk.dto.sca.report.Package)

Example 4 with Package

use of com.checkmarx.sdk.dto.sca.report.Package in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class ScaClientHelper method getScaPackages.

private List<Package> getScaPackages(PackagesType packagesType, List<Package> packages) {
    List<PackageType> packageTypeList = packagesType.getPackage();
    Package packge = new Package();
    packages = new ArrayList<>();
    List<String> licenses = null;
    for (int count = 0; count < packageTypeList.size(); count++) {
        packge.setId(packageTypeList.get(count).getId());
        packge.setName(packageTypeList.get(count).getName());
        packge.setVersion(packageTypeList.get(count).getVersion());
        packge.setMatchType(packageTypeList.get(count).getMatchType());
        packge.setHighVulnerabilityCount(packageTypeList.get(count).getHighVulnerabilityCount());
        packge.setLowVulnerabilityCount(packageTypeList.get(count).getLowVulnerabilityCount());
        packge.setMediumVulnerabilityCount(packageTypeList.get(count).getMediumVulnerabilityCount());
        packge.setNumberOfVersionsSinceLastUpdate(packageTypeList.get(count).getNumberOfVersionsSinceLastUpdate());
        packge.setNewestVersion(packageTypeList.get(count).getNewestVersion());
        packge.setOutdated(Boolean.parseBoolean(packageTypeList.get(count).getOutdated()));
        packge.setReleaseDate(packageTypeList.get(count).getReleaseDate().toString());
        packge.setRiskScore(packageTypeList.get(count).getRiskScore());
        PackageSeverity severity = scaToScanPackageSeverity(packageTypeList.get(count).getSeverity());
        packge.setSeverity(severity);
        packge.setLocations(packageTypeList.get(count).getLocations().getLocation());
        packge.setPackageRepository(packageTypeList.get(count).getPackageRepository());
        packge.setDirectDependency(Boolean.parseBoolean(packageTypeList.get(count).getIsDirectDependency()));
        packge.setDevelopment(Boolean.parseBoolean(packageTypeList.get(count).getIsDevelopmentDependency()));
        LicensesType licensesType = packageTypeList.get(count).getLicenses();
        licenses = new ArrayList<>();
        for (int licensesTypeCount = 0; licensesTypeCount < licensesType.getLicense().size(); licensesTypeCount++) {
            licenses.add(licensesType.getLicense().get(licensesTypeCount).getContent().toString());
            packge.setLicenses(licenses);
        }
        packages.add(packge);
        packge = new Package();
    }
    return packages;
}
Also used : Package(com.checkmarx.sdk.dto.sca.report.Package)

Example 5 with Package

use of com.checkmarx.sdk.dto.sca.report.Package in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class ScaClientHelper method getScaResults.

private SCAResults getScaResults(RiskReportSummaryType riskReportSummaryType, PackagesType packagesType, VulnerabilitiesType vulnerabilitiesType, LicensesType licensesType, PoliciesType policiesType) {
    SCAResults result;
    ScaSummaryBaseFormat summaryBaseFormat = new ScaSummaryBaseFormat();
    List<Package> packages = null;
    log.debug("Getting results for scan ID {}", scanId);
    try {
        result = new SCAResults();
        result.setScanId(this.scanId);
        summaryBaseFormat = getScaSummaryReport(riskReportSummaryType, summaryBaseFormat);
        printSummary(summaryBaseFormat, this.scanId);
        ModelMapper mapper = new ModelMapper();
        Summary summary = mapper.map(summaryBaseFormat, Summary.class);
        Map<Filter.Severity, Integer> findingCountsPerSeverity = getFindingCountMap(summaryBaseFormat);
        summary.setFindingCounts(findingCountsPerSeverity);
        result.setSummary(summary);
        List<Finding> findings = getScaFindings(vulnerabilitiesType);
        result.setFindings(findings);
        packages = getScaPackages(packagesType, packages);
        result.setPackages(packages);
        String reportLink = getWebReportLink(config.getScaConfig().getWebAppUrl());
        result.setWebReportLink(reportLink);
        printWebReportLink(result);
        result.setScaResultReady(true);
        List<PolicyEvaluation> policyEvaluationsByReport = getScaPolicyEvaluationByReport(policiesType);
        List<String> scanViolatedPolicies = getScanViolatedPolicies(policyEvaluationsByReport);
        result.setPolicyViolated(!scanViolatedPolicies.isEmpty());
        result.setViolatedPolicies(scanViolatedPolicies);
        log.info("Retrieved SCA results successfully.");
    } catch (Exception e) {
        throw new ScannerRuntimeException("Error retrieving CxSCA scan results.", e);
    }
    return result;
}
Also used : Severity(com.checkmarx.sdk.dto.scansummary.Severity) ScannerRuntimeException(com.checkmarx.sdk.exception.ScannerRuntimeException) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) ScannerRuntimeException(com.checkmarx.sdk.exception.ScannerRuntimeException) JAXBException(javax.xml.bind.JAXBException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CxHTTPClientException(com.checkmarx.sdk.exception.CxHTTPClientException) IOException(java.io.IOException) ModelMapper(org.modelmapper.ModelMapper) Package(com.checkmarx.sdk.dto.sca.report.Package)

Aggregations

Package (com.checkmarx.sdk.dto.sca.report.Package)10 Finding (com.checkmarx.sdk.dto.sca.report.Finding)6 ScanResults (com.checkmarx.sdk.dto.ScanResults)3 Severity (com.checkmarx.sdk.dto.scansummary.Severity)2 ScannerRuntimeException (com.checkmarx.sdk.exception.ScannerRuntimeException)2 IOException (java.io.IOException)2 ModelMapper (org.modelmapper.ModelMapper)2 CxScanSummary (com.checkmarx.sdk.dto.cx.CxScanSummary)1 SCAResults (com.checkmarx.sdk.dto.sca.SCAResults)1 Summary (com.checkmarx.sdk.dto.sca.Summary)1 CheckmarxException (com.checkmarx.sdk.exception.CheckmarxException)1 CxHTTPClientException (com.checkmarx.sdk.exception.CxHTTPClientException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 JAXBException (javax.xml.bind.JAXBException)1 NotImplementedException (org.apache.commons.lang3.NotImplementedException)1 JSONObject (org.json.JSONObject)1