2024 CWE Top 25 Most Dangerous Software Weaknesses: Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’) CWE-22

2024 CWE Top 25 Most Dangerous Software Weaknesses: Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’) CWE-22

Path traversal vulnerabilities, categorised under CWE-22, are a persistent and critical threat in software development, regularly making their way into the CWE Top 25 Most Dangerous Software Weaknesses. For software architects and developers, addressing these vulnerabilities is paramount to safeguarding applications and ensuring robust security. In this post, we delve into the technical intricacies of path traversal, explore its implications, and provide actionable strategies for mitigation.


Understanding CWE-22: Path Traversal

What Is Path Traversal?

Path traversal, also known as directory traversal, is a vulnerability that allows an attacker to access files and directories stored outside the intended directory. By exploiting improper validation of user-supplied input, attackers can manipulate file paths to access sensitive system files, configuration files, or any other data stored on the server.

How Path Traversal Works

Path traversal exploits occur when applications use user-supplied input to construct file or directory paths without adequate validation. Attackers manipulate the input to include sequences like ../ or ..\\ to traverse the directory structure. For instance:

  • Normal input: GET /profile?user=123
  • Malicious input: GET /profile?user=../../etc/passwd

Here, the ../../ sequence allows the attacker to move up two directory levels and access the /etc/passwd file.

Why CWE-22 Matters

CWE-22 ranks among the most dangerous vulnerabilities due to its simplicity and potential impact. Successful exploitation can result in data breaches, unauthorised access to sensitive files, or even full system compromise.


Real-World Implications

Business Impact

  • Data Breaches: Sensitive customer data, such as financial or personal information, can be exposed.
  • Operational Disruption: Attackers may modify or delete critical system files, leading to downtime.
  • Reputation Damage: A breach involving path traversal vulnerabilities can severely impact an organisation’s credibility.
  • Compliance Violations: Failure to secure systems against such vulnerabilities may result in regulatory penalties.

Case Studies

  1. The LFI Exploitation Incident

    In a high-profile case, attackers exploited a path traversal vulnerability in a web application to gain access to server files. This eventually escalated to remote code execution (RCE), compromising thousands of user accounts.
  2. The E-commerce Breach

    An online retailer failed to validate user input for file uploads. By exploiting this flaw, attackers accessed payment card information stored on the server, resulting in a significant financial loss and a regulatory investigation.

Why Do Path Traversal Vulnerabilities Occur?

1. Improper Input Validation

Developers often fail to validate user input adequately, allowing malicious sequences to pass unchecked.

2. Insecure API Usage

APIs that rely on file system operations can inadvertently introduce vulnerabilities if not handled securely.

3. Legacy Code

Older codebases may not incorporate modern security practices, making them more susceptible to CWE-22.

4. Misconfigured Servers

Improperly configured web servers may inadvertently expose sensitive files, exacerbating the vulnerability.


Detecting Path Traversal Vulnerabilities

Static Application Security Testing (SAST)

Static analysis tools can help identify potential path traversal vulnerabilities in the source code during development.

Dynamic Application Security Testing (DAST)

Dynamic testing involves simulating attacks on a running application to detect exploitable vulnerabilities.

Penetration Testing

Regular penetration testing by experienced professionals can uncover path traversal and other critical vulnerabilities.

Monitoring and Logging

Comprehensive logging of file access activities can help identify suspicious patterns indicative of a path traversal attack.


Mitigation Strategies for CWE-22

1. Input Validation and Sanitisation

  • Implement strict whitelisting for acceptable inputs.
  • Reject input containing sequences like ../ or ..\\.

2. Canonicalisation

Resolve file paths to their canonical forms to eliminate any ambiguities introduced by relative path sequences.

3. Access Control

  • Restrict application access to only necessary files and directories.
  • Employ file system permissions to prevent unauthorised access.

4. Use Secure APIs

Leverage APIs that abstract file system operations, such as java.nio.file.Paths in Java or Path.Combine in .NET.

5. Server Configuration

  • Use chroot or similar mechanisms to confine the application to a specific directory.
  • Disable directory listing on web servers.

6. Testing and Auditing

  • Integrate automated security testing into the CI/CD pipeline.
  • Conduct regular code reviews to identify and remediate vulnerabilities.

Coding Best Practices

Secure Code Example in Python

Vulnerable Code:

import os

def read_file(filename):

    with open(filename, ‘r’) as file:

        return file.read()

user_input = input(“Enter the filename: “)

print(read_file(user_input))

Secure Code:

import os

