Best practises for preventing SQL injection?
Already very good answers on this question, however I would like to mention some more:
- Secure coding (which is already been mentioned by many already)
- Escaping user input
- Parameterized queries (prepared statements, predefined queries where you only bind variables)
- Code defensively
- Monitoring for attacks
- Network Intrusion Detection System (NIDS)
- Host Intrusion Detection System (HIDS)
- Application Intrusion Detection System (AppIDS)
- Block attacks
- Application firewall
- Database firewall
- Web application firewall
- Apache ModSecurity
- Cisco Application Velocity System (AVS)
- Probe for vulnerabilities
- Automated blackbox injection testing
- Static source code analysis
- Manual penetration testing
This is only for prevention and I have not taken sql server hardening into account. There is however many similarities.
Additional defenses in case you are already vulnerable to injection would be:
- Running your application with the least amount of grants necessary
- Specifically grant only access to the database and tables you need
- Be sure to only grant the privilege it needs (usually select, insert, update)
Prepared statements, parameterized queries, escaping all user input, for a good starter see http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet.
The key defence is to only use API's that securely escape database queries - these are generally referred to as parameterised or prepared statements. These can't be used in all cases (for example where a SQL identifier such as the table or column name is supplied at runtime), but is the best approach where possible (the majority of cases).
Note - this can lead to harmful data being put into the database, so be aware of that when using this data elsewhere in the application
The second defence is to take an escaping approach. This is the "replace a single quote with two quotes" approach. If you need to go this way, you must escape every potentially harmful character, which means more than single quotes in some cases. I'd advise using a higher level library such as OWASP ESAPI if possible to do this for you, or read the OWASP SQL Injection Cheat Sheet (referenced above) closely.