FlawOpen

flawopen.com/SQL Injection in C#/NHibernate

Is NHibernate safe from SQL injection?

Reference guide
Short answer

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.

UNSAFE
var hql =
  $"from User u where u.Id = {userId}";
var user = session.CreateQuery(hql)
  .UniqueResult<User>();
SAFE
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

Does parameterizing HQL also authorize access to a record?

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

See also SQL Injection (CWE-89): How It Works and How to Prevent It in Every Language — flawopen.com MongoDB NoSQL Injection: Safe Query Filters Why String Formatting Risks Numeric ID Queries What Is a Parameterized Query? Is Prisma $queryRaw Safe from SQL Injection? Is Rails where() String Interpolation Safe? Is Sequelize query() Safe from SQL Injection?