Null



Prerequisites



Throughout this paper, many scripting languages will be used to provide proof-of-concept and other examples for the benefit of the reader. A basic understanding of these languages is required in order to completely understand the concepts that are conveyed herein. In addition to a basic understanding of the scripting languages that are utilized in this paper, the reader should be moderately familiar with the structure and workings of web servers and web server sub-components; that being said, a lack of knowledge in these areas should not deter you from reading on. The information contained within this document can, at least, provide you with a basic understanding of impacts of Directory Traversal attacks.

Terms of Use



By reading this document, you agree to the following terms:
  1. You will not use this information to pursue illegal means to any end.
    You will hold neither this paper's author nor its distributors liable for any actions taken that pertain to the information addressed in this document.


Introduction



Definition



A Directory Traversal attack is a type of computer security exploit that involves the use of characters designed to induce a “traverse to parent directory” within a web server, to gain access to files or directories that would otherwise be restricted. The access granted by a Directory Traversal vulnerability may include any combination of the following basic permissions: Read, Write, Execute, and Delete
  • Read Permission – Grants the ability to read the contents of a file or directory.
    Write Permission – Grants the ability to modify the contents of a file or directory, which includes editing file contents, and creating or renaming files or folders within a directory.
    Execute Permission – Grants the ability to execute a file or traverse a directory tree.
    Delete Permission – Grants the ability to delete a file or directory.

History


While the exact origins of the Directory Traversal attack may be unknown, recorded instances of the exploit date back to the late 1980s. Some security professionals suggest that Directory Traversal vulnerabilities have existed for even longer. Despite the lengthy existence of the attack, Directory Traversals did not gain much attention until about the year 2000. Statistics published in Symantec’s biannual Internet Security Threat Reports reveal the top ten attack types most commonly launched against companies from the years 2012-2014. Directory traversal attacks have ranked in the top ten.


Classifications



Directory Traversal attacks are classified as either Site Relative or Server Relative, in accordance with the level of the web server that they penetrate. A conventional web server is comprised of several layers, each of which represents a different stage in the data handling process. Site Relative based Directory Traversal attacks target the layer with which normal users directly interact (site content), known as the Site Application Layer. Server Relative based Directory Traversal attacks target the layer with which normal users do not directly interact (server software and services), known as the Server Software Layer. Although there is a vast difference between the nature of the two layers and their respective applications, there exists almost no difference between the attack-methodologies used to exploit them. Both Site Relative and Server Relative attacks are executed using the same attack principles, and both yield the power to compromise an entire system; however, the difference between the two is great enough to justify their separation into two distinct classes. For that reason, they are explained separately in this paper.

Site Relative


This vulnerability arises when a web application allows a user to supply data designed to induce a “traverse to parent directory” within a web server, to gain access to files or directories that would otherwise be restricted. Typically, web applications that are constructed to read from or write to a file system are gateways to Site Relative Directory Traversal attacks. While file execution and deletion scripts are less commonly encountered, they should not be left unmentioned.

Discovery


A functional approach to detecting openings for Site Relative Directory Traversal attacks is as follows:
  1. Choose a web application that is designed for file handling of any sort. This includes, but is not limited to, file upload/download applications, file sharing/transfer applications, file search/retrieval applications, and blogging/publishing/editing applications.
    Create an arbitrary string that, if executed properly by the target application, would grant access to files in the current directory.
    Submit the string to the application. Review the application's response to the request and annotate any successfully returned data.
    Reformat the arbitrary string mentioned in step two by adding a “traverse to parent directory” as the string’s prefix, followed by a directory and file combination that was returned successfully.
    Submit the string to the application. Review the application's response to the request and annotate any successfully returned data.
    Alter the arbitrary string mentioned in step four so that, if executed properly by the target application, access to files or directories outside of the current directory would be granted. This includes operating system files.
    Repeat steps one through six to test other applications on the target web site.
    Use the methods described in the following sections to exploit Directory Traversal vulnerabilities using the applications that correspond to the instances you recorded.

Exploitation


The purpose of this sub-section is to provide an aid in understanding Directory Traversal exploitation by means of practical examples of attacks. Each of the examples shared below is intended to emulate an attack scenario that has been encountered on the net.

