How to fix SQL Injection Vulnerabilities

Source: Internet
Author: User
Tags how to fix sql injection

According to Baidu, SQL injection is a query string that inserts SQL commands into a Web form to submit or input domain names or page requests, and finally deceives the server to execute malicious SQL commands. In fact, it is to submit carefully constructed database statements so that they can feedback some useful data. To put it bluntly, it is to spoof the database. if there is only a web server, SQL Injection cannot be performed.
There are two injection methods commonly used on the Internet. One is guessing to expose the database to information such as the user name and password, and the other is directly bypassing authentication to obtain permissions. Correspondingly, to fix such vulnerabilities, you must disable the submission of special data or modify the data submitted.
The following is anti-injection filtering code in different scripting languages. In fact, the idea is the same.

 

1. PHP anti-injection filtering code

/*************************
Determines whether the passed variable contains invalid characters, such as $ _ POST and $ _ GET.
Function: Anti-Injection
Usage: Save the following code as ak and php. Call method: Add include ("ak. php") to the data submission page ");
**************************/
<? Php
Function dowith_ SQL ($ str)
// Add the signature on both sides.
{
$ Refuse_str = "exec | and | or | select | update | from | where | order | by | * | delete | insert | into | values | create | table |

Database | set | char | asc | cast | declare | <script | iframe | 3bomb | c. js | ;";
// Define anti-injection characters
$ Arr = explode ("|", $ refuse_str );
// Extract the value in $ refuse_str separately
For ($ I = 0; $ I <count ($ arr); $ I ++)
{
$ Replace = "[". $ arr [$ I]. "]";
$ Str = str_replace ($ arr [$ I], $ replace, $ str );
// Search for the string $ arr [$ I] in the variable $ str and replace it with the string [$ replace]
}
Return $ str;
}
Foreach ($ _ GET as $ key => $ value)
// Obtain the value of $ _ GET obtained by the GET method and pass it to $ key and assign it to $ value.
{
$ _ GET [$ key] = dowith_ SQL ($ value );
// Process the signature in $ value with $ _ GET [$ key]
}
Foreach ($ _ POST as $ key => $ value)
{
$ _ POST [$ key] = dowith_ SQL ($ value );
}
?>
The above anti-injection method only defends against the data submitted by the GET and POST methods. However, the order in which the WEB server reads data is that the data in GET is obtained first, and no data in POST is returned, no more data will be sent to COOKIES. The above Code does not prevent cookie injection. Anti-Cookie injection is relatively simple. The cookie id value is generally only Arabic numerals, But Cookie injection must construct code in the id, as long as the UID parameter is obtained, the Code is as follows:

