Website Security: C # Implementation of Anti-SQL Injection code

Source: Internet
Author: User
Website security is a top concern for every website developer and operator. Once a website has a vulnerability, it will inevitably cause great losses. In order to improve the security of the website, the website should first prevent injection, and the most important thing is that the security facilities of the server should be put in place.

The following describes some elements of website anti-injection.

I. Discard SQL statements and splice them directly, although it is very convenient to write.

2. If you use SQL statements, use parameterization to add Param.

Iii. Use stored procedures as much as possible, with high security and fast processing speed

4. Blocking SQL, javascript, and other injections (very important) is unlikely to be written to each file. So we need to find a way to work on all files. I collected the following three methods online:

C # anti-SQL injection method 1

In the Web. config file, add a tag under <etettings> as follows:

 
 
  1. < appSettings>
  2. < add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
  3. < /appSettings>  

Key is the value after <saveParameters> is "OrderId-int32", where "-" indicates the name of the parameter, such as OrderId, and int32 indicates the data type.

C # SQL Injection prevention method 2

Add the following section to Global. asax:

 
 
  1. protected void Application_BeginRequest(Object sender, EventArgs e){
  2. String[] safeParameters = System.Configuration.ConfigurationSettings.AppSettings["safeParameters"].ToString().Split(',');
  3. for(int i= 0 ;i <   safeParameters.Length; i++){
  4. String parameterName = safeParameters[i].Split('-')[0];
  5. String parameterType = safeParameters[i].Split('-')[1];
  6. isValidParameter(parameterName, parameterType);
  7. }
  8. }
  9. public void isValidParameter(string parameterName, string parameterType){
  10. string parameterValue = Request.QueryString[parameterName];
  11. if(parameterValue == null) return;
  12. if(parameterType.Equals("int32")){
  13. if(!parameterCheck.isInt(parameterValue)) Response.Redirect("parameterError.aspx");
  14. }
  15. else if (parameterType.Equals("USzip")){
  16. if(!parameterCheck.isUSZip(parameterValue)) Response.Redirect("parameterError.aspx");
  17. }
  18. else if (parameterType.Equals("email")){
  19. if(!parameterCheck.isEmail(parameterValue)) Response.Redirect("parameterError.aspx");
  20. }
  21. }  

C # anti-SQL Injection Method3.

Use string filter class

 
 
  1. Using System;
  2. Namespace web. comm
  3. {
  4. /** // <Summary>
  5. /// Summary of ProcessRequest.
  6. /// </Summary>
  7. Public class ProcessRequest
  8. {
  9. Public ProcessRequest ()
  10. {
  11. //
  12. // TODO: add the constructor logic here
  13. //
  14. }
  15. SQL injection attack code analysis # region SQL injection attack code analysis
  16. /** // <Summary>
  17. /// Process user-submitted requests
  18. /// </Summary>
  19. Public static void StartProcessRequest ()
  20. {
  21. // System. Web. HttpContext. Current. Response. Write ("<script> alert ('ddddd'); </script> ");
  22. Try
  23. {
  24. String getkeys = "";
  25. // String sqlErrorPage = System. Configuration. ConfigurationSettings. deleettings ["CustomErrorPage"]. ToString ();
  26. If (System. Web. HttpContext. Current. Request. QueryString! = Null)
  27. {
  28. For (int I = 0; I <System. Web. HttpContext. Current. Request. QueryString. Count; I ++)
  29. {
  30. Getkeys = System. Web. HttpContext. Current. Request. QueryString. Keys [I];
  31. If (! ProcessSqlStr (System. Web. HttpContext. Current. Request. QueryString [getkeys], 0 ))
  32. {
  33. // System. Web. HttpContext. Current. Response. Redirect (sqlErrorPage + "? Errmsg = sqlserver & sqlprocess = true ");
  34. System. Web. HttpContext. Current. Response. Write ("<script> alert ('do not submit it illegally! '); History. back (); </script> ");
  35. System. Web. HttpContext. Current. Response. End ();
  36. }
  37. }
  38. }
  39. If (System. Web. HttpContext. Current. Request. Form! = Null)
  40. {
  41. For (int I = 0; I <System. Web. HttpContext. Current. Request. Form. Count; I ++)
  42. {
  43. Getkeys = System. Web. HttpContext. Current. Request. Form. Keys [I];
  44. If (! ProcessSqlStr (System. Web. HttpContext. Current. Request. Form [getkeys], 1 ))
  45. {
  46. // System. Web. HttpContext. Current. Response. Redirect (sqlErrorPage + "? Errmsg = sqlserver & sqlprocess = true ");
  47. System. Web. HttpContext. Current. Response. Write ("<script> alert ('do not submit it illegally! '); History. back (); </script> ");
  48. System. Web. HttpContext. Current. Response. End ();
  49. }
  50. }
  51. }
  52. }
  53. Catch
  54. {
  55. // Error handling: process user submitted information!
  56. }
  57. }
  58. /** // <Summary>
  59. /// Analyze whether the user request is normal
  60. /// </Summary>
  61. /// <Param name = "Str"> input user to submit data </param>
  62. /// <Returns> whether SQL injection attack code is returned </returns>
  63. Private static bool ProcessSqlStr (string Str, int type)
  64. {
  65. String SqlStr;
  66. If (type = 1)
  67. SqlStr = "exec | insert | select | delete | update | count | chr | mid | master | truncate | char | declare ";
  68. Else
  69. SqlStr = "'| and | exec | insert | select | delete | update | count | * | chr | mid | master | truncate | char | declare ";
  70. Bool ReturnValue = true;
  71. Try
  72. {
  73. If (Str! = "")
  74. {
  75. String [] anySqlStr = SqlStr. Split ('| ');
  76. Foreach (string ss in anySqlStr)
  77. {
  78. If (Str. IndexOf (ss)> = 0)
  79. {
  80. ReturnValue = false;
  81. }
  82. }
  83. }
  84. }
  85. Catch
  86. {
  87. ReturnValue = false;
  88. }
  89. Return ReturnValue;
  90. }
  91. # Endregion
  92. }
  93. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.