PHP Page Inclusion Hardening

chmood


One of Web App's Bugs is Remote File Inclusion. It bug can be easly exploitation because web developer is forgot to validate the requested page before including the page. So a hacker can put a remote script to the requested variable.
example:

http://site.com/?page=http://hack.er/script.txt??

so, it included by the script

In a moment of page processing, hacker's script included by the server and it processed. If it does, it can be called a hacker got the server. And administrator can only say dead!! Dead without blood, only tears.

Because of that, validate a requested page before include it is very important. It is a simple only, but sometimes overlooked or forgotten. I will make an example how to validate a requested page. A simple way to validate the requested page for inclusion.

Let's Start !

$file is a variable which i will include it into my page. $file is send by "get" method. this is standart include page from "get" variable.

$file = $_GET['file'];


Before validation, $file must be clear from "injected" variable like rfi or lfi. So, laundry it first.

$file = $_GET['file'];

$file = str_replace("http://","",$file);

$file = str_replace("/","",$file);

$file = str_replace("..","",$file);

now $file is clear from injected variable. See it.

$file = "http://hack.er/evil.txt";

after laundry, $file is hack.erevil.txt

and it if trying lfi exploit.

$file = "../../../../../../../etc/passwd";

after laundry, $file is etcpasswd;

$file is clear. next step.

Simple method to validate a page is check exists page in a directory. But checking to the directory is use more server's memory. To decrease used memory, i will check exist file if $file is valid first. valid page is defined in an array where contain a list of valid page.

$validpage = array("article","contact","news","product");

article, contact, news, product is a valid page. Put any valid page in $validpage.

first validation, check $file. if $file is found in $validpage, it is valid page.


$file = (in_array($file,$validpage))?$file:index;

if $file is not in $validpage, values of $file is replace with "index".

after this step, $file have contained with a valid page. now, i will check if it is existed file. I do not want include unexisted file, do not let an error on page, it will give another clue for hacker.

$file = ((file_exists($file.".php"))?$file:index;

Done. $file are filtered and validated. Now I can include $file without worried.

include($file.".php");


Do not forgot to put an index.php file, because it is your default page if file not valid or not exist.



And now, I can sleep in peace and sweet dreams.

Thanks.

ArRay
Komentar