9.16

What is an SQL injection attack? Explain how it works and what precautions must be taken to prevent SQL injection attacks.


SQL injection attack is a type of attack, where the attacker manages to get an application to execute an SQL query created by the attacker.

The following paragraphs are from the book “SQL injection attacks and defense” by Justin Clarke.

SQL injection is an attack in which SQL code is inserted or appended into application/user input parameters that are later passed to a back-end SQL server for parsing and execution. Any procedure that constructs SQL statements could potentially be vulnerable, as the diverse nature of SQL and the methods available for constructing it provide a wealth of coding options. The primary form of SQL injection consists of direct insertion of code into parameters that are concatenated with SQL commands and executed. A less direct attack injects malicious code into strings that are destined for storage in a table or as metadata. When the stored strings are subsequently concatenated into a dynamic SQL command, the malicious code is executed. When a Web application fails to properly sanitize the parameters which are passed to dynamically created SQL statements (even when using parameterization techniques) it is possible for an attacker to alter the construction of back-end SQL statements.

SQL injection vulnerabilities most commonly occur when the Web application developer does not ensure that values received from a Web form, cookie, input parameter, and so forth are validated before passing them to SQL queries that will be executed on a database server. If an attacker can control the input that is sent to an SQL query and manipulate that input so that the data is interpreted as code instead of as data, the attacker may be able to execute code on the back-end database.

Precautions that must be taken to prevent SQL injection attacks: * Use prepared statements. * Correctly handle errors, so as not to give valuable information (such as database version, operating system version) to attackers. * Encrypt sensitive attributes of relations (to mitigate the attack) * Use white-listing approach to validate input. The white-list approach to validating input is to create a list of all possible characters that should be allowed for a given input, and to deny anything else. * Applications should use different database users to perform SELECT, UPDATE, INSERT, and similar commands. In the event of an attacker injecting code into a vulnerable statement, the privileges afforded would be minimized.