Search in sources :

Example 1 with APIMThreatAnalyzerException

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

the class Analyze method execute.

@Override
public BValue[] execute(Context context) {
    String payloadType = getStringArgument(context, 0);
    String payload = getStringArgument(context, 1);
    String apiContext = getStringArgument(context, 2);
    String policyId = getStringArgument(context, 3);
    APIMThreatAnalyzer analyzer = AnalyzerHolder.getAnalyzer(payloadType, policyId);
    if (analyzer == null) {
        return getBValues(new BBoolean(false), new BString("Unknown Payload Type"));
    }
    boolean noThreatsDetected = true;
    String errMessage = null;
    try {
        analyzer.analyze(payload, apiContext);
    } catch (APIMThreatAnalyzerException e) {
        noThreatsDetected = false;
        errMessage = e.getMessage();
    }
    AnalyzerHolder.returnObject(analyzer);
    return getBValues(new BBoolean(noThreatsDetected), new BString(errMessage));
}
Also used : BString(org.ballerinalang.model.values.BString) BBoolean(org.ballerinalang.model.values.BBoolean) BString(org.ballerinalang.model.values.BString) APIMThreatAnalyzer(org.wso2.carbon.apimgt.ballerina.threatprotection.analyzer.APIMThreatAnalyzer)

Example 2 with APIMThreatAnalyzerException

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

the class JSONAnalyzer method analyze.

/**
 * Analyze the JSON payload against limitations.
 * @param in input stream of the request payload.
 * @param apiContext request api context.
 * @throws APIMThreatAnalyzerException if defined limits for json payload exceeds
 */
