问题
I'm going through Hibernate and I know that you can prevent SQL injection with HQL:
String query1 = "from Obj where id = "+ id;
String query2 = "from Obj where id = :id";
query1
is unsafe while query2
is safe.
How can I achieve safe queries with Criteria? Is this already implemented or do I have to do something else?
Criteria c = session.createCriteria(Obj.class);
c.add(Restrictions.eq("id", 5));
回答1:
I'm going through Hibernate and I know that you can prevent SQL injection with HQL:
It is a very common misconception that ORM solutions, like hibernate, are SQL Injection proof. Hibernate allows the use of "native SQL" and defines a proprietary query language, named, HQL (Hibernate Query Language); the former is prone to SQL Injection and the later is prone to HQL (or ORM) injection. Source: http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-hibernate
How can I achieve safe queries with Criteria?
As far as you latter question is concerned, Criteria API (similar to PreparedStatement) escapes the parameters and won't cause malicious SQL to be executed.
As far as you don't concatenate your application's parameters directly into your query (and make use of Criteria, PreparedStatement), your app is safe.
回答2:
A note about SQL injection:
Since it is the hot topic, I will address it now but discuss in detail later. Hibernate does not grant immunity to SQL Injection, one can misuse the api as they please. There is nothing special about HQL (Hibernates subset of SQL) that makes it any more or less susceptible.
Functions such as createQuery(String query) and createSQLQuery(String query) create a Query object that will be executed when the call to commit() is made. If the query string is tainted you have sql injection. The details of these functions are covered later.
Ref: https://www.owasp.org/index.php/Hibernate
来源:https://stackoverflow.com/questions/31314209/prevent-sql-injection-with-hibernate