Php security-how to securely Use PHP $ _ GET

Source: Internet
Author: User
I am a newbie. in PHP security code, I mentioned "Don't use $ _ GET directly", and I also mentioned "You can try php. enable magic_quotes_gpc in ini, so that all special characters passed in by the user GET, POST, and COOKIE will be escaped. "I am very confused, whether to enable magic_quote... I am a newbie. in PHP security code, I mentioned "Don't use $ _ GET directly", and I also mentioned "You can try php. enable magic_quotes_gpc in ini, so that all special characters passed in by the user GET, POST, and COOKIE will be escaped. "I am very confused. Do you want to enable magic_quotes_gpc to directly use $ _ GET?

As shown in the following example, the code is not safe because it is not verified, but does not know how to improve it. I hope you can help me. Thank you.


  

Reply content:

I am a newbie. in PHP security code, I mentioned "Don't use $ _ GET directly", and I also mentioned "You can try php. enable magic_quotes_gpc in ini, so that all special characters passed in by the user GET, POST, and COOKIE will be escaped. "I am very confused. Do you want to enable magic_quotes_gpc to directly use $ _ GET?

As shown in the following example, the code is not safe because it is not verified, but does not know how to improve it. I hope you can help me. Thank you.


   

You want the filter_input function. Read the following manual:

Http://www.w3school.com.cn/php/func_filter_input.asp

