SQL Injection-proof your integrated SQL search in ASP.NET 2.0

31 10 2007

I had forgotten to add SQL Injection prevention logic when I integrated and implemented a SQL search function for my employer’s internal ASP.NET app.  So in this post, I’m adding it for archival and sharing purposes.

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.

BTW, here’s an excellent article about SQL Injection on the MSDN site. 

1. The first thing you’ll need to do is grab the user’s input from the search textbox; for example:

// Get user search input
string requestString = txtSearch.Text.Trim(null);

2. Next, you’ll need to add logic to see if the user input contains any of the following:

image

I added something like this:


if ((requestString.Contains(";")) || (requestString.Contains("'")) ||
    (requestString.Contains("--")) || (requestString.Contains("/*")) ||
    (requestString.Contains("*/")) || (requestString.Contains("xp_")))
{
    // Stop processing and notify user
}
else
{
    // Continue processing and show results
}

3. Build/compile your app then test it out.  If all goes well, you should not get any errors and your web app’s search function should now be SQL Injection-proof.


Actions

Informations

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>