Anti-SQL injection _php Tutorial

Source: Internet
Author: User
Tags mssql server
Go SQL Injection
SQL Injection
Many web developers do not notice that SQL queries can be tampered with, thus treating SQL queries as trusted commands. It is not to be said that SQL queries can bypass access control, thereby bypassing authentication and permission checks. Furthermore, it is possible to run commands at the host OS level through SQL queries.
Direct SQL command injection is a common technique used by attackers to create or modify existing SQL statements to achieve hidden data, or to overwrite critical values, or even perform database host operating system commands. This is achieved by using the application to obtain user input and combine it with static parameters into SQL queries. Here are some real examples.
The attacker could create a new superuser in the database because of the lack of validation of the input data and the use of a superuser or other database account that is authorized to create a new user.
Example#1 a piece of code that implements the paging display of data ... can also be used to create a super User (PostgreSQL system).
Copy PHP content to clipboard
PHP Code:
$offset = $argv [0]; Note that there is no input validation!
$query = "SELECT ID, name from the products ORDER by name, OFFSET $offset;";
$result = Pg_query ($conn, $query);


The average user clicks on the "previous page", "next page" link $offset the bin value. The original code would only consider $offset to be a numeric value. However, if someone tries to process the following statement through UrlEncode () and then joins the URL:
0;
Insert into Pg_shadow (USENAME,USESYSID,USESUPER,USECATUPD,PASSWD)
Select ' Crack ', usesysid, ' t ', ' t ', ' crack '
From Pg_shadow where usename= ' postgres ';
--
Then he can create a super user. Note that 0; Just to provide a correct offset to complement the original query so that it does not go wrong.
Note:--is an annotation tag for SQL that can be used to tell the SQL interpreter to ignore the following statements.

It's a practical way to get a password for a page that displays search results. The only thing an attacker has to do is to find out which variables are being submitted for SQL statements and improperly handled. Variables such as these are often used in conditional statements in SELECT queries, such as where, ORDER by, LIMIT, and OFFSET. If the database supports the UNION construct, an attacker could also attach a full SQL query to the original statement to get the password from any data table. Therefore, it is important to encrypt the password field.
Example#2 Show Article ... and some passwords (any database system)
Copy PHP content to clipboard
PHP Code:
$query = "SELECT ID, name, inserted, size from products
WHERE size = ' $size '
ORDER by $order LIMIT $limit, $offset; ";
$result = Odbc_exec ($conn, $query);


You can add another SELECT query based on the original query to get the password:
'
Union select ' 1 ', concat (uname| | ' -'|| passwd) as name, ' 1971-01-01 ', ' 0 ' from usertable;
--
If the above statement (using ' and--) is added to any of the variables in the $query, then it will be troublesome.
UPDATE in SQL is also subject to attack. This query may also be inserted or appended to another complete request as in the example above. But attackers prefer to start with SET clauses so that they can change some of the data in the data table. In this case, you must know the structure of the database in order to modify the query successfully. You can guess the field by the name of the variable on the form, or brute force. There are not many naming methods for fields that hold user names and passwords.
Example#3 Reset Password ... To get more permissions (any database system)
Copy PHP content to clipboard
PHP Code:
$query = "UPDATE usertable SET pwd= ' $pwd ' WHERE uid= ' $uid ';";


But a malicious user would have ' or uid like '%admin% '; --The value of the variable is submitted to the $uid to change the password of the admin, or the $PWD value is submitted as "hehehe", admin= ' yes ', trusted=100 "(there is a space behind) to get more permissions. If you do this, the query statement actually becomes:
Copy PHP content to clipboard
PHP Code:
$uid = = ' or uid like '%admin% '; --
$query = "UPDATE usertable SET pwd= ' ... ' WHERE uid= ' or uid like '%admin% '; --";
$pwd = = "Hehehe", admin= ' yes ', trusted=100 "
$query = "UPDATE usertable SET pwd= ' hehehe ', admin= ' yes ', trusted=100 WHERE
...;";


The following scary example shows how to execute system commands on some databases.
Example#4 the operating system of the host where the attack database resides (MSSQL Server)
Copy PHP content to clipboard
PHP Code:
$query = "SELECT * FROM products WHERE id like '% $prod% '";
$result = Mssql_query ($query);


If the attack is committed a% ' exec master. xp_cmdshell ' net user Test Testpass/add '--as a variable $prod value, then $query will become
Copy PHP content to clipboard
PHP Code:
$query = "SELECT * FROM Products"
WHERE id like '%a% '
EXEC master. xp_cmdshell ' net user Test Testpass/add '--";
$result = Mssql_query ($query);


The MSSQL server executes this SQL statement, including the one behind it that is used to add users to the system. If the program is run with SA and the MSSQLSERVER service has sufficient permissions, the attacker can obtain a system account to access the host.
Note: Although the above examples are for a particular database system, this does not mean that similar attacks cannot be performed on other database systems. Using different methods, various databases are likely to suffer.

Precautions
Some may be self-comforting, saying that attackers need information about the structure of the database to implement the above attack. Yes, that's true. But no one can guarantee that the attackers will not get the information, but they get the risk that the database is compromised. If you are using an open source package to access a database, such as a forum program, the attacker will be very tolerant of the relevant code. If the code is poorly designed, the stakes are even greater.
These attacks are always based on the discovery of code that is not strong in security sense. Therefore, never trust the data entered by the outside world, especially from the client, including selection boxes, form hidden fields, and cookies. As in the first example above, even a normal query can cause disaster.
Never use a superuser or owner account to connect to the database. Account with restricted permissions. The
checks whether the input data has the desired data format. PHP has many functions that can be used to check input, from simple variable functions and character type functions (such as is_numeric (), Ctype_digit ()) to complex Perl-compatible regular expression functions.
If the program waits for a number to be entered, consider using Is_numeric () to check it, or use Settype () to convert its type, or use sprintf () to format it as a number.
Example#5 A more secure way to implement paging
copy PHP content to the Clipboard
PHP code:
Settype ($offset, ' Integer ');
$query = "SELECT ID, name from the products ORDER by name, OFFSET $offset;";
//Note%d in the format string, if%s is meaningless
$query = sprintf ("Select ID, name from the products ORDER by name", "OFFSET%d;", br> $offset);


Use database-specific, sensitive character escaping functions (such as mysql_escape_string () and sql_escape_string ()) to escape non-numeric data submitted by the user. Addslashes () and Str_replace () can replace this work if the database does not have a special sensitive character escaping feature. To take a look at the first example, this example shows that it is not enough to enclose the static part of the query, and the query is easily compromised.
Do anything to avoid showing any confidence in the database, especially the database structure. See Error reporting and error handling functions.
You can also choose to abstract several library accesses using attributes such as stored procedures for the database and predefined pointers, so that users do not have direct access to the data tables and views. But this approach has other implications.
In addition, it is also a good idea to use code or database systems to save the query log when allowed. Obviously, the log does not prevent any attacks, but it can be used to track which program has been attempted to attack. The log itself is useless, so check the information contained therein. After all, more information is always better than nothing.

http://www.bkjia.com/PHPjc/629757.html www.bkjia.com true http://www.bkjia.com/PHPjc/629757.html techarticle []sql Inject SQL injection Many Web developers do not notice that SQL queries can be tampered with, so SQL queries are treated as trusted commands. Not surprisingly, SQL query can bypass the visit ...

  • 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.