Search in sources :

Example 6 with APIMThreatAnalyzerException

use of org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException in project carbon-apimgt by wso2.

the class JSONAnalyzer method analyze.

/**
 * @param payload json payload
 * @throws APIMThreatAnalyzerException if defined limits for json payload exceeds
 */
@Override
public void analyze(String payload, String apiContext) throws APIMThreatAnalyzerException {
    try (JsonParser parser = factory.createParser(new StringReader(payload))) {
        int currentDepth = 0;
        int currentFieldCount = 0;
        JsonToken token;
        while ((token = parser.nextToken()) != null) {
            switch(token) {
                case START_OBJECT:
                    currentDepth += 1;
                    try {
                        analyzeDepth(maxJsonDepth, currentDepth, apiContext);
                    } catch (APIMThreatAnalyzerException e) {
                        throw e;
                    }
                    break;
                case END_OBJECT:
                    currentDepth -= 1;
                    break;
                case FIELD_NAME:
                    currentFieldCount += 1;
                    String name = parser.getCurrentName();
                    try {
                        analyzeField(name, maxFieldCount, currentFieldCount, maxFieldLength, apiContext);
                    } catch (APIMThreatAnalyzerException e) {
                        throw e;
                    }
                    break;
                case VALUE_STRING:
                    String value = parser.getText();
                    try {
                        analyzeString(value, maxStringLength, apiContext);
                    } catch (APIMThreatAnalyzerException e) {
                        throw e;
                    }
                    break;
                case START_ARRAY:
                    try {
                        analyzeArray(parser, maxArrayElementCount, maxStringLength, apiContext);
                    } catch (APIMThreatAnalyzerException e) {
                        throw e;
                    }
                    break;
            }
        }
    } catch (JsonParseException e) {
        logger.error(JSON_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Payload parsing failed", e);
        throw new APIMThreatAnalyzerException(JSON_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Payload parsing failed", e);
    } catch (IOException e) {
        logger.error(JSON_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Payload build failed", e);
        throw new APIMThreatAnalyzerException(JSON_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Payload build failed", e);
    }
}
Also used : StringReader(java.io.StringReader) JsonToken(com.fasterxml.jackson.core.JsonToken) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.ballerina.threatprotection.APIMThreatAnalyzerException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 7 with APIMThreatAnalyzerException

use of org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException in project carbon-apimgt by wso2.

the class XMLAnalyzer method analyze.

/**
 * @param payload xml payload
 * @throws APIMThreatAnalyzerException
 */
@Override
public void analyze(String payload, String apiContext) throws APIMThreatAnalyzerException {
    Reader reader = null;
    XMLStreamReader xmlStreamReader = null;
    try {
        reader = new StringReader(payload);
        xmlStreamReader = factory.createXMLStreamReader(reader);
        while (xmlStreamReader.hasNext()) {
            int xmlStreamEvent = xmlStreamReader.next();
            // So, we are manually checking attribute length and count
            if (xmlStreamEvent == XMLStreamReader.START_ELEMENT) {
                int currentAttributeCount = xmlStreamReader.getAttributeCount();
                if (currentAttributeCount > config.getMaxAttributeCount()) {
                    throw new APIMThreatAnalyzerException(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - XML Validation Failed: Maximum attribute limit reached.");
                }
                for (int i = 0; i < currentAttributeCount; i++) {
                    String attributeValue = xmlStreamReader.getAttributeValue(i);
                    if (attributeValue.length() > config.getMaxAttributeLength()) {
                        throw new APIMThreatAnalyzerException(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - XML Validation Failed: Maximum attribute length reached.");
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        log.error(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - XML Validation Failed: " + e.getMessage(), e);
        throw new APIMThreatAnalyzerException(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - XML Validation Failed: " + e.getMessage(), e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            log.warn(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Failed to close XMLEventReader", e);
        } catch (IOException e) {
            log.warn(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Failed to close payload StringReader", e);
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) IOException(java.io.IOException) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.ballerina.threatprotection.APIMThreatAnalyzerException)

Example 8 with APIMThreatAnalyzerException

use of org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException in project carbon-apimgt by wso2.

the class JsonSchemaValidator method mediate.

/**
 * This mediate method validates the message body.
 *
 * @param messageContext This message context contains the request message properties of the relevant
 *                       API which was enabled the JSON_Validator message mediation in flow.
 * @return a boolean true if the message content is passed the json schema criteria.
 */
public boolean mediate(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("JSON schema validation mediator is activated...");
    }
    Map<String, InputStream> inputStreams = null;
    org.apache.axis2.context.MessageContext axis2MC;
    String apiContext;
    String requestMethod;
    String contentType;
    Boolean isValid = true;
    axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Object contentTypeObject = axis2MC.getProperty(ThreatProtectorConstants.CONTENT_TYPE);
    if (contentTypeObject != null) {
        contentType = contentTypeObject.toString();
    } else {
        contentType = axis2MC.getProperty(ThreatProtectorConstants.SOAP_CONTENT_TYPE).toString();
    }
    apiContext = messageContext.getProperty(ThreatProtectorConstants.API_CONTEXT).toString();
    requestMethod = axis2MC.getProperty(ThreatProtectorConstants.HTTP_REQUEST_METHOD).toString();
    if (!APIConstants.SupportedHTTPVerbs.GET.name().equalsIgnoreCase(requestMethod) && (ThreatProtectorConstants.APPLICATION_JSON.equals(contentType) || ThreatProtectorConstants.TEXT_JSON.equals(contentType))) {
        JSONConfig jsonConfig = configureSchemaProperties(messageContext);
        ConfigurationHolder.addJsonConfig(jsonConfig);
        APIMThreatAnalyzer apimThreatAnalyzer = AnalyzerHolder.getAnalyzer(contentType);
        try {
            inputStreams = GatewayUtils.cloneRequestMessage(messageContext);
            if (inputStreams != null) {
                InputStream inputStreamJson = inputStreams.get(ThreatProtectorConstants.JSON);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamJson);
                apimThreatAnalyzer.analyze(bufferedInputStream, apiContext);
                isValid = true;
            }
        } catch (APIMThreatAnalyzerException e) {
            String message = "Request is failed due to a JSON schema validation failure: ";
            logger.error(message, e);
            isValid = GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, message + e.getMessage());
        } catch (IOException e) {
            String message = "Error occurred while building the request: ";
            logger.error(message, e);
            isValid = GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, message + e.getMessage());
        } finally {
            // return analyzer to the pool
            AnalyzerHolder.returnObject(apimThreatAnalyzer);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("JSON Schema Validator: " + APIMgtGatewayConstants.REQUEST_TYPE_FAIL_MSG);
        }
    }
    GatewayUtils.setOriginalInputStream(inputStreams, axis2MC);
    if (isValid) {
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException e) {
            isValid = GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, e.getMessage());
        }
    }
    return isValid;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) JSONConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.JSONConfig) APIMThreatAnalyzer(org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)

Example 9 with APIMThreatAnalyzerException

use of org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException in project carbon-apimgt by wso2.

the class XMLAnalyzer method analyze.

/**
 * @param in xml payload
 * @throws APIMThreatAnalyzerException
 */
@Override
public void analyze(InputStream in, String apiContext) throws APIMThreatAnalyzerException {
    Reader reader = null;
    XMLEventReader xmlEventReaderReader = null;
    try {
        reader = new InputStreamReader(in);
        xmlEventReaderReader = factory.createXMLEventReader(reader);
        while (xmlEventReaderReader.hasNext()) {
            xmlEventReaderReader.nextEvent();
        }
    } catch (XMLStreamException e) {
        throw new APIMThreatAnalyzerException("XML Validation Failed: due to " + e.getMessage());
    } finally {
        try {
            if (xmlEventReaderReader != null) {
                xmlEventReaderReader.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            log.warn(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Failed to close XMLEventReader", e);
        } catch (IOException e) {
            log.warn(XML_THREAT_PROTECTION_MSG_PREFIX + apiContext + " - Failed to close payload StringReader", e);
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventReader(javax.xml.stream.XMLEventReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) XMLEventReader(javax.xml.stream.XMLEventReader) IOException(java.io.IOException) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)

Aggregations

IOException (java.io.IOException)8 APIMThreatAnalyzerException (org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)6 XMLStreamException (javax.xml.stream.XMLStreamException)4 JsonToken (com.fasterxml.jackson.core.JsonToken)3 JsonParseException (com.fasterxml.jackson.core.JsonParseException)2 JsonParser (com.fasterxml.jackson.core.JsonParser)2 BufferedInputStream (java.io.BufferedInputStream)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Reader (java.io.Reader)2 StringReader (java.io.StringReader)2 APIMThreatAnalyzerException (org.wso2.carbon.apimgt.ballerina.threatprotection.APIMThreatAnalyzerException)2 APIMThreatAnalyzer (org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer)2 URL (java.net.URL)1 XMLEventReader (javax.xml.stream.XMLEventReader)1 XMLStreamReader (javax.xml.stream.XMLStreamReader)1 Source (javax.xml.transform.Source)1 StreamSource (javax.xml.transform.stream.StreamSource)1 Schema (javax.xml.validation.Schema)1 SchemaFactory (javax.xml.validation.SchemaFactory)1