Several methods of preventing sql injection from Net

  • 2021-11-10 09:16:37
  • OfStack

Common methods to prevent sql injection:

1. The server verifies the type of parameter values transmitted from the front end;

2. The server executes sql, using parameterized value transfer instead of sql string splicing;

3. The server carries out sql keyword transmission and detection on the data transmitted from the front end;

Focus on recording the server for sql keyword detection:

1. sql keyword detection class:


public class SqlInjectHelper:System.Web.UI.Page
 {
  private static string StrKeyWord = "select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec|master|net local group administrators|net user|or|and";
  private static string StrSymbol = ";|(|)|[|]|{|}|%|@|*|'|!";

  private HttpRequest request;
  public SqlInjectHelper(System.Web.HttpRequest _request)
  {
   this.request = _request;
  }
  public bool CheckSqlInject()
  {
   return CheckRequestQuery() || CheckRequestForm();
  }

  ///<summary> 
  /// Check URL Is included in the Sql Injection  
  /// <param name="_request"> Current HttpRequest Object </param> 
  /// <returns> If it contains sql Inject keywords and return: true; Otherwise return: false</returns> 
  ///</summary> 
  public bool CheckRequestQuery()
  {
   if (request.QueryString.Count > 0)
   {
    foreach (string sqlParam in this.request.QueryString)
    {
     if (sqlParam == "__VIEWSTATE") 
      continue;
     if (sqlParam == "__EVENTVALIDATION") 
      continue;
     if (CheckKeyWord(request.QueryString[sqlParam].ToLower()))
     {
      return true;
     }
    }
   }
   return false;
  }
  ///<summary> 
  /// Check whether the submitted form contains Sql Injection keyword 
  /// <param name="_request"> Current HttpRequest Object </param> 
  /// <returns> If it contains sql Inject keywords and return: true; Otherwise return: false</returns> 
  ///</summary> 
  public bool CheckRequestForm()
  {
   if (request.Form.Count > 0)
   {
    foreach (string sqlParam in this.request.Form)
    {
     if (sqlParam == "__VIEWSTATE") 
      continue;
     if (sqlParam == "__EVENTVALIDATION") 
      continue;
     if (CheckKeyWord(request.Form[sqlParam]))
     {
      return true;
     }
    }
   }
   return false;
  }
  ///<summary> 
  /// Check whether the string contains Sql Injection keyword  
  /// <param name="_key"> Checked string </param> 
  /// <returns> If it contains sql Inject keywords and return: true; Otherwise return: false</returns> 
  ///</summary> 
  private static bool CheckKeyWord(string _key)
  {
   string[] pattenKeyWord = StrKeyWord.Split('|');
   string[] pattenSymbol = StrSymbol.Split('|');
   foreach (string sqlParam in pattenKeyWord)
   {
    if (_key.Contains(sqlParam + " ") || _key.Contains(" " + sqlParam))
    {
     return true;
    }
   }
   foreach (string sqlParam in pattenSymbol)
   {
    if (_key.Contains(sqlParam))
    {
     return true;
    }
   }
   return false;
  }

 }

In SqlInjectHelper class, query parameters and form parameters of request are detected, but cookie is not detected. If necessary, it can be added by itself;

2. Where is SqlInjectHelper called?

1) If you want to do sql keyword detection for all requests of the whole web site, call it in Application_BeginRequest method of Global. asax;


protected void Application_BeginRequest(object sender, EventArgs e)
  {
   SqlInjectHelper myCheck = new SqlInjectHelper(Request);
   bool result = myCheck.CheckSqlInject();
   if (result)
   {
    Response.ContentType = "text/plain";
    Response.Write(" The data you submitted has malicious characters! ");
    Response.End();
   }
  }

2) If only sql keyword detection is needed for the interface of an interface file, the SqlInjectHelper class only needs to be called at the beginning of the file;


public class Handler1 : IHttpHandler
 {
  public void ProcessRequest(HttpContext context)
  {
   SqlInjectHelper myCheck = new SqlInjectHelper(context.Request);
   bool result = myCheck.CheckSqlInject();
   context.Response.ContentType = "text/plain";
   context.Response.Write(result?" The data you submitted has malicious characters! ":"");
   context.Response.StatusCode = result ? 500 : 200;
  }
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }

The above code is to add sql keyword detection to a certain 1-class handler (ashx);

3. Supplementary note: __VIEWSTATE, __EVENTVALIDATION in asp. net,

In the sql keyword detection method, the parameters of __VIEWSTATE and __EVENTVALIDATION are excluded;

1), __VIEWSTATE

ViewState is a mechanism used in ASP. NET to save the state value of WEB control when it is returned. When the WEB form (FORM) is set to runat = "server", the form (FORM) is appended with a hidden attribute _ VIEWSTATE. The state values of all controls in ViewState are stored in _ VIEWSTATE.

ViewState is a domain of class Control, and all other controls acquire ViewState functionality by inheriting Control. Its type is system. Web. UI. StateBag, a collection of objects with names/values.

When a page is requested, ASP. NET serializes the state of all controls into a string, which is then sent to the client as a hidden property of the form. When the client returns the page, ASP. NET analyzes the returned form attribute and assigns the corresponding value to the control;

2), __EVENTVALIDATION

__EVENTVALIDATION is only used to verify that an event is sent from a legitimate page and is only a digital signature, so 1 is short.

Hidden fields with the "id" attribute of "__EVENTVALIDATION" are new security measures for ASP. NET 2.0. This function can prevent unauthorized requests sent by potentially malicious users from the browser side.;

4. Another version of sql keyword detection: this version puts all dangerous characters in a regular expression;

This class not only detects common sql keywords but also common xss attack keywords


public class SafeHelper
 {
  private const string StrRegex = @"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt)\b|^\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|<\s*img\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
  public static bool PostData()
  {
   bool result = false;
   for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
   {
    result = CheckData(HttpContext.Current.Request.Form[i].ToString());
    if (result)
    {
     break;
    }
   }
   return result;
  }

  public static bool GetData()
  {
   bool result = false;
   for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
   {
    result = CheckData(HttpContext.Current.Request.QueryString[i].ToString());
    if (result)
    {
     break;
    }
   }
   return result;
  }
  public static bool CookieData()
  {
   bool result = false;
   for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
   {
    result = CheckData(HttpContext.Current.Request.Cookies[i].Value.ToLower());
    if (result)
    {
     break;
    }
   }
   return result;

  }
  public static bool referer()
  {
   bool result = false;
   return result = CheckData(HttpContext.Current.Request.UrlReferrer.ToString());
  }
  public static bool CheckData(string inputData)
  {
   if (Regex.IsMatch(inputData, StrRegex))
   {
    return true;
   }
   else
   {
    return false;
   }
  }
 }

Summarize


Related articles: