天天看点

Java代码审计之文件上传审计与修复

​​​​​​Java代码审计系列课程​​

FileUpload-文件上传漏&洞

访问url为http://localhost:8080/file/any

直接对上传的文件保存在了指定路径下,

@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直接拼接了文件名,就可以在文件名中利用../来达到目录穿越的目的,从而将任意文件保存在任意目录下。

pic

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

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

}      
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.";
        }      
判断上传的文件是否为图片,通过ImageIO.read对文件进行读取来判断。

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

}