Reading files through $ _GET

I have a php script that takes a relative path through $_GET, reads this file and creates its thumbnail. I do not want the user to be able to read any file from the server. Only files from a specific directory are allowed, otherwise the script should exit().

Here is my folder structure:

files/ <-- all files from this folder are public
my_stuff/ <-- this is the folder of my script that reads the files

My script is accessed via mydomain.com/my_stuff/script.php?pathname=files/some.jpg. What should not be allowed eg:mydomain.com/my_stuff/script.php?pathname=files/../db_login.php

So, here is the relevant part of the script in folder my_stuff:

...
$pathname = $_GET['pathname'];
$pathname = realpath('../' . $_GET['pathname']); 

if(strpos($pathname, '/files/') === false) exit('Error');
...

I am not quite sure about this, it does not seem to me too safe. Anyone with a better idea?

+3
source share
5 answers

( , , ):

$pathname = realpath('../' . $_GET['pathname']);
$rootpath = realpath('../files/');

if (strpos($pathname, $rootpath) !== 0) exit('Error');
+2

realpath() ( "../" ), , .

( , / , , ):

$basedir = "/etc/www"; 
$allowed = "/etc/www/files";

$pathname = realpath($basedir."/".$_GET["pathname"]);

if (!$pathname) 
 die ("Unknown file path");

// Check whether $pathname begins with $allowed (= is a sub-directory)
if (substring($pathname, 0, strlen($allowed)) != $allowed)
 die ("illegal access!");

, .

+3

,
basedir , script.

$basedir=dirname(__FILE__)."/";
$systemdir=realpath($_SERVER['DOCUMENT_ROOT'].$dir)."/";
if (substr($systemdir,0,strlen($basedir)) !== $basedir) {

... :)

0

./ ../ $_GET['pathname'], , . , realpath ( .. . "" ), strpos (, ) , , /files/ ,

/site/my_stuf/secretfile.txt /files/

( "", "secretfile.txt" ( ) dir, ... , , , - ... , , , , )

, , ../ GET; , files, files/ , , ../, ?

I donโ€™t know if this is all paranoid (or a better solution exists), but I used a similar approach for url-based directory / files, which allows โ€œdirectโ€ access to my siteโ€™s subdirectory, and I certainly wanted to be sure that there was no way to escape from this directory.

0
source

NB. The answers provided using realpath are fine, however, they should mention that realpath does not work the same in all server options.

0
source

Source: https://habr.com/ru/post/1749022/


All Articles