php methods and risks for opening remote files and solutions

  • 2020-11-18 06:08:40
  • OfStack

PHP has a configuration option called allow_url_fopen, which is valid by default. It allows you to point to many types of resources and process them as if they were local files 1. For example, by reading URL you can get the contents of a particular page (HTML). See the code below

<?php
$contents = file_get_contents('https://www.ofstack.com/');
?>

Serious vulnerabilities occur when contaminated data is used for file pointing to 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 the severity level is one point lower, a similar vulnerability can occur when contaminated data is used in a standard filesystem function:

<?php
$contents = file_get_contents($_GET['filename']);
?>

This example enables a user to manipulate the behavior of file_get_contents() so that it can retrieve the contents of a remote resource. Consider a request like the following:
http://example.org/file.php?file ... mple.org%2Fxss.html
This leads to a situation where the value of $content is contaminated, and since this value is obtained indirectly, this fact is likely to be ignored. This is also the depth precaution principle that sees the file system as a remote data source and the value of $content as input, so that your filtering mechanism can potentially be a game changer.
Because the $content value is contaminated, it can cause 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 contaminated data. Always filter input and be sure to filter before the data points to a file name:

<?php
$clean = array();
/* Filter Input ($_GET['filename']) */
$contents = file_get_contents($clean['filename']);
?>

While there is no guarantee that the data in $content is completely free of problems, this gives a reasonable assurance that the file you are reading is the one you want to read, not the one specified by the attacker. To enhance the security of this process, you also need to treat $content as input and filter it before using it.

<?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 way to protect against multiple attacks and is recommended for practical programming.

Related articles: