是否可以使用 Javas File 构造函数进行路径遍历?

Is path traversal possible using Javas File constructor?

我正在构建一个网络服务,用户可以在其中上传解压缩并保存到我们服务器的 zip 文件。

我创建了以下函数来打开指定路径中的文件:

private File secureOpenFile(String fileName, String directorypath){
        return new File(directorypath, fileName);
}

但是安全扫描告诉我这个不安全,有路径穿越的可能。提供参数 ("../../notsafe", "uploadfolder") 将允许恶意攻击者覆盖其他文件...

但是,在文件 class 的文档中,我发现了以下内容:https://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.io.File,%20java.lang.String)

Otherwise the parent abstract pathname is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file. If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way. If parent is the empty abstract pathname then the new File instance is created by converting child into an abstract pathname and resolving the result against a system-dependent default directory. Otherwise each pathname string is converted into an abstract pathname and the child abstract pathname is resolved against the parent.

我解释为:不离开父文件夹。我是否正确?这段代码安全吗?如果现在:解决此安全问题的最佳方法是什么?

是的,有可能。

...the child abstract pathname is resolved against the parent.

只是表示解析child路径时parent路径作为base,但是如果child路径包含..,结果会在parent.

之外

例如

new File("/Users/example/projects/sample/target", "../pom.xml").getCanonicalFile();

结果 /Users/example/projects/sample/pom.xml,因此在 target.

之外

所以,简而言之,是的,你确实需要自己防范。