Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will prepared statements prevent sql injection attacks?

Consider a hypothetical case where I have to retrieve some details from the database based on the userId and the sample code is given below

private String getpassword(String username) {

PreparedStatement statement = null;
ResultSet resultSet = null;
Connection conn = null;

final String selectQuery = "SELECT password FROM " + "users WHERE username=?";
try {
    conn = dataSource.getConnection();
    statement = conn.prepareStatement(selectQuery);
    statement.setString(1, username);
    resultSet = statement.executeQuery();
    if (resultSet.next()) {
        }

} catch (SQLException e) {
 // log it
}
//return
}

This username is actually coming from the client side and the user can tamper the data (if he wants to). So will preparedStatements prevent from accepting quotes and send only the filtered form of SQL to the database.

For eg: I can provide username= ' or 1=1 and it will be a valid SQL statement. But if the driver escapes the quotes from user inputs, then they would prevent sql injections.

What is the general understanding of the same ?

like image 275
nibin012 Avatar asked Aug 19 '11 11:08

nibin012


People also ask

How can SQL injection attacks be prevented?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is the benefit of using prepared SQL statements?

Prepared statements offer two major benefits: The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query.

Why are prepared statements considered a mitigation strategy for SQL injection attacks?

A prepared statement “sanitizes” the input. This means it makes sure that whatever the user enters is treated as a string literal in SQL and NOT as a part of the SQL query. It may also escape certain characters and detect/remove malicious code.

Why are prepared statements considered a mitigation strategy for SQL injection attacks and not a preventative one?

Prepared statements are resilient against SQL injection, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.


1 Answers

According to this, yes: http://en.wikipedia.org/wiki/SQL_injection

In that case the statement is already compiled and injected code would not be interpreted (and thus not be executed) again.

like image 109
Thomas Avatar answered Oct 12 '22 09:10

Thomas