1

I'm trying to fix Path Traversal Vulnerability raised by Gitlab SAST in the Java Source code. There is a scenario where I am creating a file object by passing in an Input string. Then creating a file output stream to write to the file represented by the specified File object.

private BufferedWriter createFile( String filePath, String fileName )
    {       
        try {
            File dir = new File( FilenameUtils.normalize(filePath) );
    
            if ( ! dir.exists() ) {
                if (! dir.mkdirs() ) {
                    log("** WARNING: The file " + fileName + " cannot be created because the path " + filePath  + " could not be created **\n");
                    return null;
                }
            }
        
            File file = new File(dir.getPath() + File.separatorChar + fileName);
            if ( file.exists() )
                file.delete();

            FileOutputStream fos = new FileOutputStream( file , false );
            ps = new PrintStream(fos);
            
            return new BufferedWriter(new FileWriter(file));
        }
        catch (Exception e) {
            log("** Warning: could not create file : " + filePath + File.separatorChar + fileName + " **\n");
            e.printStackTrace();
            return null;
        }
    }

Issue is I am getting Path traversal vulnerability error for line FileOutputStream fos = new FileOutputStream( file , false ); How do I fix this? I have tried using getCanonicalPath() method but that didn't solve the issue.

There was a vulnerability error while creating file object as well which I fixed it using FilenameUtils class

1
  • Please add a programming language tag. Commented Aug 31, 2023 at 7:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.