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