freeBuf
主站

分类

漏洞 工具 极客 Web安全 系统安全 网络安全 无线安全 设备/客户端安全 数据安全 安全管理 企业安全 工控安全

特色

头条 人物志 活动 视频 观点 招聘 报告 资讯 区块链安全 标准与合规 容器安全 公开课

官方公众号企业安全新浪微博

FreeBuf.COM网络安全行业门户,每日发布专业的安全资讯、技术剖析。

FreeBuf+小程序

FreeBuf+小程序

Java代码审计之路径遍历
2022-07-05 16:02:13
所属地 福建省

缺陷代码

/**
 * 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.";
	}
}

源码目录的上一层,有test.txt文件,使用../成功读取到上一层目录下的文件内容
图片.png

跟踪代码

图片.png
发现只是判断是否有存在,存在的话就以为base64编码形式输出
图片.png

修复方法

path_traversal/sec
对应的修复后的方法如下,调用了SecurityUtil.pathFilter对用户的输入进行检查。

@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);
}

这里对目录穿越的..进行了过滤,避免了目录穿越。只不过这里一个用作图片读取的api也可以读取项目任意文件倒也可以说是算一个小漏洞。

/**
 * 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 sovle 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.charAt(0) == '/') {
		return null;
	}

	return filepath;
}

图片.png

跟踪代码

发现SecurityUtil.pathFilter方法,先进入该方法
图片.png
发现有%号就进入(../这种特殊字符会被url编码成%),所以这是过滤特殊字符
过滤后再判断是否有../,有的话返回null
图片.png
最后跳出方法,返回为null的话就输出 Bad boy. Illegal file path.
图片.png
图片.png

# 代码审计 # 代码审计入门
本文为 独立观点,未经允许不得转载,授权请联系FreeBuf客服小蜜蜂,微信:freebee2022
被以下专辑收录,发现更多精彩内容
+ 收入我的专辑
+ 加入我的收藏
相关推荐
  • 0 文章数
  • 0 关注者
文章目录