...
A SQL command to authenticate a user might take the form:
Code Block |
---|
SELECT * FROM db_user WHERE username='<USERNAME>' AND
password='<PASSWORD>'
|
...
However, if an attacker can substitute arbitrary strings for <USERNAME>
and <PASSWORD>
, they can perform a SQL injection by using the following string for <USERNAME>
:
Code Block |
---|
validuser' OR '1'='1
|
When injected into the command, the command becomes:
Code Block |
---|
SELECT * FROM db_user WHERE username='validuser' OR '1'='1' AND password=<PASSWORD>
|
...
Likewise, an attacker could supply a string for <PASSWORD>
such as:
Code Block |
---|
' OR '1'='1
|
This would yield the following command:
Code Block |
---|
SELECT * FROM db_user WHERE username='' AND password='' OR '1'='1'
|
...
Unfortunately, this code example permits a SQL injection attack because the SQL statement sqlString
accepts unsanitized input arguments. The attack scenario outlined previously would work as described.
Code Block | ||
---|---|---|
| ||
class Login {
public Connection getConnection() throws SQLException {
DriverManager.registerDriver(new
com.microsoft.sqlserver.jdbc.SQLServerDriver());
String dbConnection =
PropertyManager.getProperty("db.connection");
// can hold some value like
// "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
return DriverManager.getConnection(dbConnection);
}
String hashPassword(char[] password) {
// create hash of password
}
public void doPrivilegedAction(String username, char[] password)
throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// handle error
}
try {
String pwd = hashPassword(password);
String sqlString = "SELECT * FROM db_user WHERE username = '"
+ username +
"' AND password = '" + pwd + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sqlString);
if (!rs.next()) {
throw new SecurityException(
"User name or password incorrect"
);
}
// Authenticated; proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// forward to handler
}
}
}
}
|
...
This compliant solution modifies the doPrivilegedAction()
method to use a PreparedStatement
instead of java.sql.Statement
. This code also validates the length of the username
argument, preventing an attacker from submitting an arbitrarily long user name.
Code Block | ||
---|---|---|
| ||
public void doPrivilegedAction(
String username, char[] password
) throws SQLException {
Connection connection = getConnection();
if (connection == null) {
// Handle error
}
try {
String pwd = hashPassword(password);
// Ensure that the length of user name is legitimate
if (username.length() > 8) {
// Handle error
}
String sqlString =
"select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
throw new SecurityException("User name or password incorrect");
}
// Authenticated, proceed
} finally {
try {
connection.close();
} catch (SQLException x) {
// forward to handler
}
}
}
|
...
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.
Code Block |
---|
<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.
Code Block |
---|
1</quantity><price>1.0</price><quantity>1
|
Consequently, the XML resolves to the following block:
Code Block |
---|
<item>
<description>Widget</description>
<price>500.0</price>
<quantity>1</quantity><price>1.0</price><quantity>1</quantity>
</item>
|
...
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,
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();
}
|
...
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 must be a number between 0 and 9.
Code Block | ||
---|---|---|
| ||
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();
}
|
...
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:
Code Block |
---|
<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.
Code Block | ||
---|---|---|
| ||
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();
}
|
...
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.
Code Block | ||
---|---|---|
| ||
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:
Code Block | ||
---|---|---|
| ||
<?xml version="1.0"?>
<!DOCTYPE foo SYSTEM "file:/dev/tty">
<foo>bar</foo>
|
...
This is an example of component-based sanitization.
Code Block | ||
---|---|---|
| ||
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());
}
}
|
...
CERT Perl Secure Coding Standard | IDS33-PL. Sanitize untrusted data passed across a trust boundary |
Injection [RST] | |
CWE-116. Improper encoding or escaping of output |
...
| |
| |
[W3C 2008] | 4.4.3, Included If Validating |