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));
}
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);
}
}
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);
}
}
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;
}
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;
}
Aggregations