Preventing Directory Traversal Vulnerability
Directory Traversal is a vulnerability that allows attackers to access files that are present outside the root directory or outside the home directory of that web server. The root directory has some internal files which are not accessible by the user. This vulnerability can be found in web servers or web application code. This type of attack is also known as a path traversal attack.
Directory traversal vulnerabilities can be found by testing all parts of the website that accept input from users, HTTP requests, forms, and cookies. The attacker makes use cd command with two dots (cd..) which changes it to its parent directory. By adding ../ directly to the file path in the URL, we can try to change it into higher directories to view system files.
Some of the system files which can be accessed by the attacker:
For Unix-based operating systems :
- /etc/passwd file: Contains information about all the user’s account
- /etc/group file: Contains groups to which users belong
- /etc/profile file: Contains default variables for users
- /proc/self/environ file: Contains certain environmental variables
- /etc/issue file: Contains message to be displayed before the login
- /proc/version file: Contains the Linux kernel version in use
- /proc/cpuinfo file: Contains the processor information
For Windows Operating systems :
Example of a Directory Traversal attack :
A typical example of a vulnerable PHP code is:
Given Below is a URL that has an inclusion function as GET method request
Using Directory Traversal Attack, an attacker can append ../ directly to the file path in the URL
Preventing Directory Traversal attacks :
- To prevent directory traversal in your web server, always keep your web server and operating system updated.
- The website should validate the user input before processing it to prevent Directory Traversal attacks.
- The permissions given to a non-superuser should be read-only for the files it needs to run. The non-superuser should not be allowed to write or modify any files.
- When any URL request is made for a directory or file, normalize all characters. For example, all %20 should be converted to spaces.
- Always run your web server from a separate disk from your system disk because the system disk has sensitive information.
- If you need to fetch a file name from a user, make sure it is properly scanned by valid characters.