Ready-made statements prevent SQL injection attacks?

Consider a hypothetical case where I need to get some data from a database based on userId, and an example 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 actually happens on the client side, and the user can change the data (if he wants). In this way, prepared states prevent quotation marks and send only the filtered SQL form to the database.

For example, I can specify username = 'or 1 = 1, and this will be a valid SQL statement. But if the driver escapes quotes from user inputs, then they will prevent sql injections.

What is the general understanding of the same?

+5
source share
3

SQL-, " 1 = 1" . , - , , HTML ,

, -:

Hello, ${username}

<script>alert('I could have been more malicious')</script>

XSS CSRF.

N.B.

Hello, ${fn:escapeXml(username)}

(JSP-).

:

+3

The username and query will be sent to the database as two separate things, and the database engine will be responsible for combining the two elements. The request has already been compiled by the engine by the time the parameter is read, so these two are never considered part of the same operator.

0
source

All Articles