Search in sources :

Example 46 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method updateProjectDetails.

/**
 * Update name and/or owning team for a project
 */
public void updateProjectDetails(CxProject cxProject) throws CheckmarxException {
    String strJSON = "{'name':'%s','owningTeam':'%s'}";
    strJSON = String.format(strJSON, cxProject.getName(), cxProject.getTeamId());
    HttpEntity requestEntity = new HttpEntity<>(strJSON, authClient.createAuthHeaders());
    try {
        log.info("Updating details for project {} with id {}", cxProject.getName(), cxProject.getId());
        restTemplate.exchange(cxProperties.getUrl().concat(PROJECT), HttpMethod.PATCH, requestEntity, String.class, cxProject.getId());
    } catch (HttpStatusCodeException e) {
        log.debug(ExceptionUtils.getStackTrace(e));
        log.error("Error occurred while updating details for project {}.", cxProject.getName());
        throw new CheckmarxException("Error occurred while updating project details: " + e.getLocalizedMessage());
    }
}
Also used : CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException)

Example 47 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method getXmlReportContent.

/**
 * Retrieve the report by reportId, mapped to ScanResults DTO, applying filtering as requested
 */
@Override
public CxXMLResultsType getXmlReportContent(Integer reportId) throws CheckmarxException {
    HttpHeaders headers = authClient.createAuthHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    HttpEntity httpEntity = new HttpEntity<>(headers);
    log.info("Retrieving report contents of report Id {} in XML format", reportId);
    try {
        ResponseEntity<String> resultsXML = restTemplate.exchange(cxProperties.getUrl().concat(REPORT_DOWNLOAD), HttpMethod.GET, httpEntity, String.class, reportId);
        String xml = resultsXML.getBody();
        log.debug(REPORT_LENGTH_MESSAGE, xml.length());
        log.debug("Headers: {}", resultsXML.getHeaders().toSingleValueMap());
        log.info("Report downloaded for report Id {}", reportId);
        /*Remove any chars before the start xml tag*/
        xml = xml.trim().replaceFirst("^([\\W]+)<", "<");
        log.debug(REPORT_LENGTH_MESSAGE, xml.length());
        String xml2 = ScanUtils.cleanStringUTF8_2(xml);
        log.trace("XML2: {}", xml2);
        InputStream xmlStream = new ByteArrayInputStream(Objects.requireNonNull(xml2.getBytes()));
        /* protect against XXE */
        JAXBContext jc = JAXBContext.newInstance(CxXMLResultsType.class);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
        try {
            XMLStreamReader xsr = xif.createXMLStreamReader(xmlStream);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            return (CxXMLResultsType) unmarshaller.unmarshal(xsr);
        } catch (UnmarshalException e) {
            log.warn("Issue occurred performing unmashall step - trying again {}", ExceptionUtils.getMessage(e));
            if (resultsXML.getBody() != null) {
                log.error("Writing raw response from CX to {}", "CX_".concat(String.valueOf(reportId)));
                ScanUtils.writeByte("CX_".concat(String.valueOf(reportId)), resultsXML.getBody().getBytes());
                xml2 = ScanUtils.cleanStringUTF8(xml);
                xmlStream = new ByteArrayInputStream(Objects.requireNonNull(xml2.getBytes()));
                XMLStreamReader xsr = xif.createXMLStreamReader(xmlStream);
                Unmarshaller unmarshaller = jc.createUnmarshaller();
                return (CxXMLResultsType) unmarshaller.unmarshal(xsr);
            } else {
                log.error("CX Response for report {} was null", reportId);
                throw new CheckmarxException("CX report was empty (null)");
            }
        }
    } catch (HttpStatusCodeException e) {
        log.error("HTTP Status Code of {} while getting downloading report contents of report Id {}", e.getStatusCode(), reportId);
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException(ERROR_PROCESSING_RESULTS.concat(reportId.toString()));
    } catch (XMLStreamException | JAXBException e) {
        log.error(ERROR_WITH_XML_REPORT);
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException(ERROR_PROCESSING_RESULTS.concat(reportId.toString()));
    } catch (NullPointerException e) {
        log.info("Null Error");
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException(ERROR_PROCESSING_RESULTS.concat(reportId.toString()));
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) UnmarshalException(javax.xml.bind.UnmarshalException) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 48 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method createScanAndReport.

/**
 * @param params attributes used to define the project
 * @param comment
 * @param filters filters to apply to the scan result set (severity, category, cwe)
 * @throws CheckmarxException
 */
@Override
public ScanResults createScanAndReport(CxScanParams params, String comment, FilterConfiguration filters) throws CheckmarxException {
    Integer scanId = createScan(params, comment);
    waitForScanCompletion(scanId);
    try {
        Integer reportId = createScanReport(scanId);
        waitForReportCreateOrFail(reportId);
        Thread.sleep(cxProperties.getScanPolling());
        return getReportContent(reportId, filters);
    } catch (InterruptedException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        Thread.currentThread().interrupt();
        throw new CheckmarxException(INTERRUPTED_EXCEPTION_MESSAGE);
    }
}
Also used : CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException)

