Showing posts with label asp.net stop sql injection attack. Show all posts
Showing posts with label asp.net stop sql injection attack. Show all posts

Sunday, 14 April 2013

How to stop sql injection attack in Asp.net...


How to prevent website from sql injection attack  in Asp.net......



Hi friends this is a class  to prevent from sql injectiion for c#.

First create a class named as SqlInjectionScreeningModule.cs and it's code will be like below...

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class SqlInjectionScreeningModule : IHttpModule
{
    ///''please remove or add the blacklist variable as per your requirement''''''''
    ///''please check(run) your application after implementing this code''''''''''''''
    public static string[] blackList = { "--", ";--", "/*", "*/", "@@", "char", "nchar", "varchar", "nvarchar", 
    "alter", "begin", "cast", "create", "cursor", "declare", "drop", "exec", 
    "execute", "fetch", "kill", "open", " sys", "sysobjects", "syscolumns", 
    "commit", "truncate", "shutdown" };
    public void Dispose()
    {
        //no-op 
    }
    public void Init(HttpApplication app)
    {
        app.BeginRequest += app_BeginRequest;
    }
    private void app_BeginRequest(object sender, EventArgs e)
    {
        HttpRequest Request = (sender as HttpApplication).Context.Request;

        foreach (string key in Request.QueryString)
        {
            CheckInput(Request.QueryString[key]);
        }
        foreach (string key in Request.Form)
        {
            CheckInput(Request.Form[key]);
        }
        foreach (string key in Request.Cookies)
        {
            CheckInput(Request.Cookies[key].Value);
        }

        //For Each key As String In Request.Files
        //    CheckInput(Request.Cookies(key).Value)
        //Next

    }
    private void CheckInput(string parameter)
    {
        for (int i = 0; i <= blackList.Length - 1; i++)
        {
            if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
            {
                ///'Your Error Display Page''''''
                HttpContext.Current.Response.Redirect("~/Default.aspx");
            }
        }
    }
}



Now in web.config add below http modules....


    <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="SqlInjectionScreeningModule" type="SqlInjectionScreeningModule"/>
    </httpModules>

Thats it... now for all the pages for any input it will check for sql injection code in input.