Home > Article > Backend Development > PHP Security-Remote File Risk
PHP has a configuration option called allow_url_fopen, which is enabled by default. It allows you to point to many types of resources and treat them like local files. For example, you can get the content (HTML) of a page by reading the URL:
<?php $contents = file_get_contents('http://example.org/'); ?>
As discussed in Chapter 5, serious vulnerabilities can arise when tainted data is used to point to files in include and require. In fact, I consider this vulnerability to be one of the most dangerous in PHP applications because it allows an attacker to execute arbitrary code.
Although slightly less severe, a similar vulnerability can result from using tainted data in a standard file system function:
<?php $contents = file_get_contents($_GET['filename']); ?>
## This example enables the user to manipulate file_get_contents( ) behavior so that it obtains the contents of the remote resource. Consider a request similar to the following:
http://www.php.cn/ ... mple.org%2Fxss.html
This leads to a situation where the value of $content is tainted. Since this value is obtained indirectly, this fact is likely to be ignored. This is why the defense-in-depth principle treats the file system as a remote data source and the value of $content as input, so your filtering mechanism can potentially turn things around.
Because the $content value is contaminated , it can lead to a variety of security vulnerabilities, including cross-site scripting vulnerabilities and SQL injection vulnerabilities. For example, here is an example of a cross-site scripting vulnerability:
<?php $contents = file_get_contents($_GET['filename']); echo $contents; ?>
# # The solution is to never point to a filename with tainted data. Always filter input and make sure the data is filtered before it points to a filename:
<?php
$clean = array();
/* Filter Input ($_GET['filename']) */
$contents =
file_get_contents($clean['filename']);
?>
Although there is no guarantee that the data in $content is completely flawless, this gives a reasonable guarantee that the file you are reading is exactly the file you intended to read, and not one specified by the attacker. To enhance the security of this process, you also need to treat $content as input and filter it before use.
<?php
$clean = array();
$html = array();
/* Filter Input ($_GET['filename']) */
$contents =
file_get_contents($clean['filename']);
/* Filter Input ($contents) */
$html['contents'] =
htmlentities($clean['contents'], ENT_QUOTES, 'UTF-8');
echo $html['contents'];
?>
## The above process provides a powerful method to prevent various attacks, and is recommended for use in actual programming.
The above is the content of PHP security-remote file risks. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!