Skip to main content

Command Palette

Search for a command to run...

Directory Traversal: A Security Architect's Perspective (Part 3)

Updated
16 min read
Directory Traversal: A Security Architect's Perspective (Part 3)
M

20+ years in software development, now focused on application security. Writing hands-on guides on secure coding patterns, vulnerability analysis, and security architecture.

In Part 1 and Part 2 of this series, we examined directory traversal from a developer's perspective, covering attack vectors, secure coding patterns, Apache Commons IO usage, frontend security considerations, testing strategies, and static analysis integration.

In this third part, the emphasis will be on strategy rather than code. The security architect must apply what they know about vulnerabilities to the enterprise controls and risk management strategies. While it is important to know how to fix the problem of directory traversal, it is equally important to build systems and processes to stop these vulnerabilities from being deployed to begin with.

According to OWASP Top 10 2025, path traversal vulnerabilities are categorized under "Broken Access Control" (A01:2025), which has been at the top since 2021. This is because it has been acknowledged by the entire industry that access control vulnerabilities, including unauthorized access to files, are the most common class of web application security vulnerabilities. The longevity of directory traversal vulnerabilities despite being known for decades shows it is not just a technology problem; it is a security program problem.

1. Threat Modeling Directory Traversal

Prior to implementing controls, security architects have to be aware of the threat landscape. Directory traversal attacks are not a homogeneous threat. Various scenarios have different business impacts.

Attack Scenarios and Business Impact

Sensitive Data Exposure

The most common objective of directory traversal attacks is the unauthorized access of files. The attacker tries to obtain configuration files, which may hold database credentials, API keys, cryptographic keys, or customer details. The business impact may result in financial penalties from regulatory bodies such as GDPR, PCI-DSS, or HIPAA, apart from reputational damage and loss of customers. Accessing the application.properties or .env files through a directory traversal attack is enough to compromise the entire infrastructure.

Source Code Disclosure

When attackers are able to read the application’s source code, they are able to gain knowledge of the business logic and other vulnerabilities within the application. The exposure of the source code of web applications via traversal of web application archives (WAR/JAR files) provides attackers with access to the entire codebase of the applications.

Configuration Manipulation

Write-based traversal attacks allow an attacker to change configuration files, overwrite system files, or add malicious content. For example, an attacker might change the configuration file for the logging mechanism to disable the security audit trail, or they might change the SSH file to gain access.

Remote Code Execution

If paired with upload functionality, directory traversal can be used for code execution. When the attacker uploads a JSP shell to a location outside the designated upload directory but within the web application's context root, they can execute code on the server. Similarly, if the attacker writes to the cron directories or the systemd service files, they can execute commands at scheduled times.

Denial of Service

The attackers may overwrite or delete vital application files, corrupt the database, or fill disk partitions. In addition to data theft, prolonged downtime equates to direct revenue loss.

Mapping to STRIDE

Security architects often use the STRIDE model to categorize threats. Directory traversal maps across multiple categories:

STRIDE Category Directory Traversal Manifestation
Spoofing Reading credential files to impersonate other systems
Tampering Modifying configuration files, overwriting application code
Repudiation Deleting or modifying log files and audit trails
Information Disclosure Reading sensitive files, source code, credentials
Denial of Service Deleting critical files, filling disk space
Elevation of Privilege Writing to cron directories, modifying sudoers files

This multi-category impact explains why directory traversal consistently ranks high in vulnerability taxonomies. It is not a single threat but a gateway to many attack outcomes.

Attack Tree Analysis

A simplified attack tree for directory traversal helps identify control points:

Each node represents an opportunity for controls. Defense in depth means placing obstacles at multiple points, so failure at one level does not mean complete compromise.

Data Flow Analysis

Understanding data flows helps identify where path manipulation can occur:

Security architects should ensure controls exist at multiple points in this flow, with canonical path validation being the primary defense at the application layer.

2. Risk-Based Prioritization

Not all directory traversal findings require immediate remediation. Security architects must prioritize based on risk, balancing security investment against business constraints.

CVSS Contextualization

The Common Vulnerability Scoring System offers a foundation, but the numbers provided by CVSS are not necessarily business-relevant. A directory traversal vulnerability in an internal documentation system is very different from one in a customer-facing file sharing application.

