How to prevent SQL injection?

Introduction

SQL injection is to deceive the server to execute malicious SQL statements by inserting SQL commands into the query string of Web form submission or input page request.

Specifically, SQL injection is to use the vulnerabilities of existing applications to inject malicious SQL commands into the background database engine, thereby executing malicious SQL commands and attacking the database or even the entire application.

SQL injection is mainly by entering strings with SQL commands in forms.

The principle of SQL injection

SQL injection attacks are passed into the application by constructing special inputs as parameters, and most of these inputs are some combinations in the SQL syntax. These combinations will change the original SQL statements in the application, so that the original normal SQL becomes malicious. SQL. This is how SQL injection works.

Causes of SQL Injection

  • The application does not carefully filter the data entered by the user, resulting in illegal data intrusion into the system.
  • The SQL operation of the application on the database itself has loopholes.

Example of SQL Injection

The following is a brief description of an example of bypassing login authentication through SQL injection.

Suppose: there is a login authentication SQL as:

SELECT * FROM users WHERE name='user01' AND password=md5('123456')

Now, there is an attacker, in the login form's username, directly enter:

' or 1=1 #

Then, just enter the password, such as abc123, and click login.

At this point, the original SQL becomes malicious SQL:

SELECT * FROM users WHERE name='' or 1=1 #' AND password=md5('abc123')

Note: In MySQL, the # sign indicates a comment.

It can be found that the where condition of this malicious SQL is always true. In this way, the attacker bypasses the login verification and enters the application with the SQL vulnerability.

Of course, SQL injection attacks go beyond just bypassing login authentication.

Measures to prevent SQL injection

SQL injection is very dangerous and we must prevent it.

The following two measures can be combined to effectively prevent SQL injection.

  • Filter user input. Never trust user input, we must carefully and strictly filter the data entered by the user. For example, you can use PHP's htmlspecialchars() function to convert special characters in a string into HTML entity characters.
  • When manipulating the database, use preprocessing and parameter binding. It is recommended to use PDO to operate the database.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324987032&siteId=291194637