Null Byte Injection – How hackers can upload malicious scripts and bypass security.

In this post, I will explain how a hacker can bypass file upload restrictions to upload arbitrary files using null byte injection. To fully understand the null byte vulnerability, we must take a look at how the C language handles strings. This is important because at some point, PHP relies on C/C++ functions to handle high-level code at a system level. A null byte can be represented in several different ways depending on the character set. In Unicode, its \u0000. In a URL, it is %00. In C, it is \0 .

What is the purpose of a null byte?

In short, a null byte is a way to denote the end of a string.

To write a string in PHP, we simply write

$string = ‘hello’;

Unfortunately, C does not have a string data type. To write a string in C/C++ we must use an array.

Char string[5];
string[0]=’h’;
string[1]=’e’;
string[2]=’l’;
string[3]=’l’;
string[4]=’o’;
string[5]=’\0′;

Here we write the last character as a null byte. So the program reads the string until the null byte is reached. As we know, PHP uses the underlying C functions for filesystem related operations. This creates a problem if the developer is unaware of this sort of vulnerability.

Example 1: Using a file upload input to gain shell access to a server
This is a file upload field on a website that accepts .dat files only. To ensure its of proper filetype, it automatically appends the .dat to any file, so uploading script.php will turn out script.php.dat

We want to bypass the security check that verifies the filetype to upload our PHP script shell.php, which contains code that will help us access the back end functions of the victim server.

$file = $_GET[‘file’];
require_once(“/var/www/data/$file.dat”);

A normal request will then look like:
https://bostonwebgroup.com/script.php?file=somedata.dat

A malicious request could look like:
https://bostonwebgroup.com/script.php?file=shell.php%00.dat

As you can see, the file still ends in .dat , passing possible php whitelist checks. Once processed, the %00 chops the .dat from the filename leaving our properly named script.php for us.

The attacker could also type:
https://bostonwebgroup.com/script.php?file=../../../etc/passwd%00
For a list of your server passwords

We’ve identified a series of methods to prevent and catch these attempts – don’t let your website get compromised. Use our services to maintain high levels of security.