How is SQL injection typically stopped in a Spring/Hibernate setup
Solution 1
SQL injection should not be a risk when you're using Hibernate - as long as you're using it properly.
Hibernate queries are either written in HQL (Hibernate's SQL-like query language) or implemented using object-oriented Criteria API.
HQL is the most common and most recommended. Typically you would write an HQL query like this:
Subscription sub = (Subscription) sessionFactory.getCurrentSession()
.createQuery("from Subscription sub where sub.verification = :verification")
.setString("verification", verification)
.uniqueResult();
In this form you are protected from SQL injection, because Hibernate passes in the string as a parameter; it cannot be interpreted as part of the SQL.
However if you behave badly an write a query like this...
Subscription sub = (Subscription) sessionFactory.getCurrentSession()
.createQuery("from Subscription sub where sub.verification = '" + verification + "'")
.uniqueResult();
...then you're not protected from SQL injection. However you should never be writing queries like this! I don't think any framework would protect you if you append strings to your queries.
Finally, if you use the Hibernate Criteria API you are automatically protected from SQL injection; because Hibernate builds the underlying query when you're using the Criteria API it does so in a way that prevents SQL injection.
Solution 2
I think you've answered your own question - if you're only using HQL as a last resort, then that probably cuts out 95% of potential attack points. And, because you're only using it in those tricky edge cases you're likely to be paying more attention to what you're actually doing.
Matthew Stopa
Updated on July 09, 2022Comments
-
Matthew Stopa almost 2 years
I hate the Ruby language because it's not statically typed but the more time I spend with Spring/Hibernate I appreciate more of Ruby on Rails' features. Specifically the fact that their Active Record model prevents SQL injection for you. How is this issue typically handled with a Spring/Hibernate stack? Does either one come with a scrubbing toolkit of some sort, to make sure your user input is safe?
This isn't much of an issue on an insert if you are just inserting DAO's, but it's a major issue when using Select statements.