File Readers


Allowing file handling applications to process user supplied data obligates web developers to accept a substantial amount of risk – the risk of system compromise. In some instances, a user should be allowed to submit data to a file handling web application, but without proper precautions, this should be strictly forbidden, as a malicious user could leverage the application to gain access to sensitive file content, restricted directories, and the like.
Unprotected File Readers allow an attacker to bypass the security procedures of a file system to view items that would be disallowed under normal circumstances. Directory Traversal attacks on File Readers may seem limited in their capacity to carry out an effective assault against a web server; nevertheless, they possess the same devastating potential as any other Directory Traversal based attack.

Example No. One:


Target - http://www.FakeGovernmentSite.com/
Intention – Espionage
Espionage is defined as the act of unauthorized acquiring, divulging, transmitting, intercepting, delivering or receiving information concerning the operations of an institution, such as a foreign government, with the intent that the information may be used to the detriment of that institution, or to the advantage of some other entity. In recent times, various institutions have employed hackers to infiltrate the computer systems of foreign organizations to obtain confidential information. The Directory Traversal attack, one of the many tools in a hacker’s arsenal, could be used as a means to acquire information held by foreign governments, corporations, and so on.

What could an attacker gain access to by launching a Directory Traversal attack against a vulnerable government website? Although providing a comprehensive answer to that question is nearly impossible, as the information that governments’ maintain is vast in amount and exists in a constant state of flux, here are a few possibilities:
  • Web administrator/content manager passwords
    Virtual Private Network addresses
    Virtual Private Network username and password combinations
    Personnel Information Files
    Internet Protocol addresses of employees

The information listed above is only a small sample of the data that can be acquired by exploiting this type of vulnerability. Usernames and password combinations can be used to infiltrate internal networks that store sensitive data; Internet Protocol addresses of employees can be used to pinpoint their locations; finally, Personnel Information Files can be used effectively in a social engineering ploy to cause an organization’s employees to think that they are speaking with a legitimate employee of their organization, and thereby persuade them to disclose information.

For example, http://www.FakeGovernmentSite.com/ contains a web application that allows users to retrieve documents pertaining to cybercrime laws. The application’s code is as follows:
Code:
!/Contents of Fake index.php
<head>
</head>
<body>
The Cybercrime Department is an auxiliary organization to FakeGovernment. Its mission is four-fold: first and foremost, to stop those behind the most serious computer intrusions and the spreading of malicious code; second, to incorporate all aspects of information assurance into our cyber operations; third, to be swift and accurate in providing counteractive measures against those who target our national security; and fourth, to promote the proliferation of knowledge related to cyber security and cybercrime laws among our citizens. Please take the time to browse through our online cybercrime knowledgebase below to acquire more information.
<br><br>
<a href="index.php?LawPage=CCL-FC">Piracy Laws</a><br>
<a href="index.php?LawPage=CCL-FC2">Hacking Laws - I</a><br>
<a href="index.php?LawPage=CCL-FC3">Hacking Laws - II</a> <br><br>
<hr color=#CCFF00>

<?php $file = $_GET.'.txt';
if (file_exists($file)) {
include $file;
}
else
{
echo '404 Error - Page not found. Are you trying to hack us?';
}
?>
</body>
</html>


An attacker could complete the following steps to obtain the passwords assigned to the Web administrator and content managers of the website:
  1. Use a dot-dot-slash (Directory Traversal) attack on the vulnerable script.
    Direct the attack to the server password file at: LawPage=../../../../../../../etc/passwd
    Copy the username and password combinations found in the password file.
    Save the copied data to a text file.
    Use a password cracking program, such as John the Ripper, to crack the passwords.
    For the benefit of the reader, I will explain briefly how to use John the Ripper (for Windows users) to crack encrypted passwords:

John the Ripper (for Windows users)
  1. Download the John the Ripper binaries from http://www.openwall.com
    Extract the binaries to a folder of your choosing
    Place a copy of command prompt inside of the folder that contains john.exe
    Place a copy of a text file that contains username and password combinations inside the folder that contains john.exe. Ensure that all combinations are in the correct format within the text file >> username:password
    Open up the copied command prompt and type the following: John.exe <name of text file>
    Wait for John the Ripper to guess the passwords. When the cracking process completes, the decrypted values of the passwords will be displayed.