def read_file(filename):

    base_path = “/secure/directory/”

    full_path = os.path.realpath(os.path.join(base_path, filename))

    if not full_path.startswith(base_path):

        raise ValueError(“Invalid file path!”)

    with open(full_path, ‘r’) as file:

        return file.read()

user_input = input(“Enter the filename: “)

print(read_file(user_input))

Key Improvements:

  1. Canonicalisation: Resolved the file path to its absolute form using os.path.realpath.
  2. Validation: Ensured the final path remains within the allowed directory.

Leveraging Tools for Enhanced Security

Static Analysis Tools

  • SonarQube
  • Fortify
  • Coverity

Dynamic Testing Tools

  • Burp Suite
  • OWASP ZAP

File Monitoring Solutions

  • OSSEC
  • Splunk

Future-Proofing Your Applications

Adopt a Security-First Mindset

Security must be a core consideration throughout the software development lifecycle (SDLC).

Continuous Learning and Training

Educate development teams about the latest security threats and best practices.

Stay Updated

Regularly review the CWE Top 25 list to understand emerging threats and mitigation techniques.


Dynamic Application Security Testing (DAST) and Penetration Testing are both crucial techniques in identifying vulnerabilities in applications, but they differ in scope, purpose, execution, and outcomes. Below is a detailed comparison:


1. Definition

  • DAST

    Dynamic Application Security Testing is an automated process that tests a running application for security vulnerabilities. It works from the “outside-in,” simulating how an attacker interacts with the application without access to its source code.
  • Penetration Testing

    Penetration Testing (often called “pen testing”) is a manual or semi-automated security testing approach where ethical hackers simulate real-world attacks to identify vulnerabilities. It is more comprehensive and mimics how an attacker might exploit an application or system.

2. Scope

  • DAST
    • Focuses on the application’s runtime behaviour.
    • Primarily tests web applications or APIs for vulnerabilities like SQL injection, cross-site scripting (XSS), and authentication issues.
    • Limited to what can be detected externally without knowledge of internal code.
  • Penetration Testing
    • Covers broader security aspects, including applications, networks, and even physical systems.
    • Goes beyond runtime behaviour to include social engineering, insider threats, and misconfigurations.
    • Often examines the entire organisation’s security posture.

3. Execution

  • DAST
    • Automated: Relies heavily on tools such as OWASP ZAP, Burp Suite (DAST mode), or Acunetix.
    • Black-box Testing: Works without insight into the internal workings or source code of the application.
    • Continuous: Can be integrated into CI/CD pipelines for regular and repeated testing during development.
  • Penetration Testing
    • Manual or Semi-Automated: Combines human expertise with tools to dig deeper into vulnerabilities.
    • Customised: Tailored to the organisation’s specific environment and threat model.
    • Point-in-time: Conducted periodically (e.g., quarterly or annually) rather than continuously.

4. Techniques Used

  • DAST
    • Crawling the application to identify endpoints.
    • Testing for vulnerabilities by injecting malicious payloads.
    • Reporting known vulnerabilities based on predefined signatures.
  • Penetration Testing
    • Exploiting vulnerabilities to determine the impact (e.g., obtaining unauthorised access or extracting data).
    • Identifying complex attack chains that automated tools may miss.
    • Assessing both technical and business risks.

5. Depth of Analysis

  • DAST
    • Detects surface-level vulnerabilities accessible via the application interface.
    • Does not provide insight into root causes since it lacks access to the source code.
  • Penetration Testing
    • Identifies vulnerabilities, exploits them, and provides context on their root causes.
    • Includes advanced techniques like chaining multiple vulnerabilities to simulate real-world attacks.

6. Use Cases

  • DAST
    • Identifying vulnerabilities during the development and testing phases.
    • Automating security checks in DevSecOps pipelines.
    • Detecting runtime issues in web applications or APIs.
  • Penetration Testing
    • Testing overall security posture during compliance audits (e.g., PCI DSS, GDPR).
    • Simulating advanced persistent threats (APTs) or targeted attacks.
    • Uncovering complex vulnerabilities that require human expertise.

7. Advantages

  • DAST
    • Quick and scalable for large applications.
    • Integrates seamlessly into development workflows.
    • Provides real-time feedback during runtime.
  • Penetration Testing
    • Comprehensive and contextual, considering the organisation’s specific risks.
    • Mimics real-world attacker behaviour.
    • Includes actionable recommendations for remediation.

8. Limitations

  • DAST
    • Cannot detect vulnerabilities requiring source code analysis.
    • Limited understanding of complex attack chains.
    • Generates false positives that require manual validation.
  • Penetration Testing
    • Time-consuming and resource-intensive.
    • Requires skilled professionals with expertise in various attack vectors.
    • Provides a snapshot of vulnerabilities at a specific point in time rather than continuous monitoring.

