实现说明
真正干活的是类 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);
}
}
}