Rob*_*ing 38 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());
}
Run Code Online (Sandbox Code Playgroud)
是否存在未命中的安全问题?是否更好/更快地可靠地实现相同的结果?
代码需要在Windows和Linux上一致地工作.
以下可能有所帮助.它比较了规范和绝对路径,如果它们不同,那么它就会失败.仅在mac/linux系统上测试(即没有窗口).
这适用于您希望允许用户提供相对路径而非绝对路径的情况,并且您不允许任何父目录引用.
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?");
}
}
Run Code Online (Sandbox Code Playgroud)
如果你在 unix 机器上运行这个(我不确定 windows 是否有类似的东西,但可能有)你会想看看 chroot。即使您认为您想尽一切办法让某人引用一些目录,让操作系统强制执行这一事实也是很好的。
(chroot 导致“/”引用其他目录,因此“/”可能是“/home/me/project”,而“/../../..”仍然是“/home/me/project”。 )
编辑:
有一个 chroot 系统调用以及一个 chroot 命令行工具。我不知道 Java 是否有本机方法,但是没有什么可以阻止您使用命令行工具运行服务器。当然,除了尽最大努力防止其他路径操作之外,还应该这样做。
| 归档时间: |
|
| 查看次数: |
20779 次 |
| 最近记录: |