فا

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

IRCAR201310189
Date: 2013-10-21
IDS00-J. Sanitize untrusted data passed across a trust boundary
Many programs accept untrusted data originating from unvalidated users, network connections, and other untrusted sources and then pass the (modified or unmodified) data across a trust boundary to a different trusted domain. Frequently the data is in the form of a string with some internal syntactic structure, which the subsystem must parse. Such data must be sanitized both because the subsystem may be unprepared to handle the malformed input and because unsanitized input may include an injection attack.
In particular, programs must sanitize all string data that is passed to command interpreters or parsers so that the resulting string is innocuous in the context in which it is parsed or interpreted.
Many command interpreters and parsers provide their own sanitization and validation methods. When available, their use is preferred over custom sanitization techniques because custom-developed sanitization can often neglect special cases or hidden complexities in the parser. Another problem with custom sanitization code is that it may not be adequately maintained when new capabilities are added to the command interpreter or parser software.
SQL Injection
A SQL injection vulnerability arises when the original SQL query can be altered to form an altogether different query. Execution of this altered query may result in information leaks or data modification. The primary means of preventing SQL injection are sanitizing and validating untrusted input and parameterizing queries.
Suppose a database contains user names and passwords used to authenticate users of the system. The user names have a string size limit of 8. The passwords have a size limit of 20.
A SQL command to authenticate a user might take the following form:
SELECT * FROM db_user WHERE username='<USERNAME>' AND
password='<PASSWORD>'
If it returns any records, the user name and password are valid.
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>:
validuser' OR '1'='1
When injected into the command, the command becomes
SELECT * FROM db_user WHERE username='validuser' OR '1'='1' AND password=<PASSWORD>
If validuser is a valid user name, this SELECT statement selects the validuser record in the table. The password is never checked because username='validuser' is true; consequently, the items after the OR are not tested. As long as the components after the OR generate a syntactically correct SQL expression, the attacker is granted the access of validuser.
Likewise, an attacker could supply a string for <PASSWORD> such as
' OR '1'='1
This would yield the following command:
SELECT * FROM db_user WHERE username='' AND password='' OR '1'='1'
This time, the '1'='1' tautology disables both user name and password validation, and the attacker is falsely logged in without a correct login ID or password.
Noncompliant Code Example
This noncompliant code example shows JDBC code to authenticate a user to a system. The password is passed as a char array, the database connection is created, and then the passwords are hashed.
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.
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
}
}
}
}
Compliant Solution (PreparedStatement)
Fortunately, the JDBC library provides an API for building SQL commands that sanitize untrusted data. The java.sql.PreparedStatement class properly escapes input strings, preventing SQL injection when used correctly. This is an example of component-based sanitization.
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.
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
}
}
}
Use the set*() methods of the PreparedStatement class to enforce strong type checking. This technique mitigates the SQL injection vulnerability because the input is properly escaped by automatic entrapment within double quotes. Note that prepared statements must be used even with queries that insert data into the database.

References:

نظرات

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

نوشته

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

دسته‌ها

امتیاز

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