SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution.
The following line of code illustrates this vulnerability:
statement = "SELECT * FROM users WHERE name = '" + userName + "';"
This SQL code is designed to pull up the records of the specified username from its table of users. However, if the "userName" variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the "userName" variable as
' or '1'='1
Or using comments to even block the rest of the query:
' or '1'='1';/*'
renders this SQL statement by the parent language:
SELECT * FROM users WHERE name = '' OR '1'='1';
If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of '1'='1' is always true.
The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table (in essence revealing the information of every user), using an API that allows multiple statements:
a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't
This input renders the final SQL statement as follows:
SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';
Preventing SQL injection
To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead,
- parameterized statements must be used (preferred)
- user input must be carefully escaped or filtered.
- Use Linq to SQL classes
0 comments:
Post a Comment