Search in sources :

Example 1 with InvalidCredentialsException

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

the class CxAuthService method getAuthToken.

/**
 * Get Auth Token
 */
@Override
public String getAuthToken(String username, String password, String clientId, String clientSecret, String scope) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("username", username);
    map.add("password", password);
    map.add("grant_type", "password");
    map.add("scope", cxProperties.getScope());
    map.add("client_id", clientId);
    if (!ScanUtils.empty(cxProperties.getClientSecret())) {
        map.add("client_secret", clientSecret);
    }
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
    try {
        // get the access token
        log.info("Logging into Checkmarx {}", cxProperties.getUrl().concat(LOGIN));
        CxAuthResponse response = restTemplate.postForObject(cxProperties.getUrl().concat(LOGIN), requestEntity, CxAuthResponse.class);
        if (response == null) {
            throw new InvalidCredentialsException();
        }
        token = response.getAccessToken();
        // expire 500 seconds early
        tokenExpires = LocalDateTime.now().plusSeconds(response.getExpiresIn() - 500);
        if (cxProperties.getEnableShardManager()) {
            ShardSession shard = sessionTracker.getShardSession();
            shard.setAccessToken(token);
            shard.setTokenExpires(tokenExpires);
        }
    } catch (NullPointerException | HttpStatusCodeException e) {
        log.error("Error occurred white obtaining Access Token.  Possibly incorrect credentials");
        log.error(ExceptionUtils.getStackTrace(e));
        throw new InvalidCredentialsException();
    }
    return token;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) CxAuthResponse(com.checkmarx.sdk.dto.cx.CxAuthResponse) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) InvalidCredentialsException(com.checkmarx.sdk.exception.InvalidCredentialsException) ShardSession(com.checkmarx.sdk.ShardManager.ShardSession) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 2 with InvalidCredentialsException

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

the class CxService method getReportContent.

/**
 * Retrieve the report by reportId, mapped to ScanResults DTO, applying filtering as requested
 */
@Override
public ScanResults getReportContent(Integer reportId, FilterConfiguration filter) throws CheckmarxException {
    HttpHeaders headers = authClient.createAuthHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    HttpEntity httpEntity = new HttpEntity<>(headers);
    String session = null;
    try {
        /* login to legacy SOAP CX Client to retrieve description */
        session = authClient.getLegacySession();
    } catch (InvalidCredentialsException e) {
        log.error("Error occurring while logging into Legacy SOAP based WebService - issue description will remain blank");
    }
    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);
        List<ScanResults.XIssue> xIssueList = new ArrayList<>();
        CxXMLResultsType cxResults;
        try {
            XMLStreamReader xsr = xif.createXMLStreamReader(xmlStream);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            cxResults = (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();
                cxResults = (CxXMLResultsType) unmarshaller.unmarshal(xsr);
            } else {
                log.error("CX Response for report {} was null", reportId);
                throw new CheckmarxException("CX report was empty (null)");
            }
        }
        ScanResults.ScanResultsBuilder cxScanBuilder = ScanResults.builder();
        cxScanBuilder.projectId(cxResults.getProjectId());
        cxScanBuilder.team(cxResults.getTeam());
        cxScanBuilder.project(cxResults.getProjectName());
        cxScanBuilder.link(cxResults.getDeepLink());
        cxScanBuilder.files(cxResults.getFilesScanned());
        cxScanBuilder.loc(cxResults.getLinesOfCodeScanned());
        cxScanBuilder.scanType(cxResults.getScanType());
        Map<String, Integer> summary = getIssues(filter, session, xIssueList, cxResults);
        cxScanBuilder.xIssues(xIssueList);
        cxScanBuilder.additionalDetails(getAdditionalScanDetails(cxResults));
        CxScanSummary scanSummary = getScanSummaryByScanId(Integer.valueOf(cxResults.getScanId()));
        cxScanBuilder.scanSummary(scanSummary);
        ScanResults results = cxScanBuilder.build();
        // Add the summary map (severity, count)
        results.getAdditionalDetails().put(Constants.SUMMARY_KEY, summary);
        if (cxProperties.getPreserveXml()) {
            results.setOutput(xml);
        }
        return results;
    } 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 while processing scan results for report Id {}".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) ScanResults(com.checkmarx.sdk.dto.ScanResults) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) JAXBContext(javax.xml.bind.JAXBContext) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) UnmarshalException(javax.xml.bind.UnmarshalException) Unmarshaller(javax.xml.bind.Unmarshaller) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JAXBException(javax.xml.bind.JAXBException) XMLStreamException(javax.xml.stream.XMLStreamException) InvalidCredentialsException(com.checkmarx.sdk.exception.InvalidCredentialsException) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 3 with InvalidCredentialsException

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

the class CxService method getReportContent.

/**
 * Parse CX report file, mapped to ScanResults DTO, applying filtering as requested
 */