@Override
public void analyze(InputStream in, String apiContext) throws APIMThreatAnalyzerException {
    try (JsonParser parser = factory.createParser(new InputStreamReader(in))) {
        int currentDepth = 0;
        int currentFieldCount = 0;
        JsonToken token;
        while ((token = parser.nextToken()) != null) {
            switch(token) {
                case START_OBJECT:
                    currentDepth += 1;
                    analyzeDepth(maxJsonDepth, currentDepth, apiContext);
                    break;
                case END_OBJECT:
                    currentDepth -= 1;
                    break;
                case FIELD_NAME:
                    currentFieldCount += 1;
                    String name = parser.getCurrentName();
                    analyzeField(name, maxFieldCount, currentFieldCount, maxFieldLength);
                    break;
                case VALUE_STRING:
                    String value = parser.getText();
                    analyzeString(value, maxStringLength);
                    break;
                case START_ARRAY:
                    analyzeArray(parser, maxArrayElementCount, maxStringLength);
            }
        }
    } catch (JsonParseException e) {
        throw new APIMThreatAnalyzerException("Error occurred while parsing the JSON payload", e);
    } catch (IOException e) {
        throw new APIMThreatAnalyzerException("Error occurred while reading the JSON payload.", e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) JsonToken(com.fasterxml.jackson.core.JsonToken) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 3 with APIMThreatAnalyzerException

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

the class JSONAnalyzer method analyzeArray.

/**
 * Analyzes json arrays using defined limits
 *
 * @param parser               JsonParser instance (Current token should be at JsonToken.START_ARRAY state)
 * @param maxArrayElementCount maximum array element count allowed
 * @param maxStringLength      maximum string length allowed
 * @throws APIMThreatAnalyzerException if array/string length is greater than maximum values provided
 */
private void analyzeArray(JsonParser parser, int maxArrayElementCount, int maxStringLength) throws APIMThreatAnalyzerException {
    JsonToken token;
    try {
        int arrayElementCount = 0;
        while ((token = parser.nextToken()) != JsonToken.END_ARRAY) {
            // analyzing string values inside the array
            if (token == JsonToken.VALUE_STRING) {
                String value = parser.getText();
                analyzeString(value, maxStringLength);
            }
            arrayElementCount += 1;
            if (arrayElementCount > maxArrayElementCount) {
                throw new APIMThreatAnalyzerException(" Max Array Length [" + maxArrayElementCount + "] Reached");
            }
        }
    } catch (IOException e) {
        throw new APIMThreatAnalyzerException("Array Parsing Error", e);
    }
}
Also used : JsonToken(com.fasterxml.jackson.core.JsonToken) IOException(java.io.IOException) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)

Example 4 with APIMThreatAnalyzerException

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

the class XMLSchemaValidator method mediate.

/**
 * This mediate method validates the xml request message.
 *
 * @param messageContext This message context contains the request message properties of the relevant
 *                       API which was enabled the XML_Validator message mediation in flow.
 * @return A boolean value.True if successful and false if not.
 */
public boolean mediate(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("XML validation mediator is activated...");
    }
    InputStream inputStreamSchema;
    InputStream inputStreamXml;
    Map<String, InputStream> inputStreams = null;
    Boolean xmlValidationStatus;
    Boolean schemaValidationStatus;
    APIMThreatAnalyzer apimThreatAnalyzer = null;
    String apiContext;
    String requestMethod;
    String contentType;
    boolean validRequest = true;
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    requestMethod = axis2MC.getProperty(ThreatProtectorConstants.HTTP_REQUEST_METHOD).toString();
    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();
    if (!APIConstants.SupportedHTTPVerbs.GET.name().equalsIgnoreCase(requestMethod) && (ThreatProtectorConstants.APPLICATION_XML.equals(contentType) || ThreatProtectorConstants.TEXT_XML.equals(contentType))) {
        try {
            inputStreams = GatewayUtils.cloneRequestMessage(messageContext);
            if (inputStreams != null) {
                Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XML_VALIDATION);
                if (messageProperty != null) {
                    xmlValidationStatus = Boolean.valueOf(messageProperty.toString());
                    if (xmlValidationStatus.equals(true)) {
                        XMLConfig xmlConfig = configureSchemaProperties(messageContext);
                        ConfigurationHolder.addXmlConfig(xmlConfig);
                        apimThreatAnalyzer = AnalyzerHolder.getAnalyzer(contentType);
                        inputStreamXml = inputStreams.get(ThreatProtectorConstants.XML);
                        apimThreatAnalyzer.analyze(inputStreamXml, apiContext);
                    }
                }
                messageProperty = messageContext.getProperty(APIMgtGatewayConstants.SCHEMA_VALIDATION);
                if (messageProperty != null) {
                    schemaValidationStatus = Boolean.valueOf(messageProperty.toString());
                    if (schemaValidationStatus.equals(true)) {
                        inputStreamSchema = inputStreams.get(ThreatProtectorConstants.SCHEMA);
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamSchema);
                        validateSchema(messageContext, bufferedInputStream);
                    }
                }
            }
        } catch (APIMThreatAnalyzerException e) {
            validRequest = false;
            logger.error(APIMgtGatewayConstants.BAD_REQUEST, e);
            GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, e.getMessage());
        } catch (IOException e) {
            logger.error(APIMgtGatewayConstants.BAD_REQUEST, e);
            GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, e.getMessage());
        }
        // return analyzer to the pool
        AnalyzerHolder.returnObject(apimThreatAnalyzer);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("XML Schema Validator: " + APIMgtGatewayConstants.REQUEST_TYPE_FAIL_MSG);
        }
    }
    GatewayUtils.setOriginalInputStream(inputStreams, axis2MC);
    if (validRequest) {
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException e) {
            logger.error("Error occurred while parsing the payload.", e);
            GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, e.getMessage());
        }
    }
    return true;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) XMLConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.XMLConfig) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) APIMThreatAnalyzer(org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 5 with APIMThreatAnalyzerException

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

the class XMLSchemaValidator method validateSchema.

/**
 * This method validates the request payload xml with the relevant xsd.
 *
 * @param messageContext      This message context contains the request message properties of the relevant
 *                            API which was enabled the XML_Validator message mediation in flow.
 * @param bufferedInputStream Buffered input stream to be validated.
 * @throws APIMThreatAnalyzerException Exception might be occurred while parsing the xml payload.
 */
private boolean validateSchema(MessageContext messageContext, BufferedInputStream bufferedInputStream) throws APIMThreatAnalyzerException {
    String xsdURL;
    Schema schema;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XSD_URL);
        if (messageProperty == null) {
            return true;
        } else {
            if (String.valueOf(messageProperty).isEmpty()) {
                return true;
            } else {
                xsdURL = String.valueOf(messageProperty);
                URL schemaFile = new URL(xsdURL);
                schema = schemaFactory.newSchema(schemaFile);
                Source xmlFile = new StreamSource(bufferedInputStream);
                Validator validator = schema.newValidator();
                validator.validate(xmlFile);
            }
        }
    } catch (SAXException | IOException e) {
        throw new APIMThreatAnalyzerException("Error occurred while parsing XML payload : " + e);
    }
    return true;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) URL(java.net.URL) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Validator(javax.xml.validation.Validator) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException) SAXException(org.xml.sax.SAXException)

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