Base Score Factors for Directory Traversal:

  • Attack Vector: Network (typically)

  • Attack Complexity: Low (well-documented techniques)

  • Privileges Required: Varies (None to Low depending on authentication)

  • User Interaction: None

  • Scope: Changed (file access may enable broader compromise)

  • Confidentiality Impact: High (access to sensitive files)

  • Integrity Impact: Variable (read-only vs write traversal)

  • Availability Impact: Variable (deletion capability)

Read-only traversal typically yields base scores of 7.5-8.5. Write-capable traversal scores 8.5-9.8 depending on potential for code execution.

Environmental Adjustments:

  • Is the vulnerable system internet-facing or internal only?

  • What data classification applies to accessible files?

  • Are there compensating controls (WAF, filesystem permissions)?

  • What is the system's business criticality?

  • Does the application have access to sensitive system files?

Risk Scoring Framework

A practical risk scoring approach for directory traversal findings:

Factor Weight Scoring Criteria
Data Sensitivity 30% Credentials/secrets = Critical, Config = High, Public = Low
Exposure 25% Internet = High, Partner = Medium, Internal = Low
Traversal Type 20% Write/Execute = Critical, Read = High
Authentication 15% None required = High, Auth required = Medium
Compensating Controls 10% None = High risk, Partial = Medium, Strong = Low

This framework enables consistent prioritization across a vulnerability backlog and helps justify remediation timelines to stakeholders.

Remediation SLAs

Based on risk scores, establish remediation timelines:

Risk Level Remediation Timeline Escalation Path
Critical 24-72 hours CISO, Emergency CAB
High 7-14 days Security Director, Product Owner
Medium 30-60 days Security Team Lead
Low 90 days or next release Standard backlog

These SLAs must be documented in security policy and tracked as metrics. Write-capable traversal in internet-facing systems should generally be treated as Critical regardless of other factors.

3. Compliance Mapping

Directory traversal vulnerabilities have many intersections with various compliance schemes. Security architects should be familiar with these interrelations to better address the vulnerabilities and demonstrate compliance to auditors.

PCI-DSS 4.0.1

Payment Card Industry requirements directly address directory traversal risks:

PCI-DSS Requirement Directory Traversal Relevance
6.2.4 Secure coding practices must address common vulnerabilities including path manipulation
6.3.1 Identified path traversal vulnerabilities must be risk-ranked and prioritized for remediation
6.4.2 Automated technical solutions (WAF) for public-facing web apps must detect path traversal attacks
11.4.1 Penetration testing methodology must include application-layer testing that covers path traversal
11.5.1 IDS/IPS must monitor CDE traffic for intrusion attempts, including file access anomalies

For organizations handling cardholder data, directory traversal vulnerabilities in relevant systems require documented remediation and may trigger PCI audit findings.

SOC 2

SOC 2 Trust Services Criteria (2017, Revised Points of Focus 2022) relate to directory traversal:

Criteria Directory Traversal Relevance
CC6.1 Logical access security over protected information assets must prevent unauthorized file access
CC6.6 Logical access measures must protect against threats from sources outside system boundaries
CC6.7 Restrict transmission, movement, and removal of information to authorized users and processes
CC7.1 Detection and monitoring for configuration changes that introduce new vulnerabilities
CC7.2 Monitor system components for anomalies indicative of malicious acts, including unauthorized file access

Directory traversal represents a failure of logical access controls (CC6.1) and system boundary protection (CC6.6, CC6.7). Audit trails should capture traversal attempts (CC7.2).

GDPR

According to the General Data Protection Regulation Article 32, there is a requirement for "appropriate technical measures" to be in place for data protection. Directory traversal that allows access to personal data fails to perform this requirement appropriately and may trigger breach notification requirements under Articles 33 and 34.

HIPAA

Health Insurance Portability and Accountability Act requires protection of Protected Health Information (PHI). Directory traversal exposing PHI violates the Security Rule technical safeguards (164.312) and may constitute a reportable breach.

Compliance Evidence

Maintain evidence for auditors demonstrating directory traversal controls:

  • SAST scan results showing traversal detection rules

  • Penetration test reports including path traversal testing

  • Code review checklists with traversal validation checks

  • Security training records for developers

  • Incident response procedures for file access violations

  • WAF rules blocking common traversal patterns

4. Security Architecture Controls