9. Tools

  • DAST
    • Tools: OWASP ZAP, Burp Suite (DAST), Acunetix, Netsparker.
    • Automated, tool-centric, requiring minimal manual effort.
  • Penetration Testing
    • Tools: Metasploit, Burp Suite (manual mode), Kali Linux, Nmap, Wireshark.
    • Combines tool usage with human expertise.

10. Reports and Outcomes

  • DAST
    • Provides automated reports highlighting detected vulnerabilities.
    • Focuses on severity levels, types of vulnerabilities, and possible fixes.
    • Ideal for developers to fix issues during the development phase.
  • Penetration Testing
    • Delivers detailed, custom reports with insights into exploited vulnerabilities, attack vectors, and remediation steps.
    • Includes business impact analysis and prioritised recommendations.
    • Useful for stakeholders such as security teams and executives.

When to Use Which?

  • Use DAST:
    • During development and testing for early detection of vulnerabilities.
    • As part of continuous security in CI/CD pipelines.
    • For quick and automated checks on runtime behaviours.
  • Use Penetration Testing:
    • For comprehensive security assessments, including advanced threat simulation.
    • To fulfil compliance and regulatory requirements.
    • To identify vulnerabilities that automated tools cannot detect.

While DAST is an essential part of the DevSecOps process for identifying vulnerabilities during development, Penetration Testing provides a broader, more in-depth assessment of an organisation’s security posture. Combining both approaches ensures a robust security strategy, addressing both development-phase weaknesses and real-world attack scenarios.

Comparison of DAST and Penetration Testing

AspectDynamic Application Security Testing (DAST)Penetration Testing
DefinitionAutomated testing of a running application to identify security vulnerabilities.Simulation of real-world attacks by ethical hackers to find vulnerabilities.
ScopeFocuses on runtime behaviour of web applications and APIs.Covers broader security aspects, including applications, networks, and systems.
ExecutionAutomated; relies on tools like OWASP ZAP and Burp Suite (DAST mode).Manual or semi-automated; combines human expertise with tools like Metasploit.
Testing MethodologyBlack-box testing without access to source code.Simulates real-world attacker scenarios, often including insider threats.
Techniques UsedCrawling applications, injecting malicious payloads, and reporting vulnerabilities.Exploiting vulnerabilities, chaining attack vectors, and assessing risks.
Depth of AnalysisDetects surface-level vulnerabilities accessible via application interfaces.Identifies root causes, exploits vulnerabilities, and evaluates business impact.
Use CasesContinuous testing during development and integration phases.Comprehensive security assessments during audits or compliance reviews.
AdvantagesQuick, scalable, integrates into CI/CD pipelines, and provides real-time feedback.Comprehensive, mimics real-world attacks, and includes actionable recommendations.
LimitationsCannot detect source-code-based issues; may generate false positives.Time-intensive, resource-heavy, and provides a one-time snapshot.
ToolsOWASP ZAP, Acunetix, Netsparker, Burp Suite (DAST mode).Metasploit, Burp Suite (manual mode), Kali Linux, Nmap, Wireshark.
Reports and OutcomesAutomated reports with severity levels and possible fixes.Detailed, customised reports with exploited vulnerabilities and remediation steps.
When to UseDuring development for quick, automated vulnerability detection.For holistic security assessments and regulatory compliance checks.

This table provides a clear and concise comparison of DAST and Penetration Testing, highlighting their unique characteristics and use cases.

The Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’), identified as CWE-22, features in the SANS Top 25 Most Dangerous Software Weaknesses because of its critical impact, widespread occurrence, and the ease with which it can be exploited. Here’s why it consistently makes the list:


1. Prevalence in Real-World Applications

  • Common in Web Applications: Path traversal vulnerabilities often exist in applications that handle file uploads, downloads, or dynamic file paths. Web applications, APIs, and microservices frequently mishandle file path inputs, exposing this vulnerability.
  • Legacy Systems: Many older systems and applications were developed without robust input validation or sanitisation practices, making them vulnerable.
  • Complexity of Validation: Developers often fail to account for all edge cases when validating user input, leaving gaps for exploitation.

2. Potential Impact

  • Access to Sensitive Data: Exploiting a path traversal vulnerability can give attackers unauthorised access to sensitive files such as configuration files, credentials, or intellectual property.
  • System Compromise: Attackers can gain control over servers or escalate privileges by accessing system files.
  • Data Breaches: This can lead to large-scale data breaches, resulting in financial and reputational damage.
  • Business Disruption: Accessing and modifying system-critical files may cause application downtime or data corruption.