The cracked passwords could then be used to log into the web server with escalated privileges. In so doing, the attacker would have access to additional information to analyze, and be able to advance in his nefarious mission.


Example No. Two:


Target - http://www.FakeInsuraceSite.com/
Intention – Identify Theft
Social engineering is defined as the act of manipulating people into communicating desired information, performing specified actions, or believing predesigned ideas. The information communicated, actions performed, and ideas believed by the victim of a social engineering scheme could be utilized by a social engineer to satisfy a number of villainous plans, including identity theft.

For example, http://www.FakeInsuraceSite.com/contains a web application that allows users to view their insurance profiles. The application’s code is as follows:

Code:
!/Contents of Fake profile.php
FakeInsuraceSite has been committed to providing its customers with quality insurance at amazingly accommodating rates since 1953, when the company was established. Responding to the needs of our customers with timeliness and effectiveness is what earns us the right to be called the leader in our industry. Insurance is designed to help financially cover potential damages, loss or injuries. It helps protect you, your family, your friends, and others in the event of an accident. Your protection is our mission. If you’re already a customer, but don’t have an online account with us, please enter your information below to search for your information profile. Once you find your information profile, submit it along with the online registration form to sign up for an online account today!
<form action="index.php" method="get">
First Name: <input type="text" name="firstname" />
Last Name: <input type="text" name="lastname" />
<input type="submit" />
</form>

<?php $firstname = $_GET;
$lastname = $_GET;
$name = $firstname.$lastname;
if (!file_exists($name.'.txt')) die("Profile not found. Are you trying to hack us?");
$file = fopen($name.'.txt',"r");
while (!feof($file)) { echo fgetc($file); } fclose($file);
?>



Upon executing the following Path Traversal attack, an attacker would be able to retrieve a list of the customers of the FakeInsuranceSite Company: ../users/ Personal records could then be accessed and utilized, with some additional social engineering, for the impersonation and exploitation of someone from the list. Sensitive personal information presents a social engineer with a number of options, including:
  • Commercial identity theft - Infiltration of corporations
    Criminal identity theft - Escaping legal entanglements
    Financial identity theft - Avoiding financial obligations
    Medical identity theft - Acquiring prescription drugs


File Writers


As was mentioned previously in this paper, without proper safety measures, permitting a web application to read from or write to a file system based on parameters supplied within user requests introduces the risk of site, server, and possibly even network compromise. This is so because any malicious user with decent computer security skills could leverage the application to gain access to and modify the contents of virtually any file, directory, etc.

File writers are especially notorious for allowing attackers to breach defenses set up by uninformed site administrators. Unprotected web applications that support the write permission thoughtlessly authorize the editing of files and file folders. This creates a huge array of opportunities for hackers to gorge themselves with.

Example No. One:


Target - http://www.FakeAuctionSite.com/
Intention – Cyber Extortion
Extortion is defined as the act of unlawfully obtaining money, property or services from a person or institution through manipulation, bullying, or pure force. The cyber equivalent of extortion incorporates all of the techniques listed above, with one obvious difference - all communication done through cyber extortion excludes physical contact. In other words, the manipulation, bullying, and pure force are all verbally and visually communicated to the victim by the attacker.

For example, http://www.FakeAuctionSite.com/ contains a web application that allows users to upload and then edit documents related to items submitted to be auctioned. The application’s code is as follows:

Code:
!Contents of
<?php $content = "edited.txt";
if($_POST) { $save = $_POST;
$fopen = @fopen($loadcontent, "w");
if ($fopen) {
fwrite($fopen, $savecontent);
fclose($fopen);
print '<a href='.$_SERVER[PHP_SELF].'>Refresh Page</a>';
print "<html><head><META http-equiv=\"refresh\" content=\"0;URL=$_SERVER[PHP_SELF]\"></head><body>";
}
}
$fopen = @fopen($content2, "r");
$content2 = fread($fopen, filesize($content2));
$lines = explode("\n", $content2);
$count = count($lines);
$content2 = htmlspecialchars($content2);
fclose($fopen);
for ($a = 1; $a < $count+1; $a++) {
$line .= "$a\n";
}
?>

