简体   繁体   中英

SQL injection prevention with hibernate

I have a existing code where the application generates different sql depend of lot of conditions and execute them via hibernate sessions createSQLQuery(). In here the parameters are concat to the sql string which reside in the java class as normal string replacement. The problem here is now i need to prevent sql injections. So for that i have to use getNamedQuery() and bind the parameters so hibernate will take care of special characters. But the problem is moving the string sql's to xml file is a overhead because conditionally generating sql's. So i decide to manually do the special character validation and append it to the string query and execute as it is now. So then i check the source for PrepareStatement i found, it just throw a exception

byte[] arrayOfByte1 = new byte[0];
try
{
   arrayOfByte1 = CharsToBytes(this.OdbcApi.charSet, arrayOfChar);
}
   catch (UnsupportedEncodingException localUnsupportedEncodingException) {
}

How can i do same kind of encoding in the java class as above for the parameters before concat them with the string query for eliminate sql injections? Or is there any way i can still keep the string sql as it is an append parameters and use hibernate to execute the query?

As far as I can tell, you want to create SQL queries on the fly because the combination of conditions (from the UI, I guess) can be very complicated. That's fine. All you need to control are the parameters that the user supplies. And for that, you can, and should, still use Hibernate's createSqlQuery() . That function understands either ? for positional parameters (numbered from beginning of query string), or :param_name syntax and then you supply named parameters. You don't need to move anything into an xml file.

Section 16.1.7 has examples.

If you need to assemble custom SQL into a query, I've found writing my own criteria classes that includes the custom SQL works well.

You just need to implement the Criterion interface. https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/criterion/Criterion.html

(See also the Hibernate implementation of 'not null': http://www.grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate/3.2.4.sp1/org/hibernate/criterion/NotNullExpression.java?av=f .)

Then you can simply build up each custom query using the normal hibernate criteria API.

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-creating

Sanitising SQL values properly is painful - try really hard to avoid it! ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM