4

I am looking to provide users of my website access to some static resources which are provided within a JAR file.

I am unable to provide a list of all files which the user should be able to access, but I can ensure that they are all contained within a subdirectory of the JAR, e.g:

public-access/file-1
public-access/file-2
public-access/sub-dir/file-3

The files will then be accessed via:

this.getClass().getResource("/public-access/" + requestedFile);

Is there a recommended way to prevent path traversal attacks? This is to prevent a malicious user from requesting a file called e.g. ../secret, or sub-dir/../../secret

Charles
  • 50,943
  • 13
  • 104
  • 142
Armand
  • 23,463
  • 20
  • 90
  • 119
  • I'm looking for a solution to this as well. Interestingly, I can't produce such an attack using "../" in the path. Perhaps it is being filtered away by Java somewhere in the process. Did you manage to perform the attack yourself? – Zero3 Mar 19 '15 at 23:49

2 Answers2

1

Have a look at the Security Manager: http://docs.oracle.com/javase/tutorial/essential/environment/security.html

I think it supports exactly what you need, just specify that opening a resource of given paths is not allowed.

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
  • It looks like I'd need to implement `checkRead()` in a custom security manager. This would need to verify an instance of `FileDescriptor` to make sure that the absolute path requested is inside my allowed path. Two issues with this - firstly I'd have to write the path resolution and verification functionality myself, which I expect has a lot of edge cases, and secondly there is one `SecurityManager` allowed per JVM, which means that I would have to restrict access through my whole application instead of solely in the `getResource()` call I am worried about, which seems less than ideal. – Armand Feb 21 '13 at 12:48
  • As above, you don't need to subclass `SecurityManager`. Should be able to write a policy file. – Tom Hawtin - tackline Feb 21 '13 at 19:10
  • @Alison You're looking at the wrong overload(s) of `SecurityManager.checkRead`. / As you're calling a method on a type you cannot control the implementation of, you'll probably want to do any validation before calling the method. – Tom Hawtin - tackline Feb 21 '13 at 19:13
1

What you need is to define a custom security policy by overriding SecurityManager. Check this tutorial which nicely explains how to create one and register.

Providing Your Own Security Manager

Hope this helps

Sudhakar
  • 4,823
  • 2
  • 35
  • 42