flawopen.com/path-traversal/Java
How unvalidated File constructors in Java allow traversal, and how to verify boundaries using getCanonicalFile and Path.startsWith.
设想一家酒店的房卡扫描锁原本只允许开启二楼的客房。如果客人在门禁键盘上输入 '../../master-safe',有缺陷的门锁就会跳出当前楼道,直接打开酒店经理办公室的主保险箱。
Web Application SecurityCWE-918.CWE-918CWE-918):Standard Common Weakness Enumeration classification for path-traversal-java.Defense-in-Depth应用程序接口通过 HTTP 参数接收用户指定的文件名、报告路径或静态资源标识。
攻击者在文件名参数中注入相对路径遍历符号(如 '../', '..%2f')或绝对路径覆盖。
后端直接将不可信输入与基础目录拼接,未进行规范化绝对路径解析(Canonicalization)与边界校验。
系统运行时打开并回传敏感配置文件(如 /etc/passwd、源码凭证、环境变量密钥),造成数据外泄。
// VULNERABLE: Direct File instantiation with user parameter
import java.io.File;
import javax.servlet.http.*;
public class FileServlet extends HttpServlet {
private static final File BASE_DIR = new File("/var/app/public/files");
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
String filename = req.getParameter("file");
// Attacker sends: ../../../../etc/passwd
File target = new File(BASE_DIR, filename);
// Directly serves arbitrary system file!
serveFile(target, resp);
}
}
// HARDENED: Canonicalize file and enforce directory prefix check
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.servlet.http.*;
public class FileServlet extends HttpServlet {
private static final File BASE_DIR = new File("/var/app/public/files");
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String filename = req.getParameter("file");
if (filename == null || filename.isBlank()) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// 1. Resolve canonical path (resolves .. and all symlinks)
File target = new File(BASE_DIR, filename).getCanonicalFile();
File canonicalBase = BASE_DIR.getCanonicalFile();
// 2. Strict boundary check using Java NIO Path
if (!target.toPath().startsWith(canonicalBase.toPath())) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Path traversal detected");
return;
}
if (!target.isFile()) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
serveFile(target, resp);
}
}
getCanonicalFile() on both target and base directory。target.toPath().startsWith(base.toPath())。target.isFile() to prevent reading device nodes or directories。ZipEntry.getName() before writing。