How to fix "Path Manipulation Vulnerability" in some Java Code?

mohan picture mohan · Oct 2, 2012 · Viewed 75.3k times · Source

The below simple java code getting Fortify Path Manipulation error. Please help me to resolve this. I am struggling from long time.

public class Test {
    public static void main(String[] args) {
        File file=new File(args[0]);
    }

}

Answer

Joe picture Joe · Oct 2, 2012

Looking at the OWASP page for Path Manipulation, it says

An attacker can specify a path used in an operation on the filesystem

You are opening a file as defined by a user-given input. Your code is almost a perfect example of the vulnerability! Either

  1. Don't use the above code (don't let the user specify the input file as an argument)
  2. Let the user choose from a list of files that you supply (an array of files with an integer choice)
  3. Don't let the user supply the filename at all, remove the configurability
  4. Accept the vulnerability but protect against it by checking the filename (although this is the worst thing to do - someone may get round it anyway).

Or re-think your application's design.