Handling SQL Injection Attack using Global.asax page.

<%@ Application Language="C#" %>
<script runat="server">
    private static string[] SQLKeywords = new string[]
      {
            // code to use it in the "Application_BeginRequest" method to prevent "ASCII Encoded/Binary String Automated SQL Injection Attack" on the Website     

            ";", "--", "EXECUTE ", "EXEC(", "SELECT ", "INSERT ", "UPDATE ", "DELETE ", "CREATE ",
            "TRUNCATE ", "DROP ", "ALTER TABLE ", "TABLE ", "DATABASE ", "WHERE ", "ORDER BY ", "GROUP BY "
            "DECLARE ", "CAST(", "CONVERT(", "VARCHAR(", "NVARCHAR("
      };
    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
    }
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
    }
    void Application_Error(object sender, EventArgs e) 
   
        // Code that runs when an unhandled error occurs
    }
    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started
    }
    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
    }
    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        // To prevent "ASCII Encoded/Binary String Automated SQL Injection Attack" on the Website
        HttpContext context = HttpContext.Current;
        if (context != null)
        {
            string queryString = "";
            string strErrorMessage = "";
            queryString = context.Request.ServerVariables["QUERY_STRING"];
            try
            {
                if (queryString != "")
                {
                    if (queryString.Length > 500)
                    {
                       strErrorMessage = String.Format("Unexpected 'QUERY_STRING' length ({0}).", queryString).ToString();
                        throw new Exception(strErrorMessage);
                    }
                    queryString = Server.UrlDecode(queryString);
                    queryString = queryString.ToUpper();
                    foreach (string keyword in SQLKeywords)
                    {
                        if (queryString.IndexOf(keyword) != (-1))
                        {
                            strErrorMessage = String.Format("Unexpected T-SQL keyword ('{0}') has been detected ({1})", keyword, queryString);
                            throw new Exception(strErrorMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
</script>

Ebook Download
View all
Learn
View all