Add two more assignments for SQL injection where only filtering is applied.
This commit is contained in:
@ -1,47 +1,11 @@
|
||||
== Order by clause
|
||||
== Input validation alone is not enough!!
|
||||
|
||||
Question: Does a prepared statement always prevent against an SQL injection?
|
||||
Answer: No it does not
|
||||
You need to do both use parametrized queries and validate the input received from the user. On StackOverflow you will
|
||||
see alot of answers stating that input validation is enough. *However* it only takes you so far before you know it
|
||||
the validation is broken and you have an SQL injection in your application.
|
||||
|
||||
Let us take a look at the following statement:
|
||||
A nice read why it is not enough can be found https://twitter.com/marcan42/status/1238004834806067200?s=21
|
||||
|
||||
----
|
||||
SELECT * FROM users ORDER BY lastname;
|
||||
----
|
||||
Let's repeat one of the previous assignments, the developer fixed the possible SQL injection with filtering, can you
|
||||
spot the weakness in this approach?
|
||||
|
||||
If we look at the specification of the SQL grammar the definition is as follows:
|
||||
|
||||
----
|
||||
SELECT ...
|
||||
FROM tableList
|
||||
[WHERE Expression]
|
||||
[ORDER BY orderExpression [, ...]]
|
||||
|
||||
orderExpression:
|
||||
{ columnNr | columnAlias | selectExpression }
|
||||
[ASC | DESC]
|
||||
|
||||
selectExpression:
|
||||
{ Expression | COUNT(*) | {
|
||||
COUNT | MIN | MAX | SUM | AVG | SOME | EVERY |
|
||||
VAR_POP | VAR_SAMP | STDDEV_POP | STDDEV_SAMP
|
||||
} ([ALL | DISTINCT][2]] Expression) } [[AS] label]
|
||||
|
||||
Based on HSQLDB
|
||||
----
|
||||
|
||||
This means an `orderExpression` can be a `selectExpression` which can be a function as well, so for example with
|
||||
a `case` statement we might be able to ask the database some questions, like:
|
||||
|
||||
----
|
||||
SELECT * FROM users ORDER BY (CASE WHEN (TRUE) THEN lastname ELSE firstname)
|
||||
----
|
||||
|
||||
So we can substitute any kind of boolean operation in the `when(....)` part. The statement will just work because
|
||||
it is a valid query whether you use a prepared statement or not an order by clause can by definition contain a
|
||||
expression.
|
||||
|
||||
=== Mitigation
|
||||
|
||||
If you need to provide a sorting column in your web application you should implement a whitelist to validate the value
|
||||
of the `order by` statement it should always be limited to something like 'firstname' or 'lastname'.
|
||||
|
Reference in New Issue
Block a user