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

92,087

Solution 1

Try to normalize the URL before using it

https://docs.oracle.com/javase/7/docs/api/java/net/URI.html#normalize()

Path path = Paths.get("/foo/../bar/../baz").normalize();

or use normalize from org.apache.commons.io.FilenameUtils

https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/FilenameUtils.html#normalize(java.lang.String)

Stirng path = FilenameUtils.normalize("/foo/../bar/../baz");

For both the result will be \baz

Solution 2

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.

Solution 3

Fortify will flag the code even if the path/file doesn't come from user input like a property file. The best way to handle these is to canonicalize the path first, then validate it against a white list of allowed paths.

Bad:

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

}

Good:

public class Test {
    public static void main(String[] args) {
        File file=new File(args[0]);
        if (!isInSecureDir(file)) {
              throw new IllegalArgumentException();
            }
            String canonicalPath = file.getCanonicalPath();
        if (!canonicalPath.equals("/img/java/file1.txt") &&
            !canonicalPath.equals("/img/java/file2.txt")) {
           // Invalid file; handle error
        }

        FileInputStream fis = new FileInputStream(f);
    }

Source: https://www.securecoding.cert.org/confluence/display/java/FIO16-J.+Canonicalize+path+names+before+validating+them

Solution 4

Only allow alnum and a period in input. That means you filter out the control chars, "..", "/", "\" which would make your files vulnerable. For example, one should not be able to enter /path/password.txt.

Once done, rescan and then run Fortify AWB.

Share:
92,087
mohan
Author by

mohan

Updated on July 11, 2022

Comments

  • mohan
    mohan almost 2 years

    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]);
        }
    
    }