<form method=post action="<?=$_SERVER?>">
<input type="submit" name="save_file" value="Save">
<table width="100%" valign="top" border="0" cellspacing="1" cellpadding="1">
<tr>
<td width="3%" align="right" valign="top"><pre style="text-align: right; padding: 4px; overflow: auto; border: 0px groove; font-size: 12px" name="lines" cols="4" rows="<?=$count+3;?>">
<?=$line;?>
</pre>
</td>
<td width="97%" align="left" valign="top">
<textarea style="text-align: left; padding: 0px; overflow: auto; border: 3px groove; font-size: 12px" name="content" cols="150" rows="<?=$count;?>" wrap="OFF">
<?=$content2?>
</textarea>
</td>
</tr>
</table> <br>
<input type="submit" name="save_file" value="Submit">
</form>


In this scenario, let’s say that a black-hat hacker stumbled across the vulnerable application and decides that it would be in his best interest to change the application code so that all site generated credit card transactions are forwarded to his anonymous bank account. The sheer magnitude of potential damage that these types of vulnerabilities can lead to is nauseating, especially when you consider the fact that a good percentage of Directory Traversal holes can be fixed with just a little effort.

Prevention


Prevention methods for the infamous Dot-Dot-Slash have been under development since the discovery of the attack; however, the product of that development has seen little growth in popularity until recent years due to the fact that a large amount of web developers have been under the impression that malicious hackers will not target their websites, and so they have dismissed the idea of web application security altogether - to their own detriment. The most successful approach to-date used to patch Path Traversal holes is as follows:
  1. Choose a target application.
    Isolate every function within the application by which user-controlled data is processed.
    Validate all user supplied input by ensuring that all submitted data contains only permitted characters, and that the length of the data meets set requirements. A combination of these two methods and other preventative validations is most effective because it requires that the submitted data conforms to an established standard. If the data supplied by the user does not meet the set requirements, have the application stop processing the request.
    Include within the application a list of acceptable file types. Have the application stop processing any request for a different type.
    Repeat steps one through four to secure other web applications on the web site.

Server Relative



This vulnerability occurs when software or services that are employed by the web server allow user-supplied input to induce a “traverse to parent directory” within a web server, to gain access to files or directories that would otherwise be restricted. Unlike Site Relative Directory Traversal vulnerabilities, this type of security hole typically involves the use of the ‘execute’ and ‘delete’ permissions. Frequently, the ‘read’ and ‘write’ permissions are introduced as well, usually via the ‘execute’ permission.

Discovery


A workable approach to discovering Server Relative Directory Traversal holes is as follows: Step One Search for service related files that routinely allow users to execute commands. Step Two Search for directories that are executable in nature. Step Three Send Directory Traversal requests to each service related file and directory hosted on the server.

Exploitation


The purpose of this sub-section is to provide an aid in understanding Directory Traversal exploitation by means of practical examples of attacks. Each of the examples shared below is intended to emulate an attack scenario that has been encountered on the net.

Command Execution


In some instances, a user should be allowed to submit data to a server and have the web server process the request and respond accordingly. In the case of server objects that permit command execution, this should be completely forbidden. There are few valid reasons why an average site user should be able to run commands against a server. In most cases, this is NOT safe.

These types of attacks make system and even network compromise a much easier task for villainous users.

Example No. One
Target: http://www.fakemilitary.mil
Intention: Counter Intelligence Terrorism

The objective of counter intelligence terrorism is to deny, degrade, disrupt, destroy, or deceive an adversary’s communication.

For this example, let’s say that the FakeMilitary has a website set up for service members to use to access their personnel files and information on upcoming events. Military personnel also use the site to check for pending assignments. If a hacker were able delete necessary server files via a vulnerable web service, military inter-communication would suffer, resulting in disorganization, financial loss, and possible chaos.

Exploit Examples:
  1. http://www.fakemilitary.mil /scripts/..%5c../Windows/System32/ cmd.exe?/c+dir+c:\
    http://www.fakemilitary.mil /scripts/..%5c../Windows/System32/ cmd.exe?/c+deltree+c:\