The intval parameter of a numeric value is forced to integer other parameter values for filtering or escape protected function zaddslashes ($ string, $ force = 0, $ strip = FALSE) {if (! Defined ('Magic _ QUOTES_GPC ') {define ('Magic _ QUOTES_GPC', '');} if (! MAGIC_QUOTES_GPC | $ force) {if (is_array ($ string) {foreach ($ string as $ key => $ val) {$ string [$ key] = $ this-> zaddslashes ($ val, $ force, $ strip) ;}} else {$ string = ($ strip? Stripslashes ($ string): $ string); $ string = htmlspecialchars ($ string) ;}} return $ string ;}

I usually use zaddslashes for $ _ POST $ _ GET, and then integer parameter values are rounded to prevent XSS and SQL injection.

HTTP header information: the IP address, browser information, and so on are also escaped to prevent HTTP header injection.

When magic_quotes_gpc is enabled, the Image Upload will be affected, and the content will be automatically escaped by quotation marks.

Note that magic_quotes_gpc configuration has been removed after PHP5.5 is included.

In addition, it is best to perform keyword filtering on the server. Mysql creates users and grants permissions for the databases used by the business.

You can put your own application on the server and install a sqlmap for injection. The above steps are generally not involved, at least not getshell.

Wooyun white hat passed...

1. Something formatted like a user name should be obtained and verified immediately using a regular expression, suchpreg_match('/\A\w{6,14}\z/', $user)Verify that it is 6 ~ 14-digit, letter, and underline. Do not use the built-in filter.

2. Do not usemysqlTo use a functionmysqliAnd it is better to perform parameterized query insteadaddslashesThe latter may have Encoding Problems.

3. When html is outputhtmlspecialcharsThis function can specify the encoding. Or you can use the ready-made template engine.

4. Use it forcibly when comparing stringsstrcmpDo not use the double equal sign.

5. Do not use$_REQUEST.

This prevents 95% attacks. Asmagic_quotes_gpcIt should have been abandoned.

Currently, these books on the market are really harmless. You can draw a conclusion or the landlord has not read them carefully. Why is it insecure to directly use $ _ GET $ _ POST?

After reading the example of the landlord, we should directly use $ _ GET on the concatenated SQL statement. This is definitely not safe, so the core information should be: it is not safe to directly use the content entered by users such as $ _ GET/$ _ POST for SQL concatenation. How can this problem be avoided?

For example:

sqlselect * from user where username= "$_GET['username']"

If the username submitted by the user is

sql" 0 or true or username ="

Then it will become like this:

sqlselect * from user where username = "0" or true  or username=""

All user records are returned. Of course, this is just a rough example. In fact, XSS should be familiar with code or guess the running logic.

The simplest filtering method is to use the mysql_real_escape_string function.

Magic_quotes is the most failed improvement of php and is now obsolete. Even a lower version of PHP must be disabled.

If $ _ GET
First, determine whether it is null.
Then judge the value
For example:
If you only accept numbers, use the php built-in function is_numeric.

Generally, GET only transmits an identifier.
In short, verify that the passed variables are your expected values before the database or other operations.

You can filter post or get requests first. php has built-in functions to filter requests.

I agree that there should be a filter on the second floor, but it is definitely not possible for the system to come with it. It is best to perform filtering and other processing based on the situation.

To prevent XSS attacks, the simplest and most crude method is to use htmlspecialchars (&,",',<,>) To HTML Entity (&"'<>.


    

To prevent XSS attacks, write regular expression filtering by yourself. However, the HTMLPurifier library can complete or remove incomplete tags in addition to filtering XSS code. the Yii framework also uses the XSS filter library.
Http://htmlpurifier.org/download

 purify($html);

The above is to defend against XSS, and the following is to defend against SQL injection:
PDO and MySQLi both provide the function of binding parameter queries, and the purpose of binding parameters is to prevent SQL injection.
Http://php.net/manual/zh/pdo.prepared-statements.php

Many more mature databases support the concept of pre-processing statements.
What is a pre-processing statement? You can think of it as a compiled template for the SQL statement you want to run. It can be customized using variable parameters.
Preprocessing statements can bring two benefits:
1. the query only needs to be parsed (or preprocessed) once, but can be executed multiple times with the same or different parameters.
When the query is ready, the database will analyze, compile, and optimize the plan for executing the query.
For complex queries, this process takes a long time. If you need to repeat the same query multiple times with different parameters, this process will greatly reduce the speed of the application.
By using preprocessing statements, you can avoid repeated analysis, compilation, and optimization cycles.
In short, preprocessing statements consume less resources and therefore run faster.
2. parameters provided to the pre-processing statement do not need to be enclosed in quotation marks, and the driver will automatically process them.
If the application only uses preprocessing statements, it can ensure that SQL injection is not performed.
However, if the other part of the query is constructed by unescaped input, there is still a risk of SQL injection.

Preprocessing statements are so useful that their only feature is that PDO will simulate processing when the driver does not support them.
This ensures that the application can use the same data access mode regardless of whether the database has such a function.

 prepare('SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour');$sth->bindParam(':calories', $calories, PDO::PARAM_INT);$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);$sth->execute();

The preceding variable $ calories is bound to an integer type, and $ color is bound to a string of 12 characters.
MySQLi also provides bind_param like PDO bindParam. In this case, functions such as addslashes and mysqli_real_escape_string are not required, you do not need to rely on magic_quotes_gpc configuration (this configuration has been removed from PHP5.4 ).
When using PDO to operate MySQL, pay attention to disabling analog preprocessing so that the actual preprocessing can be used. In this way, the program can send an SQL template to MySQL for compilation and then pass the parameter to the system for execution, this ensures that these parameters are not injected with SQL statements. the pre-processing of MySQLi extension is the real pre-processing by default.

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

These can be observed through MySQL general_log or WireShark.

 Prepare ('select * FROM users WHERE username =? '); $ Stmt-> bind_param ('s', $ _ GET ['username']); // s indicates that the user name is bound to a string type, and the integer type is I. $ stmt-> execute ();

You can also directly use integer parameters.intval($calories)Get the integer value.

If you want to verify and filter some user input data and do not want to write regular expressions, you can use the filter_input/filter_var function, such as email address verification and IP address verification:
Http://php.net/manual/zh/filter.filters.php

I will answer an irrelevant question:
Are PDO prepared statements sufficient to prevent SQL injection?

Does PDO defend against SQL injection.

We recommend that you check it out first.
The input class library of joomla-framework. The address is here.
You can also use the joomla-framework input class library in your code (do not consider performance issues in the early stage ), first, understand how to process $ _ GET (including $ _ POST, $ _ FILES, and $ _ COOKIE, then, you can choose whether to implement a simple version in the future.

Why is it so common that php cannot implement unified control :(

Why not use PDO?

To prevent injection, we recommend that you use some XSS filtering scripts provided by the security vendor to filter the output.

I think the data type should be well controlled, and the other is to prevent SQL injection attacks.
In addition, it is best to use Session to save the same content and submit SQL statements.

What is $ _ GET? $ _ GET is an array of variables that are passed to the current script through URL parameters. $ HTTP_GET_VARS contains the same information, but it is not a super global variable. (Note that $ HTTP_GET_VARS and $ _ GET are different variables. PHP processes them differently ).

Therefore, the security considerations of $ _ GET () mainly include security considerations when obtaining values and preventing XSS attacks during data filtering, security issues such as SQL Injection in PDO attacks are all threats to system security by passing $ _ GET () values, and it is best to encrypt sensitive data, do not expose it too clearly to prevent risks such as hijacking and exploitation.

Some simple data filtering methods are as follows:

XXS attacks (cross-site scripting attacks) are caused by the absence of strict filtering of user input, therefore, we must block potential dangers before all data enters our website and database. You can use htmlentities () to filter data for illegal HTML code, including single and double quotation marks. But note that htmlentities () is encoded as a ISO-8859-1 by default, and if your illegal script code is another, it may not be filtered out, while the browser can recognize and execute.

For SQL Injection in PDO attacks, in php programming, we can use the following PDO pre-processing binding statements to effectively prevent SQL Injection problems:

$stmt  =  $dbh -> prepare ( "INSERT INTO REGISTRY (name, value) VALUES (:name, :value)" );$stmt -> bindParam ( ':name' ,  $name );$stmt -> bindParam ( ':value' ,  $value );$name  =  'one' ;$value  =  1 ;$stmt -> execute ();

Or use? To achieve the same effect:

$stmt  =  $dbh -> prepare ( "INSERT INTO REGISTRY (name, value) VALUES (?, ?)" );

Xss cannot be prevented. This is the $ _ GET method. If you have encapsulated it, what should you do?

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.