← 中文资源

简体中文版本

Path 规范化穿越防护

用户输入直接拼进路径就有穿越风险:resolve 后 normalize 抹平 . 与 ..,再用 startsWith 确认结果仍在基目录内,越界请求直接拒绝。

阅读英文原文

实现说明

真正干活的是类 DocumentStore,其余都是接线。 for (String request : new String[] {"reports/q4.pdf", "../../etc/passwd", "a/./b.txt"}) 承担全部的逐项处理。

常见问题

「Path 规范化穿越防护」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

核心语句

boolean traversalGuard = resolved.startsWith(base);
Path resolved = base.resolve(request).normalize();
Path base = Files.createTempDirectory("docs");

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DocumentStore {

    public static void main(String[] args) throws IOException {
        Path base = Files.createTempDirectory("docs");
        // path traversal 防御:先 resolve 再 normalize,最后确认仍在 base 内
        for (String request : new String[] {"reports/q4.pdf", "../../etc/passwd", "a/./b.txt"}) {
            Path resolved = base.resolve(request).normalize();
            boolean traversalGuard = resolved.startsWith(base);
            System.out.println(request + " -> " + resolved + " inside: " + traversalGuard);
        }
    }
}