3. Simplicity of Exploitation

  • Low Barrier to Entry: Path traversal attacks do not require sophisticated tools or advanced knowledge. Simple payloads like ../ or ..\\ allow attackers to traverse directories and exploit vulnerable file paths.
  • Remote Exploitation: These vulnerabilities are often exploitable remotely, making them attractive to attackers.
  • Automated Attacks: Many tools and scripts can automatically identify and exploit path traversal weaknesses, increasing the likelihood of exploitation.

4. Difficulty in Detection

  • Subtle Nature of Exploits: Path traversal vulnerabilities are often overlooked during routine testing because they exploit subtle oversights in input validation.
  • Dynamic Behaviour: Vulnerabilities manifest only when specific input patterns are provided, making them hard to detect with static analysis alone.
  • False Positives: Developers may misinterpret alerts from tools, either underestimating or ignoring the risk.

5. Widespread Consequences

  • Multi-Platform Risk: Path traversal vulnerabilities affect applications across different platforms, programming languages, and environments, increasing their relevance and impact.
  • Chaining with Other Attacks: Path traversal is often a stepping stone for more severe attacks like remote code execution (RCE), SQL injection, or privilege escalation.

6. Alignment with SANS Priorities

  • Focus on Impact: The SANS Top 25 emphasises weaknesses that have a high impact on security, business continuity, and data integrity. CWE-22 aligns perfectly with this criterion.
  • Risk Mitigation Awareness: Including CWE-22 in the list raises awareness among developers, architects, and organisations, encouraging them to adopt security-first practices.
  • Relevance to Threat Landscape: The consistent presence of path traversal exploits in real-world breaches underlines its relevance in today’s cybersecurity threat landscape.

Path traversal (CWE-22) is in the SANS Top 25 because it encapsulates the core reasons for prioritising weaknesses in the list: high exploitability, severe impact, and wide prevalence. Addressing this vulnerability requires a combination of robust coding practices, vigilant testing, and secure deployment configurations, making it a critical focus for developers, software architects, and security teams.

The Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’) (CWE-22) is not explicitly listed as a separate vulnerability in the OWASP Top 10, but it falls under a broader category. Here’s how it aligns with the OWASP Top 10:


1. Included Under “A01:2021 – Broken Access Control”

Path traversal vulnerabilities are a classic example of Broken Access Control, which is the first category in the OWASP Top 10 (2021). Specifically:

  • Path traversal allows attackers to bypass access restrictions by manipulating file paths, giving them access to sensitive files or directories that should be restricted.
  • This vulnerability violates the principle of least privilege and proper access control mechanisms, which are central to this OWASP category.

Examples of Path Traversal in Broken Access Control

  • Accessing configuration files like /etc/passwd or /etc/shadow.
  • Retrieving sensitive application logs or credentials stored in files outside the intended directory.

2. Indirectly Related to “A05:2021 – Security Misconfiguration”

  • Path traversal vulnerabilities can also stem from security misconfigurations in file systems, web servers, or APIs.
  • For instance, improper configuration of file permissions or lack of directory restrictions can make path traversal attacks feasible.

3. Connection to “A06:2021 – Vulnerable and Outdated Components”

  • Applications using outdated libraries or frameworks may lack mitigations for path traversal vulnerabilities.
  • Legacy systems and components often fail to validate user inputs effectively, leaving them susceptible to directory traversal attacks.

Why Path Traversal Is Not Explicitly Listed

The OWASP Top 10 focuses on broad categories of vulnerabilities rather than specific issues. Path traversal:

  1. Fits under Broken Access Control, as it exploits improper enforcement of access restrictions.
  2. Is a subset of the broader problems covered in Security Misconfiguration or Vulnerable Components.

While Path Traversal (CWE-22) is not explicitly listed as a standalone issue in the OWASP Top 10, it is implicitly covered under categories like Broken Access Control (A01), making it an important consideration for developers and security professionals working on securing applications.

Final Thoughts

Path traversal vulnerabilities, as represented by CWE-22, pose a significant risk to software security. By understanding the root causes, employing robust mitigation strategies, and adhering to best practices, software architects and developers can effectively safeguard their applications. In an era where cyber threats evolve rapidly, proactive measures and continuous learning remain indispensable.

Path-Traversal-Attacks-KrishnaG-CEO

By addressing path traversal vulnerabilities comprehensively, organisations not only protect their assets but also foster trust and confidence among stakeholders—delivering tangible business value and peace of mind.


Is your applications ready to withstand the test of CWE-22?

Leave a comment