Java代码审计之路径遍历
字数 795 2025-08-12 11:33:52
Java代码审计之路径遍历漏洞详解
漏洞概述
路径遍历(Path Traversal)漏洞,也称为目录遍历漏洞,是指应用程序未能正确验证用户提供的输入,导致攻击者能够访问应用程序所在服务器上的任意文件。在Java Web应用中,这种漏洞通常出现在文件操作相关的功能中。
漏洞示例代码分析
漏洞代码
/**
* http://localhost:8080/path_traversal/vul?filepath=etc/passwd
*/
@GetMapping("/path_traversal/vul")
public String getImage(String filepath) throws IOException {
return getImgBase64(filepath);
}
private String getImgBase64(String imgFile) throws IOException {
logger.info("Working directory: " + System.getProperty("user.dir"));
logger.info("File path: " + imgFile);
File f = new File(imgFile);
if (f.exists() && !f.isDirectory()) {
byte[] data = Files.readAllBytes(Paths.get(imgFile));
return new String(Base64.encodeBase64(data));
} else {
return "File doesn't exist or is not a file.";
}
}
漏洞分析
- 该接口接收一个
filepath参数,直接传递给getImgBase64方法 getImgBase64方法直接将用户输入作为文件路径使用- 攻击者可以通过构造特殊路径(如
../test.txt)访问上层目录文件 - 漏洞点在于没有对用户输入进行任何过滤或验证
漏洞利用方式
- 直接访问系统敏感文件:
/path_traversal/vul?filepath=../../../../etc/passwd - 访问应用程序上级目录文件:
/path_traversal/vul?filepath=../test.txt - URL编码绕过(如果存在解码处理):
/path_traversal/vul?filepath=%2e%2e%2ftest.txt
修复方案
修复代码
@GetMapping("/path_traversal/sec")
public String getImageSec(String filepath) throws IOException {
if (SecurityUtil.pathFilter(filepath) == null) {
logger.info("Illegal file path: " + filepath);
return "Bad boy. Illegal file path.";
}
return getImgBase64(filepath);
}
安全过滤工具类
/**
* Filter file path to prevent path traversal vulns.
*
* @param filepath file path
* @return illegal file path return null
*/
public static String pathFilter(String filepath) {
String temp = filepath;
// use while to solve multi urlencode
while (temp.indexOf('%') != -1) {
try {
temp = URLDecoder.decode(temp, "utf-8");
} catch (UnsupportedEncodingException e) {
logger.info("Unsupported encoding exception: " + filepath);
return null;
} catch (Exception e) {
logger.info(e.toString());
return null;
}
}
if (temp.contains("../") || temp.contains("..\\")) {
return null;
}
return filepath;
}
修复要点分析
-
多层URL解码处理:
- 使用while循环处理多次URL编码的情况
- 确保所有编码后的恶意字符都能被检测到
-
路径遍历字符检测:
- 检测
../(Unix-like系统)和..\(Windows系统)路径遍历模式 - 发现这些模式直接返回null,拒绝请求
- 检测
-
安全边界:
- 在业务逻辑前进行过滤
- 过滤失败时返回明确的错误信息
进阶防护建议
-
白名单验证:
- 只允许访问特定目录下的特定类型文件
- 示例:
if (!filepath.startsWith("/safe_dir/") || !filepath.endsWith(".jpg")) { return null; }
-
规范化路径检查:
- 使用
getCanonicalPath()获取规范路径后验证 - 确保路径在预期目录下:
File file = new File(BASE_DIR, userInput); if (!file.getCanonicalPath().startsWith(BASE_DIR)) { throw new SecurityException("Invalid file path"); }
- 使用
-
使用安全API:
- Java 7+可以使用
Path和Paths类提供更安全的文件操作 - 示例:
Path path = Paths.get(BASE_DIR).resolve(userInput).normalize(); if (!path.startsWith(BASE_DIR)) { throw new SecurityException("Invalid file path"); }
- Java 7+可以使用
总结
路径遍历漏洞是Web应用常见的高危漏洞,修复关键在于:
- 永远不要信任用户输入
- 实施严格的输入验证和过滤
- 使用规范化路径检查
- 尽可能使用白名单而非黑名单
- 对多层URL编码进行解码处理
通过以上措施,可以有效防止路径遍历漏洞,保护服务器文件系统的安全。