Chris Mok
Chris Mok

Reputation: 83

How to prevent the Path Traversal in Java

Recently, I used the AppScan Source to scan the coding, and it found out one of the finding which I don't know how to fix and pass to the scanner

Here's my code.

public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");

String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;

File fileExists = new File(n);
if (fileExists.exists()) {
            PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
          } else {
            BasicConfigurator.configure();
          }   
 }

I tried to add the if statement to check any special character in the path. However the scanner still report the finding in "File fileExists = new File(n);"

public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");

String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;
 //For Security Checking
if (file != null && !n.contains("../") && !n.contains("$") && !n.contains("*"))//Check the path whether it's included risk character
{

File fileExists = new File(n);
if (fileExists.exists()) {
            PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
          } else {
            BasicConfigurator.configure();
          }
}
 }

Upvotes: 4

Views: 16939

Answers (2)

James Lawruk
James Lawruk

Reputation: 31383

The scanner flags file paths with variables.

var sr = new StreamReader("C:\\....\\WEB-INF" + file);

As mentioned by Ahmad, it is usually a false positive. But it is a good idea to verify a malicious user could not exploit the code and to get access to files that was not intended.

To make the scanner happy, you could supply it with hard coded paths, or create a switch statement for every possible file path.

switch (fileId)
  {
      case "1":
          sr = new StreamReader("C:\file-1");
          break;
      case "2":
          sr = new StreamReader("C:\file-2");
          break;
  }

But who wants to do that!

Your best option is to ensure no threat exists and to convince the security folks to allow your code to proceed.

Upvotes: 0

Ahmad
Ahmad

Reputation: 66

This is just a false positive by the scanner. There is no security risk with the above code as no user input involved in reading or writing to the path.

Upvotes: 4

Related Questions