我有一个 Java 服务器实现(TFTP,如果对你很重要的话),我想确保它不会受到路径遍历攻击,允许访问不应该可用的文件和位置。
到目前为止,我最好的防御尝试是拒绝任何匹配 File.isAbsolute()
的条目,然后依靠 File.getCanonicalPath()
来解析任何 >../
和 ./
组件脱离路径。最后,我确保生成的路径仍在我的服务器所需的根目录中:
public String sanitize(final File dir, final String entry) throws IOException {
if (entry.length() == 0) {
throw new PathTraversalException(entry);
}
if (new File(entry).isAbsolute()) {
throw new PathTraversalException(entry);
}
final String canonicalDirPath = dir.getCanonicalPath() + File.separator;
final String canonicalEntryPath = new File(dir, entry).getCanonicalPath();
if (!canonicalEntryPath.startsWith(canonicalDirPath)) {
throw new PathTraversalException(entry);
}
return canonicalEntryPath.substring(canonicalDirPath.length());
}
是否存在遗漏的安全问题?是否有更好/更快可靠地实现相同结果的方法?
代码需要在 Windows 和 Linux 上一致地工作。
最佳答案
以下内容可能会有所帮助。它比较规范路径和绝对路径,如果它们不同,那么它将失败。仅在 mac/linux 系统上测试(即没有 windows)。
这适用于您希望允许用户提供相对路径而不是绝对路径并且不允许任何父目录引用的情况。
public void failIfDirectoryTraversal(String relativePath)
{
File file = new File(relativePath);
if (file.isAbsolute())
{
throw new RuntimeException("Directory traversal attempt - absolute path not allowed");
}
String pathUsingCanonical;
String pathUsingAbsolute;
try
{
pathUsingCanonical = file.getCanonicalPath();
pathUsingAbsolute = file.getAbsolutePath();
}
catch (IOException e)
{
throw new RuntimeException("Directory traversal attempt?", e);
}
// Require the absolute path and canonicalized path match.
// This is done to avoid directory traversal
// attacks, e.g. "1/../2/"
if (! pathUsingCanonical.equals(pathUsingAbsolute))
{
throw new RuntimeException("Directory traversal attempt?");
}
}
关于java - 防御路径遍历攻击的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2375903/