flawopen.com/SQL Injection in C#/NHibernate
Is NHibernate safe from SQL injection?
A bound parameter is like a sealed value card placed into a query form: the database treats it as data, not as query instructions. NHibernate HQL parameters provide that boundary for values. Interpolating untrusted text into HQL or SQL puts it back into the query language.
var hql =
$"from User u where u.Id = {userId}";
var user = session.CreateQuery(hql)
.UniqueResult<User>();
var user = session.CreateQuery(
"from User u where u.Id = :id")
.SetParameter("id", userId)
.UniqueResult<User>();
Bind values; constrain query structure
SetParameter() sends the value separately from the HQL text. Use named or positional parameters for every untrusted value. Native SQL queries also support named and positional parameters; use the matching ISQLQuery binding method (for example, SetString() for string values). Parameters do not represent entity names, property names, sort directions, or arbitrary query fragments; those are query structure. If a feature needs a user-selectable property, map the choice to a fixed set of application-owned HQL fragments. Parameterization prevents value-to-query-syntax confusion, but it does not decide whether the user is authorized to see or change the selected records.
FAQ
No. Parameter binding protects query syntax from data values; authorization must still scope the query to records the current user may access, such as by filtering on the authenticated account or tenant.
References
- NHibernate Reference — HQL: The Hibernate Query Language
- NHibernate Reference — Native SQL
- OWASP — SQL Injection Prevention Cheat Sheet
- flawopen.com — SQL Injection in C#