java代码审计-文件操作

admin 2023年4月3日09:19:39评论24 views字数 3619阅读12分3秒阅读模式

0x01 任意文件读取

@GetMapping("/path_traversal/vul")
public String getImage(String filepath) throws IOException {
return getImgBase64(filepath);
}

这里的路由对应的方法是getImgBase64(),看名字是用作图片读取转base64输出的。但是这里没有对输入进行过滤检查,只是简单判断文件存在且不是文件夹,就对其进行读取输出。imgFile里面存放的都是图片

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

成功读取base64编码后的系统/etc/passwd文件,windows系统可以读取c:boot.ini(查看系统版本)

java代码审计-文件操作

0x02 任意文件读取-修复方法

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也可以读取项目同级目录下任意文件倒也可以说是算一个小漏洞,所以同级目录下只存放图片才比较安全

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

0x03 任意文件上传

    @PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes)
{
if (file.isEmpty()) {
// 赋值给uploadStatus.html里的动态参数message
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/file/status";
}

try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);

redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + UPLOADED_FOLDER + file.getOriginalFilename() + "'");

} catch (IOException e) {
redirectAttributes.addFlashAttribute("message", "upload failed");
logger.error(e.toString());
}

return "redirect:/file/status";
}

没有任何的后缀名及内容过滤,可以上传任意的恶意文件。在这里上传目录在/tmp下,同时文件的写入时用的Files.write(path, bytes),这里的path就是保存的路径,由于是保存的目录/tmp直接拼接了文件名,就可以在文件名中利用../来达到目录穿越的目的,从而将任意文件保存在任意目录下

0x04 任意文件上传-漏洞修复

限制只能上传图片,同时进行多重验证

 // 判断文件后缀名是否在白名单内  校验1
String[] picSuffixList = {".jpg", ".png", ".jpeg", ".gif", ".bmp", ".ico"};
boolean suffixFlag = false;
for (String white_suffix : picSuffixList) {
if (Suffix.toLowerCase().equals(white_suffix)) {
suffixFlag = true;
break;
}
}

对文件后缀名进行白名单限制,只能为白名单中的图片后缀名。(绕过方式:XXX.JSP.PNG

    // 判断MIME类型是否在黑名单内 校验2
String[] mimeTypeBlackList = {
"text/html",
"text/javascript",
"application/javascript",
"application/ecmascript",
"text/xml",
"application/xml"
};
for (String blackMimeType : mimeTypeBlackList) {
// 用contains是为了防止text/html;charset=UTF-8绕过
if (SecurityUtil.replaceSpecialStr(mimeType).toLowerCase().contains(blackMimeType)) {
logger.error("[-] Mime type error: " + mimeType);
//deleteFile(filePath);
return "Upload failed. Illeagl picture.";
}
}

对MIME类型进行了黑名单限制,不过这个可以进行抓包修改绕过

File excelFile = convert(multifile);//文件名字做了uuid处理
String filePath = excelFile.getPath();
// 判断文件内容是否是图片 校验3
boolean isImageFlag = isImage(excelFile);
if (!isImageFlag) {
logger.error("[-] File is not Image");
deleteFile(filePath);
return "Upload failed. Illeagl picture.";
}

文件保存的时候路径是通过 来获取,Path path = excelFile.toPath();就避免了路径穿越的实现

private static boolean isImage(File file) throws IOException {
BufferedImage bi = ImageIO.read(file);
return bi != null;
}

最后判断上传的文件内容是否为图片,通过ImageIO.read对文件进行读取来判断

0x03 总结

关键词:FileUpload

原文链接:https://www.cnblogs.com/Ne2o1/p/17188436.html

原文始发于微信公众号(亿人安全):java代码审计-文件操作

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年4月3日09:19:39
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   java代码审计-文件操作http://cn-sec.com/archives/1648744.html

发表评论

匿名网友 填写信息