Tuesday, September 20, 2011

Local file inclusion and Null Byte prevention and it's consequences

As you may know or not know, there is a vulnerability called Local File Inclusion, that is used for a close time to gain shell access and even server control.
How does Local File Inclusion works?


imagine you are dynamically including a part of page, in PHP it may looks as next:
include($_GET['file']);
//this one validated as even remote inclusion
ok, you got it, you going to jail the directory to:
include(dirname(__FILE__).'/'.$_GET['file']); 
// jailed, but now Local File Inclusion present in script.
in 2 previous example we are able to do www.evil.host/script.php?file=../../etc/passwd
and get access to the passwd file of linux systems, the problem that it is almost in all systems locked, but there is a lot of other useful files to view this way.

Why i mentioned Null Byte Poisoning in the head of the post...
we go to jail this even more, to strict to file extension
include(dirname(__FILE__).'/'.$_GET['file'].'.php');
last example looks perfect protection against any inclusion type, but not all good, we left Local Inclusion with a help of null by poisoning that works as follows:
www.evil.host/script.php?file=../../etc/passwd%00
the %00 is a null byte, after this the string will be terminated and .php will get thrown away
We can get access to potentially dangerous files to access from outside.

How To Prevent?
//do this, but before filter you $_GET['file'] also implement in additional to usual verification next:
$_GET['file'] = stripcslashes( str_replace( chr(0), '', $_GET['file'] ) );
include( dirname(__FILE__).'/'.$_GET['file'].'.php' );

Now you will become protected against remote/local file inclusions using even null byte poisoning.
First: chr(0) is a null byte, getting stripped and then stripCslashes, char C is a special strip that strips "C" like \n, \r ..., octal and hexadecimal representations.
Very Important to know the consequences of such attacks if the hole is not locked, to read about this please follow and read Gaining Shell Access via Local File Inclusion Vulnerabilities in Brian Haddock's Blog.

I will describe Remote file inclusion, how to implement and how to prevent next time.

No comments: