Search code examples
javasecurityjava-securitydirectory-traversalpath-traversal

Is there a way to prevent directory traversal attacks (../ pattern) at the JRE level?


I'm looking for a way to prevent directory traversal attacks, specifically those involving the ../ pattern in file paths, at the Java Runtime Environment (JRE) level. My goal is to ensure that such attacks are mitigated without relying on explicit path validation and sanitization checks in my Java code.

  • Here is what I have observed:

Java Security Manager: While the SecurityManager can help with controlling file access, it does not directly prevent or sanitize paths that include ../ sequences.

File Permissions and Policies: Setting file permissions and security policies might restrict access but does not inherently sanitize paths to prevent directory traversal.

JRE Configuration: I'm aware that JRE configurations or system properties might provide some level of security, but I haven't found specific options to prevent ../ patterns from being processed.

  • My Questions:
  1. Is there any built-in mechanism in the JRE to automatically prevent or sanitize file paths containing ../ patterns?

  2. Are there JRE configurations, system properties, or settings that can help in mitigating directory traversal attacks at a lower level, without requiring code-level checks?

  3. If no such mechanisms exist, what are the best practices for securing file paths at the JRE level, apart from application code checks?

I would appreciate any guidance or references to relevant documentation or tools that could help achieve this security goal at the JRE level.


Solution

  • It is a challenging task because the JRE itself doesn't inherently sanitize or reject paths containing patterns like ../. The best approach combines using a SecurityManager with custom policies, leveraging security libraries, and applying best practices for filesystem access. Additionally, configuring the environment and using containers can provide an extra layer of security.

    Try using custom policies :

    System.setSecurityManager(new SecurityManager());
    
    PermissionCollection permissions = new Permissions();
    PermissionCollection permissions = new Permissions();
    permissions.add(new FilePermission("/your/allowed/directory/-", "read,write"));
    permissions.add(new FilePermission("/your/allowed/file.txt", "read"));
    Policy.setPolicy(new Policy() {
    @Override
    public PermissionCollection getPermissions(CodeSource codesource) {
        return permissions;
      }
    });
    

    Check this references: Java SecurityManager Doc and OWASP Path Traversal