فا

‫ Java Secure Coding - Input Validation and Data Sanitization Rules – Part2

IRCAR201310190
Date: 2013-10-21
IDS00-J. Sanitize untrusted data passed across a trust boundary
XML Injection
Because of its platform independence, flexibility, and relative simplicity, the extensible markup language (XML) has found use in applications ranging from remote procedure calls to systematic storage, exchange, and retrieval of data. However, because of its versatility, XML is vulnerable to a wide spectrum of attacks. One such attack is called XML injection.
A user who has the ability to provide structured XML as input can override the contents of an XML document by injecting XML tags in data fields. These tags are interpreted and classified by an XML parser as executable content and, as a result, may cause certain data members to be overridden.
Consider the following XML code snippet from an online store application, designed primarily to query a back-end database. The user has the ability to specify the quantity of an item available for purchase.
<item>
<description>Widget</description>
<price>500.0</price>
<quantity>1</quantity>
</item>
A malicious user might input the following string instead of a simple number in the quantity field.
1</quantity><price>1.0</price><quantity>1
Consequently, the XML resolves to the following block:
<item>
<description>Widget</description>
<price>500.0</price>
<quantity>1</quantity><price>1.0</price><quantity>1</quantity>
</item>
A Simple API for XML (SAX) parser (org.xml.sax and javax.xml.parsers.SAXParser) interprets the XML such that the second price field overrides the first, leaving the price of the item as $1. Even when it is not possible to perform such an attack, the attacker may be able to inject special characters, such as comment blocks and CDATA delimiters, which corrupt the meaning of the XML.
Noncompliant Code Example
In this noncompliant code example, a client method uses simple string concatenation to build an XML query to send to a server. XML injection is possible because the method performs no input validation.
private void createXMLStream(BufferedOutputStream outStream,
String quantity) throws IOException {
String xmlString;
xmlString = "<item>\n<description>Widget</description>\n" +
"<price>500.0</price>\n" +
"<quantity>" + quantity + "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
Compliant Solution (Whitelisting)
Depending on the specific data and command interpreter or parser to which data is being sent, appropriate methods must be used to sanitize untrusted user input. This compliant solution uses whitelisting to sanitize the input. In this compliant solution, the method requires that the quantity field be a number between 0 and 9.
private void createXMLStream(BufferedOutputStream outStream,
String quantity) throws IOException {
// Write XML string if quantity contains numbers only.
// Blacklisting of invalid characters can be performed
// in conjunction.
if (!Pattern.matches("[0-9]+", quantity)) {
// Format violation
}
String xmlString = "<item>\n<description>Widget</description>\n" +
"<price>500</price>\n" +
"<quantity>" + quantity + "</quantity></item>";
outStream.write(xmlString.getBytes());
outStream.flush();
}
Compliant Solution (XML Schema)
A more general mechanism for checking XML for attempted injection is to validate it using a Document Type Definition (DTD) or schema. The schema must be rigidly defined to prevent injections from being mistaken for valid XML. Here is a suitable schema for validating our XML snippet:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
<xs:element name="quantity" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The schema is available as the file schema.xsd. This compliant solution employs this schema to prevent XML injection from succeeding. It also relies on the CustomResolver class to prevent XXE attacks. This class, as well as XXE attacks, are described in the subsequent code examples.
private void createXMLStream(BufferedOutputStream outStream,
String quantity) throws IOException {
String xmlString;
xmlString = "<item>\n<description>Widget</description>\n" +
"<price>500.0</price>\n" +
"<quantity>" + quantity + "</quantity></item>";
InputSource xmlStream = new InputSource(
new StringReader(xmlString)
);
// Build a validating SAX parser using our schema
SchemaFactory sf
= SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
DefaultHandler defHandler = new DefaultHandler() {
public void warning(SAXParseException s)
throws SAXParseException {throw s;}
public void error(SAXParseException s)
throws SAXParseException {throw s;}
public void fatalError(SAXParseException s)
throws SAXParseException {throw s;}
};
StreamSource ss = new StreamSource(new File("schema.xsd"));
try {
Schema schema = sf.newSchema(ss);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser saxParser = spf.newSAXParser();
// To set the custom entity resolver,
// an XML reader needs to be created
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
saxParser.parse(xmlStream, defHandler);
} catch (ParserConfigurationException x) {
throw new IOException("Unable to validate XML", x);
} catch (SAXException x) {
throw new IOException("Invalid quantity", x);
}
// Our XML is valid, proceed
outStream.write(xmlString.getBytes());
outStream.flush();
}
Using a schema or DTD to validate XML is convenient when receiving XML that may have been loaded with unsanitized input. If such an XML string has not yet been built, sanitizing input before constructing XML yields better performance.
XML External Entity Attacks
An XML document can be dynamically constructed from smaller logical blocks called entities. Entities can be internal, external, or parameter-based. External entities allow the inclusion of XML data from external files.
According to XML W3C Recommendation [W3C 2008], section 4.4.3, "Included If Validating":
When an XML processor recognizes a reference to a parsed entity, to validate the document, the processor MUST include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor MAY, but need not, include the entity's replacement text.
An attacker may attempt to cause denial of service or program crashes by manipulating the URI of the entity to refer to special files existing on the local file system, for example, by specifying /dev/random or /dev/tty as input URIs. This may crash or block the program indefinitely. This is called an XML external entity (XXE) attack. Because inclusion of replacement text from an external entity is optional, not all XML processors are vulnerable to external entity attacks.
Noncompliant Code Example
This noncompliant code example attempts to parse the file evil.xml, report any errors, and exit. However, a SAX or a DOM (Document Object Model) parser will attempt to access the URL specified by the SYSTEM attribute, which means it will attempt to read the contents of the local /dev/tty file. On POSIX systems, reading this file causes the program to block until input data is supplied to the machine's console. Consequently, an attacker can use this malicious XML file to cause the program to hang.
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inStream, defaultHandler);
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException {
receiveXMLStream(new FileInputStream("evil.xml"),
new DefaultHandler());
}
}
This program is subject to a remote XXE attack if the evil.xml file contains the following:
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo>
Compliant Solution (EntityResolver)
This compliant solution defines a CustomResolver class that implements the interface org.xml.sax.EntityResolver. This interface enables a SAX application to customize handling of external entities. The setEntityResolver() method registers the instance with the corresponding SAX driver. The customized handler uses a simple whitelist for external entities. The resolveEntity() method returns an empty InputSource when an input fails to resolve to any of the specified, safe entity source paths. Consequently, when parsing malicious input, the empty InputSource returned by the custom resolver causes a java.net.MalformedURLException to be thrown. Note that you must create an XMLReader object on which to set the custom entity resolver.
Following is an example of component-based sanitization:
class CustomResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// Check for known good entities
String entityPath = "/home/username/java/xxe/file";
if (systemId.equals(entityPath)) {
System.out.println("Resolving entity: " + publicId +
" " + systemId);
return new InputSource(entityPath);
} else {
return new InputSource(); // Disallow unknown entities
// by returning a blank path
}
}
}
class XXE {
private static void receiveXMLStream(InputStream inStream,
DefaultHandler defaultHandler)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// To set the entity resolver, an XML reader needs to be created
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(new CustomResolver());
reader.setContentHandler(defaultHandler);
InputSource is = new InputSource(inStream);
reader.parse(is);
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException {
receiveXMLStream(new FileInputStream("evil.xml"),
new DefaultHandler());
}
}
Risk Assessment
Failure to sanitize user input before processing or storing it can result in injection attacks.
Automated Detection

References:

نظرات

بدون نظر
شما برای نظر دادن باید وارد شوید

نوشته

 
تاریخ ایجاد: 18 مرداد 1393

دسته‌ها

امتیاز

امتیاز شما
تعداد امتیازها: 0