...
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.
Code Block | ||
---|---|---|
| ||
private void createXMLStream(BufferedOutputStream outStream, import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OnlineStore { private static void createXMLStreamBad(final BufferedOutputStream outStream, final String quantity) throws IOException { String xmlString; String xmlString = "<item>\n<description>Widget</description>\n" + + "<price>500.0<"<price>500</price>\n" + "<quantity>" + quantity "<quantity>" + quantity + "</quantity></item>"; outStream.write(xmlString.getBytes()); outStream.flush(); } } |
Compliant Solution (Input Validation)
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 validates that quantity
is an unsigned integer.
Code Block | ||
---|---|---|
| ||
private void createXMLStream(BufferedOutputStream outStream, import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OnlineStore { private static void createXMLStream(final BufferedOutputStream outStream, final String quantity) throws IOException, NumberFormatException { // Write XML string only if quantity containsis numbersan only. unsigned // Blacklisting of invalid characters can be performed integer (count). // in conjunction. int count if= (!PatternInteger.matches("[0-9]+", quantity)) { // Format violationparseUnsignedInt(quantity); } String xmlString = "<item>\n<description>Widget</description>\n" + + "<price>500</price>\n" + "<quantity>" + quantitycount + "</quantity></item>"; outStream.write(xmlString.getBytes()); outStream.flush(); } } |
Compliant Solution (XML Schema)
...