SQL Injection is a very serious problem on any website that allows user input that is either inserted or checked against information in a database. Here's what we do to stop it:
1. To escape the ' character, use SQL parameters:
SqlCommand.CommandText = "SELECT * FROM tblTable WHERE TableID = @Parameter";
SqlCommand.Parameters.Add(new SqlParameter("@Parameter", parameterValue));
2. Whenever you Response.Write content that was submitted by a user eg in a forum for instance, htmlencode it:
3. To hide pages that crash and may expose table names in the database, in web.config add:
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm"/> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors>
This article presents a complete example of an SQL Injection attack against a site, describes the best techniques for preventing such an attack and why some of the common methods of prevention are not sufficient.