Prevent SQL injection with Hibernate

≡放荡痞女 提交于 2020-05-16 20:34:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!