Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sanitize $_GET variables to prevent path injection?

Tags:

security

php

What is the best way to sanitize $_GET[''] request? I want to allow downloading files from one directory only.

$baseDir = "/home/html/xy.com/public_html/downloads/";    
$path = realpath($baseDir . $_GET['file']);  

What is the next step?

like image 246
Adrian Avatar asked Dec 04 '22 19:12

Adrian


2 Answers

Here's what I would do after the lines you have there:

if (dirname($path) === $baseDir) {
    //Safe
}

http://php.net/dirname

Basically, do a check before sending anything that the file is actually in that one path you support. Note, you will also have to add your own / before the filename (in $path) and remove it from your $baseDir definition, as dirname() won't leave a trailing path separator.

like image 99
Brad Avatar answered Dec 08 '22 00:12

Brad


Instead of post-checking that no relative path fragments were present, it's easier to just strip them right away. Just use basename() immediately when you fetch the value:

$baseDir = "/home/html/xy.com/public_html/downloads/";    
$path = realpath($baseDir . basename($_GET['file']));  

That already guarantees that it can't move upwards or downwards from your base directory.

like image 33
mario Avatar answered Dec 07 '22 23:12

mario