Sql injection Attacks & Defense

CVE-2024-2879

SQL injection is through the SQL command into the Web form submit or enter the domain name query string or page request, and ultimately to deceive the server to execute malicious SQL commands. Specifically, it leverages existing applications to inject (malicious) SQL commands into the background database engine, which can be exploited by typing (malicious) SQL statements into a Web site that has a security vulnerability Database, rather than according to the intention of the designer to execute SQL statements.

 

Basics

Principle

SQL injection attacks refer to the construction of special input as parameters passed to Web applications, and these are mostly SQL syntax in some combination, through the implementation of SQL statements and then implement the operation of the attacker, the main reason is that the program is not detailed To filter the user input data, resulting in illegal data intrusion system.

According to the relevant technical principles, SQL injection can be divided into platform-level injection and code-level injection. The former by the unsafe database configuration or database platform vulnerabilities caused by; the latter is mainly due to the programmer on the input is not carefully filtered, so the implementation of the illegal data query. Based on this, the cause of SQL injection is usually manifested in the following aspects:  type of inappropriate treatment;  insecure data library configuration;  unreasonable set of queries processing;  improper error handling;  escape character processing inappropriate ;  multiple submissions are handled improperly.

Attack

When an application uses input to construct a dynamic sql statement to access the database, a sql injection attack occurs. If your code uses stored procedures , and stored procedures as a string that contains unfiltered user input be passed, also occurs sql injection. Sql injection may lead to an attacker using an application to log in to execute commands in the database. The associated SQL injection can be done using the test tool pangolin. This can become a serious problem if the application connects to the database using an account with a very high privilege. In some form , the user input is directly used to construct dynamic sql command, or as a stored procedure input parameter, these forms are particularly vulnerable to sql injection attacks. And many Web site procedures in the preparation, there is no legitimacy of the user input to determine the process variable or improper handling of their own, so that the application exists security risks. In this way, the user can submit a database query code, according to the results of the return process to obtain some sensitive information or control the entire server, so sql injection occurred.

Protection

Summarize, there are the following points:

1. Never trust the user’s input. For user input validation, by a regular expression , or to limit the length; and single quotes

Double “-” to convert and so on.

2. Never use dynamic assembly sql, you can use the parameters of the direct use of sql or stored procedures for data query access.

3. Never use administrator privileges database connection, use limited individual permissions for each application database connection.

4. Do not store confidential information directly, encrypted or hash out the password and sensitive information.

5. Application of the exception information should be given as little as possible tips, it is best to use a custom error message to the original error message packaging

Injection method

Method 1

First guess the table name

And (Select count(*) from “table name”)

Guess the name

And (Select count from the table)

Or it could be

And exists (select * from table name)

And exists (select column name from the table name)

Return the correct, then write the table name or column name is correct

Here should be noted that, this can not be used to guess the contents, such as and exists (select len ​​(user) from admin)> 3 This is not acceptable

Many people are like the contents of the query inside, once iis did not close the error, then you can use the error method to easily access the contents of the library

Obtain the database connection user name:; and user> 0

This is the bamboo put forward, here I quote “SQL into the bible” inside a paragraph to explain:

“Focus and user> 0, we know, user is SQLServer a built-in variable whose value is currently connected user name, and type nvarchar. Take a nvarchar value with the int number 0 comparison, the system will first attempt to Nvarchar value into int type, of course, the process will certainly be wrong, SQLServer error message is: the nvarchar conversion int exception, XXXX can not be converted to int ”

See here we understand it, the error is the principle of the use of SQLserver built-in system table conversion query, the conversion process will be wrong, and then will be displayed on the page, there is a similar and 1 = (selet top 1 user from Admin), this statement is also to burst out. ; And db_name ()> 0 is the violent database name.

Once you close the IIS error, you can also use the union ( union query ) to check the content of the main statement is the

Order by 10

And 1 = 2 union select 1,2,3,4,5,6,7,8,9,10 from admin

And 1 = 2 union select 1,2,3, user, 5, passwd, 7,8,9,10 from admin

The above order by 10 is the main check the number of fields, admin is the table name, you can guess, user, passwd is listed

Anyway, is to return to the right that is, the return exception is wrong

Another very common ASCII code split half method

First know the designated column name, for example, the length of the contents of the user

And (select len ​​(user) from admin) = 2 is the query length is not 2, the return error increase or decrease the number, generally this number will not be too big, too much to give up, guess also redundant

The following logical symbols can be changed according to different requirements,

