• java代码审计-文件操作


    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 (查看系统版本)

    image.png

    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

  • 相关阅读:
    【0基础学算法】前缀和 (超详细讲解+私人笔记+源码)
    Xcode编译流程
    VMWare 虚拟机如何通过新增挂载点的方式扩展磁盘空间
    java计算机毕业设计高校教学资源库设计与实现---MyBatis+系统+LW文档+源码+调试部署
    MyBatis动态SQL多表操作
    【项目实战合集】计算机视觉毕业设计项目怎么选,超30个经典案例供你选择...
    XML概述
    Julia绘图初步:Plots
    学习开发一个RISC-V上的操作系统(汪辰老师) — 环境配置
    【LeetCode】Day95-有效的数独&矩阵置零
  • 原文地址:https://www.cnblogs.com/Ne2o1/p/17188436.html