The following article explains how to protect your ASP.NET code from a SQL Injection. The recent injection attacks that have been seen against ASP and ASP.Net coded sites takes advantage of vulnerabilities in improperly coded sites. These attacks can be mitigated by simply running any user input that can come in contact with the database through a sanitization process, and this does not apply to .Net and ASP code but any language. Below are examples of how to protect your code from Injection attacks.
The following are a few techniques you can use to protect your code from Injection attacks:
Write your dynamic queries using parameterized queries
Dim SSN as String = Request.QueryString("page")
Dim cmd As new SqlCommand("SELECT title, content FROM page WHERE p_id = @p_id")
Dim param = new SqlParameter("p_id", SqlDbType.Int)
param.Value = SSN
cmd.Parameters.Add(param)
Set the length of the input data
If you know that the length of the input data will not be longer than a set amount then you should constrain it to that length. In this case we are going to constrain the page length to 4 characters which will give us up to 9999 pages.
Dim page_num as String = Request.QueryString("page")
Dim cmd As new SqlCommand("SELECT title, content FROM page WHERE p_id = @p_id")
'Here we are setting the max length to 4 characters
Dim param = new SqlParameter("p_id", SqlDbType.Int, 4)
param.Value = page_num
cmd.Parameters.Add(param)
Sanitize any escape characters from the SQL query
Dim page_num as String = SafeSQLLiteral ( Request.QueryString("page") )
Dim cmd As new SqlCommand("SELECT title, content FROM page WHERE p_id = @p_id")
Dim param = new SqlParameter("p_id", SqlDbType.Int, 4)
param.Value = page_num
cmd.Parameters.Add(param)
Private Function SafeSQLLiteral(ByVal inputSQL as String) as string
Return inputSQL.Replace("'", "''");
End Function
More information and code examples available at: