Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the principles of SQL injection

2025-03-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article is to share with you about the principles of SQL injection, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

What is sql injection?

1. What is sql injection?

The so-called SQL injection is to deceive the server into executing malicious SQL commands by inserting the SQL command into the Web form to submit the domain name or enter the query string requested by the page. For example, most of the previous film and television websites leaked the VIP member password through the query character submitted through the WEB form. Such forms are particularly vulnerable to SQL injection attacks. Sql injection attacks occur when an application uses input to construct dynamic sql statements to access the database. Sql injection also occurs if your code uses stored procedures that are passed as strings containing unfiltered user input. Hackers can get access to the website database through SQL injection attacks, and then they can get all the data in the website database. Malicious hackers can tamper with the data in the database and even destroy the data in the database through SQL injection. As a web developer, you hate this kind of hacking. Of course, it is necessary to understand the principle of SQL injection and learn how to protect your website database through code.

2. The cause of sql injection

Sql injection attack refers to the use of loopholes in design to run Sql statements on the target server and other attacks. The failure to validate the data entered by users when dynamically generating Sql statements is the main reason for the success of Sql injection attacks. For java database connection JDBC, the SQL injection attack is valid only for Statement and not for PreparedStatement, because PreparedStatement does not allow the logical structure of the query to be changed at different insertion times.

For example, the SQL statement to verify the existence of a user is:

Username 'and pswd=' password

If you enter:'or 1'in the user name field or'or 1'in the password field

Validation will be bypassed, but this method works only for Statement, not for PreparedStatement. Compared with Statement, it has the following advantages:

1. Guard against injection attack

two。 The speed of multiple runs is fast.

3. Prevent database buffer overflow

4. The code is readable and maintainable.

These four points make PreparedStatement the first choice for statement objects that access the database, but the disadvantage is that flexibility is not good enough, and Statement is still necessary in some cases.

3. Sql injection principle.

Let's talk about the principle of sql injection to give the reader a perceptual understanding of sql injection attacks. As for other attacks, the principles are the same.

SQL injection enables an attacker to bypass the authentication mechanism and take complete control of the database on the remote server. SQL is the abbreviation of structured query language, and it is the de facto standard for accessing databases. At present, most Web applications use SQL database to store application data. Almost all Web applications use some kind of SQL database in the background. Like most languages, SQL syntax allows database commands to be mixed with user data. If the developer is not careful, user data may be interpreted as commands, so that remote users can not only enter data into the Web application, but also execute arbitrary commands on the database.

There are two main forms of SQL injection attacks. One is to insert the code directly into the user input variable that is concatenated with the SQL command and causes it to execute. The example cited by the author above is the use of this method. Because it is directly bundled with SQL statements, it is also called direct injection attack. The second is an indirect attack method that injects malicious code into strings to be stored in a table or as original data. A dynamic SQL command is concatenated in the stored string to execute some malicious SQL code. The injection process works by terminating the text string ahead of time and then appending a new command. Take the direct injection attack as an example. That is, when the user enters a variable, the current statement ends with a semicolon. Then insert a malicious SQL statement. Because the inserted command may append another string before execution, attackers often terminate the injected string with the comment mark "-". During execution, the system will assume that the statement bit is annotated after that, so the subsequent text will be ignored and will not be compiled and executed.

4. A simple example of SQL injection attack:

Here we give a more common example to briefly illustrate the principle of sql injection. Suppose we have a users table with two fields username and password. In our java code, we beginners are used to using sql splicing for user authentication. For example, "select id from users where username ='" + username + "'and password ='" + password + "here both username and password are the data we access from the web form. Let's take a look at a simple injection. If we type'or 1 in the input box of username in the form, and enter something casually in the form of password, if we enter 123 here. At this point, the sql statement we are going to execute becomes select id from users where username =''or 1, and password-and password = '123. Let's take a look at this sql, because 1 is true, and then and password =' 123'is commented out. So sql validation is skipped completely here.

Second, how to defend against sql injection attacks

1. A set of precompiled statements is used, which has the built-in ability to handle SQL injection, as long as it uses its setXXX method to pass values.

Benefits of use:

(1)。 Readability and maintainability of the code.

(2). PreparedStatement improves performance as much as possible.

(3)。 The most important point is that the security is greatly improved.

String sql= "select * from users where username=? and password=?; PreparedStatement preState = conn.prepareStatement (sql); preState.setString (1, userName); preState.setString (2, password); ResultSet rs = preState.executeQuery ()

Principle: sql injection only destroys the preparation (compilation) process of sql statements, but PreparedStatement is ready, the execution phase only treats the input string as data, and no longer parses and prepares sql statements, so the problem of sql injection is avoided.

two。 Use regular expressions to filter incoming parameters

Regular expression:

Private String CHECKSQL = "^ (. +)\\ sand\\ s (. +) | (. +)\\ sor (. +)\\ s $"

Determine if there is a match:

Pattern.matches (CHECKSQL,targerStr)

Here are the specific regular expressions:

Detect the regular expression of SQL meta-characters: / (\% 27) | (\') | (\ -) | (\% 23) | (#) / ix

Fixed the regular expression for detecting SQL meta-characters: / ((\% 3D) | (=)) [^\ n] * ((\% 27) | (\') | (\ -) | (\% 3B) | (:)) / I

Regular expression for a typical SQL injection attack: /\ w * ((\% 27) | (\')) ((\% 6F) | o | (\% 4F)) ((\% 72) | r | (\% 52)) / ix

Detect SQL injection. Regular expression of UNION query keyword: / (\% 27) | (\') union/ix (\% 27) | (\')

Regular expression for detecting MS SQL Server SQL injection attacks: / exec (\ s |\ +) + (s | x) p\ w+/ix

Wait... ..

In fact, you can simply use the replace method to achieve the appeal function:

Public static String TransactSQLInjection (String str) {return str.replaceAll (". * ([';] + | (-) +). *", ");}

3. String filtering

A more general method: (| | parameters can be added according to the needs of your own program)

Public static Boolean sql_inj (String str) {String inj_str = "'| and | exec | insert | select | delete | update | * |% | chr | mid | master | truncate | char | declare |; or |-| + |,"; String inj_stra [] = split (inj_str, "|"); for (int iTun0; I)

< inj_stra.length ; i++ ) { if (str.indexOf(inj_stra[i])>

= 0) {return true;}} return false;}

Call this function in 4.jsp to check whether the package is illegal.

Prevent SQL from injecting from URL:

Sql_inj.java Code:

Package sql_inj;import java.net.*;import java.io.*;import java.sql.*;import java.text.*;import java.lang.String;public class sql_inj {public static Boolean sql_inj (String str) {String inj_str = "'| and | exec | insert | delete | delete | count | * |% | chr | mid | master | truncate | char | declare |; or |-| + |," / / you can also add String [] inj_stra=inj_str.split ("\\ |"); for (int iTunes 0; I) to things here.

< inj_stra.length ; i++ ) { if (str.indexOf(inj_stra[i])>

= 0) {return true;}} return false;}}

Add the client judgment code to the 5.JSP page:

Use javascript to mask unsafe characters on the client side

Function description: check whether it contains "'", "\", "/"

Parameter description: string to check

Return value: 0: yes: 1: no

Function check (a) {return 1; fibdn = new Array ("'", "\", "/"); for (ii=0; ii < I; ii++) {for (jj=0; jj < j) {temp1=a.charAt (jj) Temp2=fibdn [ii]; if (tem'; p1==temp2) {return 0;} return 1 } these are the principles of SQL injection, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report