Our application has a filtering capability, where the database query is built dynamically as per the user-entered filter values. Prepared Statements are not an option for us.
All the filters are text filters, so we have the luxury to use IN keyword instead of the equals (=) operator.
We're currently checking the possibility of SQL injections that can be caused by the user text inputs.
I think since we're not using the = operator and we wrap the user input by single quotes, we can negate the possibility of SQL injection by handling the single quote (') gracefully.
StringBuilder resultBuilder = new StringBuilder(""); resultBuilder.append("'").append(input.trim()).append("'"); We're thinking of restricting single quotes for user inputs. Is it possible to break the query in our scenario, if we restrict single quote?
Etc. If we do not handle the single quote, query can be injected like this:
SELECT ItemName, ItemDescription FROM Items WHERE ItemNumber IN ('userInput'); If user enters something like, 'Alice'); DROP TABLE users;-- the query becomes,
SELECT ItemName, ItemDescription FROM Items WHERE ItemNumber IN ('Alice'); DROP TABLE users;--'); PS: We have a capability where the user can select any database table to a GUI grid to display data, and add custom filters according to that selected table, to filter that grid data. So the DB entities are not predefined at the code. This makes it impossible or messy to use Prepare statements.
- DB Server: Postgres
- Language: Java
- Framework: Spring boot, JdbcTemplate
PreparedStatementGetteras a second parameter to some variants of theJdbcTemplate#querymethod. I understand that you need to build the query dynamically based on the user-provided filters, so it's all a bit inconvenient. But it's certainly doable.