public ScanResults getReportContent(File file, FilterConfiguration filter) throws CheckmarxException {
    if (file == null) {
        throw new CheckmarxException("File not provided for processing of results");
    }
    String session = null;
    try {
        if (!cxProperties.getOffline()) {
            session = authClient.getLegacySession();
        }
    } catch (InvalidCredentialsException e) {
        log.error("Error occurring while logging into Legacy SOAP based WebService - issue description will remain blank");
    }
    try {
        /* 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);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        List<ScanResults.XIssue> issueList = new ArrayList<>();
        CxXMLResultsType cxResults = (CxXMLResultsType) unmarshaller.unmarshal(file);
        ScanResults.ScanResultsBuilder cxScanBuilder = ScanResults.builder();
        cxScanBuilder.projectId(cxResults.getProjectId());
        cxScanBuilder.team(cxResults.getTeam());
        cxScanBuilder.project(cxResults.getProjectName());
        cxScanBuilder.link(cxResults.getDeepLink());
        cxScanBuilder.files(cxResults.getFilesScanned());
        cxScanBuilder.loc(cxResults.getLinesOfCodeScanned());
        cxScanBuilder.scanType(cxResults.getScanType());
        Map<String, Integer> summary = getIssues(filter, session, issueList, cxResults);
        cxScanBuilder.xIssues(issueList);
        cxScanBuilder.additionalDetails(getAdditionalScanDetails(cxResults));
        ScanResults results = cxScanBuilder.build();
        if (!cxProperties.getOffline() && !ScanUtils.empty(cxResults.getScanId())) {
            CxScanSummary scanSummary = getScanSummaryByScanId(Integer.valueOf(cxResults.getScanId()));
            results.setScanSummary(scanSummary);
        }
        results.getAdditionalDetails().put(Constants.SUMMARY_KEY, summary);
        return results;
    } catch (JAXBException e) {
        log.error(ERROR_WITH_XML_REPORT);
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException(ERROR_PROCESSING_SCAN_RESULTS);
    } catch (NullPointerException e) {
        log.info("Null error");
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException(ERROR_PROCESSING_SCAN_RESULTS);
    }
}
Also used : ScanResults(com.checkmarx.sdk.dto.ScanResults) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) InvalidCredentialsException(com.checkmarx.sdk.exception.InvalidCredentialsException) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 4 with InvalidCredentialsException

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

the class CxAuthService method getSoapAuthToken.

/**
 * Get Auth Token specific to SOAP API Calls
 */
@Override
public String getSoapAuthToken(String username, String password) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    if (cxProperties.getEnableShardManager()) {
        ShardSession shard = sessionTracker.getShardSession();
        username = shard.getUsername();
        password = shard.getPassword();
    }
    map.add("username", username);
    map.add("password", password);
    map.add("grant_type", "password");
    map.add("scope", cxProperties.getSoapScope());
    map.add("client_id", cxProperties.getSoapClientId());
    if (!ScanUtils.empty(cxProperties.getSoapClientSecret())) {
        map.add("client_secret", cxProperties.getSoapClientSecret());
    }
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
    try {
        // get the access token
        log.info("Logging into Checkmarx for SOAP token {}", cxProperties.getUrl().concat(LOGIN));
        CxAuthResponse response = restTemplate.postForObject(cxProperties.getUrl().concat(LOGIN), requestEntity, CxAuthResponse.class);
        if (response == null) {
            throw new InvalidCredentialsException();
        }
        soapToken = response.getAccessToken();
        // expire 500 seconds early
        soapTokenExpires = LocalDateTime.now().plusSeconds(response.getExpiresIn() - 500);
        if (cxProperties.getEnableShardManager()) {
            ShardSession shard = sessionTracker.getShardSession();
            shard.setSoapToken(soapToken);
            shard.setSoapTokenExpires(soapTokenExpires);
        }
    } catch (NullPointerException | HttpStatusCodeException e) {
        log.error("Error occurred white obtaining Access Token.  Possibly incorrect credentials");
        log.error(ExceptionUtils.getStackTrace(e));
        throw new InvalidCredentialsException();
    }
    return soapToken;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) CxAuthResponse(com.checkmarx.sdk.dto.cx.CxAuthResponse) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) ShardSession(com.checkmarx.sdk.ShardManager.ShardSession) InvalidCredentialsException(com.checkmarx.sdk.exception.InvalidCredentialsException) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

InvalidCredentialsException (com.checkmarx.sdk.exception.InvalidCredentialsException)4 HttpStatusCodeException (org.springframework.web.client.HttpStatusCodeException)3 ShardSession (com.checkmarx.sdk.ShardManager.ShardSession)2 ScanResults (com.checkmarx.sdk.dto.ScanResults)2 CxAuthResponse (com.checkmarx.sdk.dto.cx.CxAuthResponse)2 CheckmarxException (com.checkmarx.sdk.exception.CheckmarxException)2 JAXBContext (javax.xml.bind.JAXBContext)2 JAXBException (javax.xml.bind.JAXBException)2 Unmarshaller (javax.xml.bind.Unmarshaller)2 XMLInputFactory (javax.xml.stream.XMLInputFactory)2 HttpEntity (org.springframework.http.HttpEntity)2 HttpHeaders (org.springframework.http.HttpHeaders)2 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)2 MultiValueMap (org.springframework.util.MultiValueMap)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 UnmarshalException (javax.xml.bind.UnmarshalException)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 XMLStreamReader (javax.xml.stream.XMLStreamReader)1