Prevention


While it seems that prevention methods for Server Relative Directory Traversal attacks are the responsibility of server software developers alone, there are a few steps that can be taken by site developers to avoid becoming a victim.
  1. Ensure that you only use software and services that have been thoroughly tested for Directory Traversal vulnerabilities over a long period of time.
    Restrict access to files or directories that could potentially turn into attack vectors.

Bypassing Prevention Methods


The attention that Directory Traversal vulnerabilities have received by security professionals in recent years has caused an increase in the level of awareness among web developers with regard to the seriousness of the flaw; therefore, many web developers incorporate defensive functions in an attempt to prevent exploitation. Frequently, the defenses that are put in place are not comprehensive enough to provide absolute protection against Directory Traversal attacks, making circumvention possible. Below are a few of the most widely used defensive measures taken by web developers and the steps to circumvent those defenses.

Encoding Schemes


Filtration mechanisms are often constructed to analyze submitted data to determine whether or not user input contains Directory Traversal sequences. If the input supplied by the user is determined to be unsafe by the filter, the hazardous sequences are escaped, encoded, or removed completely. The following steps can be used to evaluate whether or not a bypass for the filter exists.
  1. Choose an application target.
    Create a simple Directory Traversal attack string and submit it to the application.
    Review the application’s response to verify that the request was processed properly.
    If the request was rejected, identify the characters that are disallowed by the filter and evaluate whether or not constructing a functional attack string without those characters is possible. (e.g. Try using either forward slashes or backslashes)
    If step four is not possible, attempt to circumvent the filter by using various encoding schemes:

Code:
URL Encoding %5c %2f %2e
Dbl URL Encoding %255c %252f %252e
18-Bit Unicode %u2216 %u2215 %u002e
UTF-8 Unicode %c0%5c %c0%af %c0%2e Examples: Source.php?file=%2e%2e/%2e%2e/etc/passwd File.php?name=..%252f.. %252fetc%252fpasswd DL.php?file=%u002e %u002e %u2215.htpasswd
15


Poison Null Byte


The NULL character, also known as the NULL terminator, represents the value zero in the ASCII and Unicode character sets. The NULL character is often referred to as a termination character because it is used by the vast majority of mainstream programming languages to represent the end of a string.

A NULL byte is said to be poisoned, or a poison NULL byte, when it is used by an attacker to force a string to end at a certain point, effectively causing an application to return the truncated value of the string in its response after the original version of the string, including the NULL character, has been processed.

Below are a few examples of defensive measures that are commonly implemented by web developers to avoid Directory Traversal attacks, and the steps to evade those measures using the poison NULL byte.
  1. Choose an application target.
    Create a simple Directory Traversal attack string and submit it to the application.
    Review the application’s response to verify that the request was processed properly.
    If the request was rejected, submit an array of attack strings that contain a variety of different prefixes (directories) and suffixes (file extensions).
    If any of the sent requests are returned successfully, attempt to circumvent the filter by using a poisoned NULL byte.

Case One – The application checks for a specific file extension:
Code:
$filename = $GET[‘filename’]; Require_once(“/var/www/$filename.php”);

Bypass – Insert a null byte between the desired filename and the required extension. Script.php?filename=login.php%00.txt

Case Two – The application checks for a particular subdirectory prefix.
Code:
$filename = $GET[‘filename’]; $directory = $GET[‘directory’]; Require_once(“/var/www/$directory/$filename.php”);}

Bypass – Insert a null byte at the beginning of the directory parameter. Script.php?filename=../../../etc/passwd%00&directory=%00


OUTRODUCTION



Closing Remarks



Directory Traversal vulnerabilities are quite common, but their presence is often difficult to detect by rogue hackers and web-developers alike; however, by using a systematic approach, along with determination and skill, these vulnerabilities can be unveiled.

While the bugs themselves might be illusive, their potential for devastation is not. Path Traversal attacks have ranked among the most dangerous computer security exploits. They pose a serious threat not solely to internet users, but to theoretically any user with a direct or indirect network connection to the outside world.

So find them, before they find you.

Contact Information
x2600.hack@gmail.com