Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring (MVC) SQL injection avoidance?

I am wondering how Spring MVC handles SQL injections (and other security issues: XSS, code [javascript] injection, etc). I'm talking mostly about escaping the values that are added to DBs and such. I can't seem to find any answer because every time I search for spring sql injection results that involve dependency injection arise.

My flow is as follows: from the client browser I make a request consisting of an JSON with some query parameters (not the SQL statement, that would be too stupid - to form the SQL query in JS). When the request reaches the properly annotated method in the Controller, the request is mapped via @RequestBody using Jackson to an "request object". Now this object is sent to the DAO, where using JDBC Template I query the db (and using RowMapper I map the results).

In the DAO I have something like:

public int countAll(RequestObject request) {
    String sql = "SELECT count(*) FROM employees WHERE name = '" + request.getName() + "'";

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    int count = jdbcTemplate.queryForInt(sql);

    return count;
}

Now is this approach safe from SQL injection? Are non-JDBCTemplate -based queries safe given that are flowing through Spring MVC?

Could we have a little discussion on this?

like image 823
BogdanSorlea Avatar asked Dec 12 '11 10:12

BogdanSorlea


People also ask

Does Spring JPA prevent SQL injection?

Note that using JPA or other ORMs without prepared statements with bound parameters won't protect you from an SQL injection.

How SQL injection is avoided?

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.

Does JDBC prevent SQL injection?

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.


1 Answers

Anytime you build a query by concatenation you are vunerlable to injection attacks

pass your parameters correctly:

jdbcTemplate.queryForInt(sql, args, argTypes)

for example:

        JdbcTemplate insert = new JdbcTemplate(dataSource);
    insert.update("INSERT INTO PERSON (FIRSTNAME, LASTNAME) VALUES(?,?)",
            new Object[] { firstName, lastName });
like image 84
Michael W Avatar answered Dec 24 '22 17:12

Michael W