Example 49 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class GoScanner method createScan.

@Override
public Integer createScan(CxScanParams params, String comment) throws CheckmarxException {
    // 
    try {
        String appID = params.getTeamId();
        Integer projectID = getProjectId(appID, params.getProjectName());
        if (projectID.equals(UNKNOWN_INT)) {
            projectID = Integer.parseInt(createCxGoProject(appID, params.getProjectName(), params.getScanPreset()));
        }
        params.setProjectId(projectID);
        // / Create the scan
        CreateScan scan = CreateScan.builder().projectId(params.getProjectId()).engineTypes(cxGoProperties.getEngineTypes()).build();
        log.info("Sending scan to CxGo for projectID {}.", params.getProjectId());
        HttpHeaders headers = authClient.createAuthHeaders(params.getClientSecret());
        HttpEntity<CreateScan> httpEntity = new HttpEntity<>(scan, headers);
        ResponseEntity<CreateScanResponse> createResp = restTemplate.exchange(cxGoProperties.getUrl().concat(CREATE_SCAN), HttpMethod.POST, httpEntity, CreateScanResponse.class);
        CreateScanResponse scanCreate = createResp.getBody();
        assert scanCreate != null;
        Integer scanId = scanCreate.getScan().getId();
        log.info("CxGo started scan with scanId {}.", scanId);
        // /The repo to be scanned is uploaded to amazon bucket
        log.info("CxGo Uploading Scan file {}.", scanId);
        File archive;
        if (params.getSourceType() == CxScanParams.Type.FILE) {
            archive = new File(params.getFilePath());
        } else {
            archive = new File(cxRepoFileHelper.prepareRepoFile(params));
        }
        uploadScanFile(scanCreate.getStorage(), archive);
        FileSystemUtils.deleteRecursively(archive);
        return scanId;
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        log.error("Http Exception: {}", ExceptionUtils.getRootCauseMessage(e), e);
        throw new CheckmarxException("Http error occurred");
    } catch (NullPointerException e) {
        log.error("Null Exception: {}", ExceptionUtils.getRootCauseMessage(e), e);
        throw new CheckmarxException("NullPointerException occurred");
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) File(java.io.File)

Example 50 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class GoScanner method uploadScanFile.

/**
 * Upload Source to pre-signed URL
 *
 * @param scanStorage Response Object from CxGo for S3 details
 * @param file File to upload
 */
private void uploadScanFile(Storage scanStorage, File file) throws CheckmarxException {
    try {
        Fields scanFields = scanStorage.getFields();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("key", scanFields.getKey());
        body.add("bucket", scanFields.getBucket());
        body.add("X-Amz-Algorithm", scanFields.getXAmzAlgorithm());
        body.add("X-Amz-Credential", scanFields.getXAmzCredential());
        body.add("X-Amz-Date", scanFields.getXAmzDate());
        body.add("X-Amz-Security-Token", scanFields.getXAmzSecurityToken());
        body.add("Policy", scanFields.getPolicy());
        body.add("X-Amz-Signature", scanFields.getXAmzSignature());
        FileSystemResource fsr = new FileSystemResource(file);
        body.add("file", fsr);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        restTemplate.exchange(scanStorage.getUrl(), HttpMethod.POST, requestEntity, String.class);
    } catch (HttpClientErrorException e) {
        log.error("CxGo error uploading file.", e);
        throw new CheckmarxException("Error Uploading Source to ".concat(scanStorage.getUrl()));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) JSONObject(org.json.JSONObject) FileSystemResource(org.springframework.core.io.FileSystemResource) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

CheckmarxException (com.checkmarx.sdk.exception.CheckmarxException)62 HttpStatusCodeException (org.springframework.web.client.HttpStatusCodeException)23 ScanResults (com.checkmarx.sdk.dto.ScanResults)11 HttpEntity (org.springframework.http.HttpEntity)10 MachinaException (com.checkmarx.flow.exception.MachinaException)8 Test (org.junit.Test)7 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)7 File (java.io.File)6 JSONObject (org.json.JSONObject)6 CxProject (com.checkmarx.sdk.dto.cx.CxProject)5 CxScanParams (com.checkmarx.sdk.dto.cx.CxScanParams)4 IOException (java.io.IOException)4 JAXBContext (javax.xml.bind.JAXBContext)4 JAXBException (javax.xml.bind.JAXBException)4 Unmarshaller (javax.xml.bind.Unmarshaller)4 XMLInputFactory (javax.xml.stream.XMLInputFactory)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)3 SoapActionCallback (org.springframework.ws.soap.client.core.SoapActionCallback)3 ScanReport (com.checkmarx.flow.dto.report.ScanReport)2