<? Php
If ($ _ COOKIE [id]! = Null ){
// Judge that cookies are not empty
Foreach ($ _ COOKIE [id] as $ key => $ id ){
// Read the values in cookies
If (if_numeric ($ id) <0 ){
Echo "<script language = \" javascript \ "> alert (\" Please do not enter invalid characters! \ "); </Script>" history. go (-1); </script> ";
}
}
?>

Save the above Code as hk. php.
Therefore, in normal times, add include ("ak. php"); and include ("hk. php") on the webpage ");


2. ASP anti-injection filtering code

<%
-------- Description ------------------
Usage: use it in the header of the page to be protected <! -- # Include File = "sql2.Asp" --> Include
Tip: copy the code to CONN. asp (database connection file). If all the files containing CONN are not noticed
--------------------------------
Dim xf_Post, xf_Get, xf_In, xf_Inf, xf_Xh, xf_db, xf_dbstr
Customize the string to be filtered, separated by "|"
Xf_In = "|; | and | exec | insert | select | delete | update | count | * | % | chr | mid | master | truncate | char | declare"
Xf_Inf = split (xf_In, "| ")
If Request. Form <> "" Then
For Each xf_Post In Request. Form

For xf_Xh = 0 To Ubound (xf_Inf)
If Instr (LCase (Request. Form (xf_Post), xf_Inf (xf_Xh) <> 0 Then
Response. Write "<Script Language = JavaScript> alert (please do not include invalid characters in the parameter to try to inject); </Script>"
Response. Write "illegal operation! The system makes the following records: <br>"
Response. Write "Operation IP:" & Request. ServerVariables ("REMOTE_ADDR") & "<br>"
Response. Write "operation time:" & Now & "<br>"
Response. Write "Operation page:" & Request. ServerVariables ("URL") & "<br>"
Response. Write "submission method: POST <br>"
Response. Write "Submit parameters:" & xf_Post & "<br>"
Response. Write "submit data:" & Request. Form (xf_Post)
Response. End
End If
Next
Next
End If
If Request. QueryString <> "Then
For Each xf_Get In Request. QueryString
For xf_Xh = 0 To Ubound (xf_Inf)
If Instr (LCase (Request. QueryString (xf_Get), xf_Inf (xf_Xh) <> 0 Then
Response. Write "<Script Language = JavaScript> alert (please do not include invalid characters in the parameter to try to inject); </Script>"
Response. Write "illegal operation! The system has made the following record for you <br>"
Response. Write "Operation IP:" & Request. ServerVariables ("REMOTE_ADDR") & "<br>"
Response. Write "operation time:" & Now & "<br>"
Response. Write "Operation page:" & Request. ServerVariables ("URL") & "<br>"
Response. Write "submission method: GET <br>"
Response. Write "Submit parameters:" & xf_Get & "<br>"
Response. Write "submit data:" & Request. QueryString (xf_Get)
Response. End
End If
Next
Next
End If
%>

Similarly, we can add the cookies and code to the data submission page.
If (Request. Cookies ["uid"]! = Null)
{
Uid = Request. Cookies ["uid"]. value;
Isnumeric cooidesID = new isnumeric ();
// This is a class
If (cooidesID. reIsnumeric (ruid ))
// If it is a number, run the following
{
String str = "select * from userTable where id =" + uid;
...
}
}

3. JSP anti-injection filtering code
<Script language = "javascript">
<! --
Var url = location. search;
// What is the function of location. search? Obtain the QueryString part.
Var re =/^? (. *) (Select % 20 | insert % 20 | delete % 20 from % 20 | count (| drop % 20table | update % 20 truncate % 20 | asc (| mid (| char (| xp_1_shell | exec % 20master | net % 20 localgroup % 20administrators | "|: | net % 20user | % 20or % 20 )(. *) $/gi;
// Define a special string
Var e = re. test (url );
// Check whether a substring matches a regular expression in the test () string. Returns true or false.
If (e ){
Alert ("the address contains invalid characters ~ ");
Location. href = "error. asp ";
}
// -->
<Script>
Of course, we can also define a filter function that is directly applied to data parameters submitted, such as user names and passwords. The function is as follows:
Function checkuseravoid (str ){
Var inj_str = "'| and | exec | insert | select | delete | update | count | * | % | chr | mid | master | truncate | char | declare |; | or |-| + | ,";
Var sarray = new Array ();
Sarray = inj_str.split (| );
For (var I = 0; I <inj_stra.length; I ++ ){
If (str. indexOf (inj_stra)> = 0)
Return true;
}
Return false;
}


4. C # anti-injection filtering code
// This example is tentatively set to "=" and ". You can add more
Bool CheckParams (params object [] args)
{
String [] Lawlesses = {"= ",""};
If (Lawlesses = null | Lawlesses. Length <= 0) return true;
// Construct a regular expression. For example, if Lawlesses is a = sign and a number, the regular expression is. * [=}]. *
// In addition, because I want to make a general and easy-to-Modify function, I have added a step from a character array to a regular expression. In actual use, I can directly write a regular expression;
String str_Regex = ".*[";
For (int I = 0; I <Lawlesses. Length-1; I ++)
Str_Regex + = Lawlesses + "| ";
Str_Regex + = Lawlesses [Lawlesses. Length-1] + "]. *";
//
Foreach (object arg in args)
{
If (arg is string)
// If it is a string, directly check
{
If (Regex. Matches (arg. ToString (), str_Regex). Count> 0)
Return false;
}
Else if (arg is ICollection)
// If it is a set, check whether the element in the set is a string.
{
Foreach (object obj in (ICollection) arg)
& Nbs

Related Article

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.