Search in sources :

Example 1 with APIMThreatAnalyzer

use of org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer 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 APIMThreatAnalyzer

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

the class AnalyzerHolder method getAnalyzer.

/**
 * Borrows an object from pools (xml or json) for threat analysis
 *
 * @param contentType Content-Type of the payload
 * @param policyId ID of the API
 * @return Instance of APIMThreatAnalyzer based on content type
 */
public static APIMThreatAnalyzer getAnalyzer(String contentType, String policyId) {
    APIMThreatAnalyzer analyzer = null;
    if (T_TEXT_XML.equalsIgnoreCase(contentType) || T_APPLICATION_XML.equalsIgnoreCase(contentType)) {
        try {
            analyzer = xmlAnalyzerAnalyzerPool.borrowObject();
            // configure per api
            XMLConfig xmlConfig = ConfigurationHolder.getXmlConfig(policyId);
            if (xmlConfig == null) {
                xmlConfig = ConfigurationHolder.getXmlConfig("GLOBAL-XML");
            }
            if (xmlConfig == null) {
                return null;
            }
            analyzer.configure(xmlConfig);
        } catch (Exception e) {
            logger.error("Threat Protection: Failed to create XMLAnalyzer, " + e.getMessage());
        }
    } else if (T_TEXT_JSON.equalsIgnoreCase(contentType) || T_APPLICATION_JSON.equalsIgnoreCase(contentType)) {
        try {
            analyzer = jsonAnalyzerAnalyzerPool.borrowObject();
            // configure per api
            JSONConfig jsonConfig = ConfigurationHolder.getJsonConfig(policyId);
            if (jsonConfig == null) {
                jsonConfig = ConfigurationHolder.getJsonConfig("GLOBAL-JSON");
            }
            if (jsonConfig == null) {
                return null;
            }
            analyzer.configure(jsonConfig);
        } catch (Exception e) {
            logger.error("Threat Protection: Failed to create JSONAnalyzer, " + e.getMessage());
        }
    }
    return analyzer;
}
Also used : XMLConfig(org.wso2.carbon.apimgt.ballerina.threatprotection.configurations.XMLConfig) JSONConfig(org.wso2.carbon.apimgt.ballerina.threatprotection.configurations.JSONConfig) APIMThreatAnalyzer(org.wso2.carbon.apimgt.ballerina.threatprotection.analyzer.APIMThreatAnalyzer)

Example 3 with APIMThreatAnalyzer

use of org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer 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 4 with APIMThreatAnalyzer

use of org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer 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 5 with APIMThreatAnalyzer

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

the class AnalyzerHolder method getAnalyzer.

/**
 * Borrows an object from pools (xml or json) for threat analysis
 *
 * @param contentType Content-Type of the payload
 * @return Instance of APIMThreatAnalyzer based on content type
 */
public static APIMThreatAnalyzer getAnalyzer(String contentType) {
    APIMThreatAnalyzer analyzer = null;
    if (ThreatProtectorConstants.TEXT_XML.equalsIgnoreCase(contentType) || ThreatProtectorConstants.APPLICATION_XML.equalsIgnoreCase(contentType)) {
        try {
            analyzer = xmlAnalyzerAnalyzerPool.borrowObject();
            XMLConfig xmlConfig = ConfigurationHolder.getXmlConfig();
            analyzer.configure(xmlConfig);
        } catch (Exception e) {
            // here apache.commons GenericObjectPool's borrow object method throws generic exception.
            // here log the stacktrace along with the message.
            log.error("Threat Protection: Error occurred while getting an object from the pool.", e);
        }
    } else if (ThreatProtectorConstants.TEXT_JSON.equalsIgnoreCase(contentType) || ThreatProtectorConstants.APPLICATION_JSON.equalsIgnoreCase(contentType)) {
        try {
            analyzer = jsonAnalyzerAnalyzerPool.borrowObject();
            JSONConfig jsonConfig = ConfigurationHolder.getJsonConfig();
            analyzer.configure(jsonConfig);
        } catch (Exception e) {
            log.error("Threat Protection: Error occurred while getting an object from the pool.", e);
        }
    }
    return analyzer;
}
Also used : XMLConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.XMLConfig) JSONConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.JSONConfig) APIMThreatAnalyzer(org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer)

Aggregations

APIMThreatAnalyzer (org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer)3 BufferedInputStream (java.io.BufferedInputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 APIMThreatAnalyzer (org.wso2.carbon.apimgt.ballerina.threatprotection.analyzer.APIMThreatAnalyzer)2 APIMThreatAnalyzerException (org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)2 JSONConfig (org.wso2.carbon.apimgt.gateway.threatprotection.configuration.JSONConfig)2 XMLConfig (org.wso2.carbon.apimgt.gateway.threatprotection.configuration.XMLConfig)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 BBoolean (org.ballerinalang.model.values.BBoolean)1 BString (org.ballerinalang.model.values.BString)1 JSONConfig (org.wso2.carbon.apimgt.ballerina.threatprotection.configurations.JSONConfig)1 XMLConfig (org.wso2.carbon.apimgt.ballerina.threatprotection.configurations.XMLConfig)1