user1129665
user1129665

Reputation:

Forbidding Java URL from fetching local files?

I have a Java web application that has functionality to fetch remote files using URL.

While I was testing the code I found out that it is possible for an anonymous user to read a local file by modifying the path of the file, /etc/passwd, to file URL schema, file:///etc/passwd, and the file will be read by URL, here is an example:

String remoteUrl = "file:///etc/passwd"; // some url we got from anonymous user
URL url = new URL(remoteUrl);
byte data[] = new byte[1024];
int length;

BufferedInputStream inputStream = new BufferedInputStream(url.openStream());

ServletOutputStream outputStream = response.getOutputStream();
// OR PrintStream outputStream = System.out;

while( (length = inputStream.read(data, 0, 1024)) >= 0 ) {
    outputStream.write(data, 0, length);
}

Any suggestions on fixing this issue?

Upvotes: 1

Views: 138

Answers (2)

Scott Neville
Scott Neville

Reputation: 898

If your using URL, you can get the protocol from it. In that case you can just throw an exception if the protocol is "file" (or is not "http" depending on how restrictive you want to make it)

Upvotes: 2

muruga
muruga

Reputation: 1073

Execute this process under a user who has a restricted access to certain folders. This would be handled at the OS level and the OS will allow the process by the permissions defined.

Upvotes: 1

Related Questions