Saturday, June 6, 2015

SQL - Injection

In the most cases, SQL injection attacks are executed via front-end Web/Mobile applications that don't properly validate user input.  These attacks can be carried out manually which requires a lot of potential means if you have a lot of time. 

Simply, SQL injection is the process by which a malicious user enters SQL statements instead of valid input. 
For example, suppose that a website is asking for a user name. Instead of actually typing in a user name, a malicious user could type ‘blah’; DROP TABLE Sales;. The web server will happily take the user input and pass it along to the application layer, where it is executed in code as follows:
SqlCommand cmd = new SqlCommand
("SELECT * FROM Sales WHERE Name='" + customerName + "'", conn)
To SQL Server, it looks like the following:
SELECT * FROM Sales WHERE Name='blah';
DROP TABLE Sales;
When this statement executes, the sales table will be erased (which is not quite what the application developer had in mind!). You can see how easy it is for malicious users to cause problems and return potentially sensitive information via simple inputs to webpages or applications that blindly accept user input to build dynamic SQL. 
To eliminate this potential, add the user input as a parameter to the SqlCommand rather than concatenating dynamic SQL strings, as shown here:
SqlCommand cmd = new SqlCommand("SELECT * FROM Sales WHERE Name=@CustomerName", conn));
cmd.Parameters.Add("@CustomerName", customerName);
By using the Parameters collection of the SqlCommand object, whatever the user types will be treated just as the value of the name part of the WHERE clause.

No comments:

Post a Comment

Popular Posts