Security architects design controls at multiple layers to prevent, detect, and respond to directory traversal attacks.

Preventive Controls

Application Layer

The canonical path validation is the main preventive measure. Recall the discussions in Parts 1 and 2 regarding the validation of all paths after resolution, including symbolic link resolution, via the use of the toRealPath() method and startsWith() comparisons.

A centralized file access service can be used as a single location for implementing path validation. Rather than having path validation implemented in each controller individually, consider routing all file operations via a security-hardened service layer.

Framework Configuration

Spring Boot's PathResourceResolver has built-in protection against path traversals for static resources. Ensure that all file-serving code uses framework-based methods instead of custom code.

Web Application Firewall

Configure WAF rules to identify and prevent common path traversals. WAF is not a primary security mechanism, but it is an additional security feature:

# Example WAF rule patterns
Block requests containing:
- ../
- ..%2f (URL encoded)
- ..%252f (double encoded)
- ..%c0%af (overlong UTF-8)
- Absolute paths in parameters

WAF rules must be regularly updated to reflect newly developed bypass techniques. They will only detect known patterns and cannot be used as a substitute for application-level validation.

Operating System Controls

Apply the principle of least privilege for the operating system. The application service accounts should have minimal filesystem privileges. The filesystem should be chrooted or containerized to restrict the filesystem available to the application.

Audit Controls

Application Logging

Log file access attempts in sufficient detail for forensic analysis. As discussed in Part 2, audit logging should include the requested path, resolved path, client IP address, user identity, and access result (access allowed/denied).

Security Information and Event Management (SIEM)

Correlate file access logs with other security events. Create detection rules for traversal indicators such as multiple blocked access attempts from single IP, access attempts to sensitive paths like /etc/passwd, unusual file access patterns outside business hours, and sequential enumeration suggesting automated scanning.

File Integrity Monitoring

Deploy file integrity monitoring on sensitive directories. Changes to configuration files, application code, or cron directories should trigger alerts even if the change mechanism is not the application itself.

Responsive Controls

Automated Blocking Configure systems to automatically block IP addresses or sessions upon detecting a traversal attempt. The balance between security and user experience must also be considered, including temporary blocks and verification processes.

Incident Response Integration The process of detecting directory traversal should also trigger an incident response process. Pre-defined runbooks should be established for detecting file access incidents, including initial actions, evidence preservation, and communication processes.

5. Secure SDLC Integration

Security architects must embed directory traversal prevention into the software development lifecycle rather than relying solely on late-stage detection.

Secure SDLC Integration Points

Requirements Phase: Define the security requirements for canonical path validation for all file operations. Threat modeling is used to understand file access threats. Data classification is used to determine which files need to be protected.

Design Phase: In this phase, architecture review is used to validate file access patterns. Data access layer design is approved by security architects. Framework selection involves checking for built-in protection against file traversal.

Development Phase: In this phase, plugins in the integrated development environment (IDE) are used to detect potential issues with file path construction. SAST is run on modified files before committing the code. Code reviews include checklists for traversal verification.

Testing Phase: In this phase, SAST is used to scan the entire codebase for CWE-22 patterns. DAST is used to probe for potential traversal issues. Penetration testing involves attempts to traverse the file system with encoding variations.

Deployment Phase: In this phase, security gates block deployment with critical issues. WAF rules are updated to include new endpoints. File integrity monitoring is set up for new paths.

Operations Phase: In this phase, runtime protection is used to monitor for potential traversal issues. Log analysis is used to detect anomalous file access. Incident response is used to handle successful attacks.

Security Gates

Automated security gates should be put in place to stop weak code from entering production. The four gates of pre-commit, pull request, CI pipeline, and pre-production are covered extensively in Building an AppSec Metrics Program. For directory traversal vulnerabilities, the important gates are: SAST rules for CWE-22 patterns, mandatory security review of any code manipulating file operations, dependency checks for libraries with known traversal CVEs, and DAST with encoding variation payloads including URL-encoded, double-encoded, and overlong UTF-8.

Developer Training

The general developer training program structure (mandatory courses, refreshers, CTF exercises, security champions) is already covered in the Building an AppSec Metrics Program topic. For directory traversal, the training should focus on the following points:

  • Why is the use of normalize() alone not sufficient? What is the correct solution with toRealPath() + startsWith()?

  • Why do encoding variations bypass simple input filtering?

  • What are zip slip vulnerabilities during archive extraction?

  • What is the difference between blocklist/whitelist approaches?

