4

I'm Using Struts2 Framework and Hibernate, I'm Enhancing a System that I didn't started, I enhanced some features of the system and implement it on the prod. But when they scan it using Acunetix, Somewhere in Login Module, there are some threats(alerts) that are detected in the System wherein the alert says:

Alert: SQL injection

Severity: High

Description: This script is possibly vulnerable to SQL Injection attacks.

Recommendation: Your script should filter metacharacters from user input. Check detailed information for more information about fixing this vulnerability.

And then, I checked the Script that would be the fault on that alert. The Old Developer uses Hibernate to create a query.

List<UserBean> users = session.createQuery("from UserBean where username =?")
    .setParameter(0,username)
    .list();

My Question is:

-Is this Query using Hibernate can't Avoid SQL Injection?

-Is .setParameter should be .setString to be more specific to avoid SQL Injection?

or None of the Above ?

Thanks for the time.

Roman C
  • 49,761
  • 33
  • 66
  • 176
msagala25
  • 1,806
  • 2
  • 17
  • 24

1 Answers1

7

If you use the Hibernate query parameter binding like this you are safe from SQL injection attacks.

In opposite to string concatenation, setParameter will fill the placeholders of the query after creating the prepared statement and before execution of the query, and the query processing engine knows which (probably malicious) chars should be escaped.

This is the common way to go.

setString is the non-generic pendant to setParameter. setParameter detects the datatype automatically.

A small improvement would be to use named parameter binding, e.g.:

List<UserBean> users = session.createQuery("from UserBean where username = :username")
.setParameter("username", username)
.list();

This way you will not get more problems with more parameters in the future.

Kevin Peters
  • 3,314
  • 1
  • 17
  • 38
  • 1
    That explains a lot for me, But why It is alerting that it is prone in SQL Injection even if I bind it by names.? – msagala25 Apr 17 '17 at 08:30
  • I don't know the Acunetix tool at all, you have to ask an expert in this topic about why the report does say that. Maybe it's just because the tool does not find any code which is validating your inputs and it does not know about Hibernate or how prepared statements work. – Kevin Peters Apr 17 '17 at 08:40
  • Why is sql injection not possible in setParameter("username", username) ? Someone can pass in a malicious sql as username, then what happens? – Kumar Manish May 14 '22 at 20:36