>; Greater than “; less than = = equal to slightly updated phrase, = can also be said that the transmission symbol <>;

Know the length of the solution can start guessing

And (Select top 1 asc (mid (user, n, 1)) from admin)> 100

N is guess the name of the first few table, the length of the last figure is just guess out the length of the column name, And (Select top 1 asc (mid (user, 1,1)) from> Solutions for the first user in the ASCII content of character is not greater than 100

Correct, then the first USER represents a character ‘s ASCII code greater than 100, then guess> 120, an error is returned between 100-120, then shrink less then step by step, and ultimately get the correct characters XXX, then use an ASCII Converter bar into the ordinary characters on it

And then is the second And (Select top 1 asc (mid (user, 2,1)) from admin)

Plus behind the url, watches the column name or the first guess solution, return the correct account on behalf of ASCII codes greater than 100, then forward again to guess until the error, take the guess ASCII code ASCII converter to convert it, Chinese is negative, plus asb take the absolute value

And (Select top 1 asb (asc (mid (user, n, 1))) from admin)> 15320

Get after the increase in the number of remember -, otherwise the ASCII converter does not come, the Chinese in the ASCII code is -23423 this, so guess very troublesome

The guess solution speed is slower, but the best, most extensive

Method 2

Background authentication bypasses the vulnerability

Verification of bypass vulnerability is ‘or’ = ‘or’ Background to bypass loopholes, the use of AND and OR is the rules of operation, resulting in logic errors in the background script

For example the administrator account password is admin, then another, such as the background database query statements is

User = request (“user”)

Passwd = request (“passwd”)

Sql = ‘select admin from adminbate where user =’ & ” ‘& user &’ ” & ‘and passwd =’ & ” ‘& passwd &’ ”

Then I use ‘or’ a ‘=’ a do user name password, then the query becomes a

Select admin from adminbate where user = ” or ‘a’ = ‘a’ and passwd = ” or ‘a’ = ‘a’

In this case, according to the operation rules, here a total of four query, then the query result is false or true and false or true, the first operator and then operator or, the end result is true, so you can enter the background

This loophole there must be two conditions, the first: in the background verification code, the account password to the same query is a query, that is similar to

Sql = “select * from admin where username = ‘” & username &’ & “passwd = ‘” & passwd &’

If once the account password is separated from the query, first check the account number, then check the password, so there is no way.

The second is to look at the password plus encryption, once MD5 encryption or other encryption encryption, it depends on the first condition can not, did not reach the first condition, then there is no drama

Method 3

Defense method

For how to prevent SQL injection, I say a few here

If you write anti-injection code, the general is to first define a function, and then write to the inside of the keyword to filter, such as select; “; from; and so on, these keywords are the most commonly used query words, , Then the user’s own data submitted by the structure will not be fully involved in the operation of the database.

Of course, if your site all the data submitted are digital, you can use the methods provided by Kotake

Function SafeRequest (ParaName, ParaType)

‘— incoming parameters —

‘ParaName: Parameter name – character type

‘ParaType: parameter type – numeric (1 for the above parameters is a number, 0 or more parameters of the character )

Dim ParaValue

ParaValue = Request (ParaName)

If ParaType = 1 then

If not isNumeric (ParaValue) then

Response.write “parameter” & ParaName & “must be numeric!”

Response.end

End if

Else

ParaValue = replace (ParaValue, “‘”,’ ” “)

End if

SafeRequest = ParaValue

End function

Then use SafeRequest () to filter parameters, check whether the number of parameters, not the number can not pass.

SQL injection approach is quite flexible, when the injection will encounter a lot of unexpected situations. Can be analyzed according to specific circumstances, the structure clever SQL statement, which successfully obtain the desired data, is the master and the “rookie” the fundamental difference.

SQL injection techniques

Forces an error

It is the motivation of this type of attack to identify the database type, version and other information. Its purpose is to collect the type of database, structure and other information for other types of attacks to prepare, can be described as a preliminary step to attack. Using the application server to return to the default error message and obtain vulnerability information.

Using non-mainstream channel technology

In addition to HTTP response, the data can be obtained through the channel, however, most rely on the channel and database support functions exist, so this technology is not fully applicable to all database platforms. SQL injection of non-mainstream channels are E-mail, DNS and database connections, the basic idea is: the first SQL query package, and then use non-mainstream channel to the information back to the attacker.

Use special characters

Different SQL databases have many different special characters and variables that are unsecured by certain configurations or can be filtered to provide some direction for further attacks by gaining some useful information.

Use conditional statements

This approach can be divided into specific content-based, time-based, error-based three forms. Usually after a regular visit with conditional statements, according to information feedback to determine the target attack.

Use of stored procedures

Through some standard stored procedures, database vendors to expand the functions of the database at the same time, the system can also interact with. Part of the stored procedure can be user-defined. Through other types of attacks collected to the database type, structure and other information, we can build the implementation of the stored procedure command. This type of attack can often achieve remote command execution, privilege expansion, denial of service purposes.

Avoid input filtering

Although some filtering techniques can be used to prevent SQL injection for normal encoding, there are a number of ways to avoid filtering in this case. Techniques commonly used to achieve this include SQL comments and dynamic queries. With truncation, The use of URL encoding and null bytes, the use of case and variants, and nested stripped expressions. By means of these means, the input query can be avoided after the input filter, so that an attacker can get the desired query results.

Inference technique

Ability to specify database schema, extract data, and identify injectable parameters. In this way the attack through the site of the user input feedback on the parameters can be injected, the database model inference, this attack construct the query after the implementation of the answer is only true and false. Based on the inferred injection method can be divided into time measurement injection and blind injection of two. The former is to add statements in the injection statement, such as “waitfor 100”, according to the results of this query the time of the success of the injection and the range of data derived to determine the latter is mainly “and l = l”, “and l = 2 “two classic injection method. These methods are for some indirect association and can get a response to the question, and then through the response information to infer the desired information, and then attack.

SQL injection prevention

SQL injection into the understanding of how to prevent SQL injection? How to further prevent the proliferation of SQL injection? Through some reasonable operation and configuration to reduce the risk of SQL injection.

Use parameterized filter statements

To prevent SQL injection, the user’s input can never be directly embedded in the SQL statement. On the contrary, the user’s input must be filtered, or use a parameterized statement. Parameterized statements use parameters instead of embedding user input into the statement. In most cases, SQL statements can be fixed. The user input is then limited to one parameter.

Enter the validation

Check the legitimacy of the user input, make sure the input contains only legitimate data. Data checking should be performed both on the client and server side to perform server-side validation in order to compensate for the fragile security of the client-side authentication mechanism.

In the client, the attacker is entirely possible to obtain the source code of the page, modify the validation of the legitimacy of the script (or directly delete the script), then the illegal content submitted to the server through the modified form. Therefore, to ensure that the verification operation has indeed been implemented, the only way is to perform authentication on the server side. You can use a number of built-in validation objects, such as the Regular Expression Validator, which can automatically generate client-side script for validation, although you can also insert server-side method calls. If you do not find an existing validation object, you can create your own custom Validator.

Error message processing

Prevent SQL injection, but also to avoid some detailed error messages, because hackers can take advantage of these messages. A standard input validation mechanism is used to verify the length, type, statement, and enterprise rules of all input data.

Encryption processing

The user login name, password and other data encryption to save. Encrypt the data entered by the user, and then compare it with the data stored in the database, which is equivalent to the user input data were “disinfected” processing, the user input data no longer have any special significance to the database, Prevents an attacker from injecting SQL commands.

Stored procedures to perform all the inquiries

SQL parameter passing will prevent an attacker from exploiting single quotes and hyphens. In addition, it also makes the database permissions can be limited to only allow a specific stored procedure execution, all user input must be called the stored procedure of the security context, so it is difficult to happen injection attacks.

Use a professional vulnerability scanning tool

Attackers are currently automatically searching for targets and implementing attacks, and their technologies can even be easily applied to vulnerabilities in other Web architectures. Companies should invest in a number of professional vulnerability scanning tools, such as the famous Acunetix Web vulnerability scanners and so on. A complete vulnerability scanner differs from network scanning programs in that it specifically looks for SQL injection vulnerabilities on Web sites. The latest vulnerability scanners can find the latest discovered vulnerabilities.

Ensure database security

Lock your database security, only to access the database web application features the minimum permissions required to revoke unnecessary public license, the use of strong encryption technology to protect sensitive data and maintain the audit trail. If the web application does not need access to some tables, verify that it does not have access to those tables. If the web application only needs read-only permission, then it is prohibited on the table drop, insert, update, delete permissions, and to ensure that the database hit the latest patch.

Safety review

Before deploying an application, always do a security review. Establish a formal security process, and each time to do updates, to do a review of all the code. The development team will do a detailed security review before it goes live, and then after a few weeks or months they do minor updates, they skip the security review. “It’s a small update , We do the code review later. ” Always insist on safety reviews.