6. Metrics and Measurement

The core AppSec metrics framework, including MTTD, MTTR, Vulnerability Density, Exposure Window, Residual Risk Trend, and Security Debt Ratio, is discussed in the Building an AppSec Metrics Program. All these definitions and tracking mechanisms are applicable to directory traversal as well. Here, we are discussing the metrics that are applicable to path traversal prevention.

Code centralization for file handling is the percentage of code that interacts with the filesystem that is handled through the centralized security-hardened file access service versus custom code. The higher the centralization percentage, the lower the number of places where the traversal bug is present. This is tracked through architectural reviews or code searches.

WAF traversal block rate is the rate at which the WAF layer is catching the traversal attempts compared to the application layer. If the WAF layer is catching most of the traversal attempts, it is an indication that the attackers are actively trying to exploit your system. If the application layer is catching the ones that the WAF layer is missing, then the WAF rules need to be updated.

Canonical validation adoption is the percentage of file-serving endpoints that are using the approved toRealPath() + startsWith() pattern compared to legacy or custom validation. This is the percentage of your code that is already using the pattern that is suggested in Parts 1 and 2. The goal is to have this at 100% for internet-facing applications with a plan for internal applications.

7. Incident Response Considerations

The general incident response lifecycle, the communication templates, and the remediation SLA framework are discussed in Building an AppSec Metrics Program. There are some unique features in directory traversal incidents that need to be pointed out.

Detection is often indirect. Unlike SQL injection which may trigger database errors, traversal attempts frequently surface as application errors for nonexistent paths, WAF blocks for encoded dot-dot-slash patterns, or anomalous entries in file access logs such as a web application suddenly reading /etc/passwd. File integrity monitoring is especially valuable here because it catches successful write-based traversal that other detection mechanisms missed entirely.

Scope assessment is critical. The first question after confirming a traversal incident: what files were accessible? This depends on the application's OS-level permissions, not just the vulnerability itself. An application running as root with a traversal bug is a completely different incident than one running in a container with a read-only filesystem. Rotate any credentials found in files within the accessible scope, even if you cannot confirm they were actually read.

Post-incident review should focus on why canonical path validation was missing. Was it a new endpoint that bypassed the centralized file service? A developer who did not know the correct pattern? A third-party library that handled paths internally without validation? The root cause determines whether you need better gates, better training, or better architecture.

8. Organizational Considerations

Security Champions Program

The general security champions framework is described in Building an AppSec Metrics Program. For directory traversal, champions should focus on reviewing file handling code and ensuring all file-serving endpoints route through the centralized validation service rather than implementing custom path checks.

Vendor and Third-Party Risk

Directory traversal risk exists in third-party code too. Assess the security practices of third-party library maintainers. Check third-party file handling code for directory traversal vulnerabilities. Include testing for path traversal vulnerabilities in third-party security assessments. Monitor for CVEs in third-party dependencies related to file handling. A file handling library has a vulnerability affecting all applications using this library.

Wrapping Part 3

Directory traversal prevention is not just a coding issue. It is a security program issue that requires consideration of architecture, governance, process, and culture as well.

Security architects must consider the broader picture beyond the specific vulnerability. The objective is not to address the directory traversal vulnerability individually but to design systems where the vulnerability cannot happen easily, where it can be quickly detected if it does happen, and where it can be quickly fixed if it does happen.

The technical underpinnings provided in Parts 1 and 2 of this blog series will help developers write secure code. The architectural and programmatic frameworks provided in this part will help ensure that those best practices are applied, measured, and continually improved throughout an organization.

The problem of directory traversal will continue to show up in vulnerability reports as long as applications process user-influenced file paths. The question is, will your organization detect those problems in development, or will you learn about them from attackers? Security architecture is the key.

Directory Traversal

Part 3 of 3

Secure file handling patterns in Java Spring applications. From path validation and zip slip prevention to Apache Commons IO, testing strategies, threat modeling, compliance mapping, and security program integration.

Start from the beginning

Directory Traversal in Java: A Comprehensive Security Guide (Part 1)

Directory traversal vulnerabilities are at the core of a failure in the boundary between application logic and filesystem access. There is a tendency to focus on SQL injection, but directory traversal