Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid injection for sorting query by runtime value

This is a common problem when the query allows you to sort a column by passed-in arguments. Below is what I am trying with ColdFusion ORM. I know that doing this will add a security loop-hole for SQL injection. Since ORDER BY cannot put on parameter we have to append it in the query itself. I have already escaped some vulnerable characters but still I cannot say that is safe (from SQL injection). ESAPI provides the function encodeForSQL() but this doesn't work SQL Server (it works with MYSQL though).

Another approach I normally use is that instead of passing a column name in the arguments, I pass some numeric value and use switch-case to match the proper column name... but this is an increase in maintenance.

Is there any good method for escaping sorting parameters in SQL (or HQL) when we cannot use named parameters?

<cfscript>
    var gridstruct = {};
    var isPaging = 0;
    var hql = "FROM tbl6 order by #arguments.sortcolumn#";      
    x = entitytoquery(ORMexecuteQuery(hql,false));
</cfscript>
like image 308
Pritesh Patel Avatar asked Dec 18 '13 04:12

Pritesh Patel


People also ask

How can SQL injection be prevented?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

How can we prevent SQL injection in dynamic query in SQL Server?

To avoid SQL injection flaws is simple. Developers need to either: a) stop writing dynamic queries with string concatenation; and/or b) prevent user supplied input which contains malicious SQL from affecting the logic of the executed query.

Is escaping enough to prevent SQL injection?

Character Escaping Pre-cleansing input data by “escaping” characters tells SQL values that they should be treated as a string, rather than as a command. Escaping special characters doesn't guarantee SQL injection prevention, but it reduces the risk significantly. Here is an example of how character escaping works.

Does NamedParameterJdbcTemplate prevent SQL injection?

Using parameters in a NamedParameterJdbcTemplate will use JDBC prepared statement with parameters, which will - in general - protect you against SQL injection.


1 Answers

I'd probably just validate the value of the incoming sortcolumn argument against a known list of values that are appropriate. SQLI aside, you'd not want to be sorting on just any column in the underlying schema, surely?

eg:

if (!isValid("regex", arguments.sortcolumn, "list|of|valid|values|here")){
    throw(type="IllegalArgumentException");
}
like image 139
Adam Cameron Avatar answered Nov 06 '22 15:11

Adam Cameron