java - 防御路径遍历攻击的最佳方法是什么?

标签 java security path-traversal

我有一个 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/

相关文章:

java - 是否可以使用 Java 文件构造函数进行路径遍历?

在机器人中测试时,Java webapp 代码返回路径遍历问题

java - 如何在 Jersey 2.0 中使用 HK2 依赖注入(inject)?

java - RCP E4 @UIEventTopic 未调用

java - map-reduce代码的输出是什么?

security - OAuth 2.0——有什么新功能?

Java邮件类

php - 保护网站的最佳方法和途径

ruby-on-rails - 在 Rails 开发环境中允许不安全的脚本