当前位置: 首页 > news >正文

【java任意文件漏洞修复,使用文件魔数解决】

java任意文件漏洞修复,使用文件魔数解决

背景: 客户进行渗透测试,验证上传文件的程序没有对上传文件作任何过滤,导致可以上传任意文件到服务器,甚至是病毒文件和Webshell木马文件。

解决办法:对于上传的附件,验证程序要做严格验证,使用服务器端校验,而不能仅用前端验证。

代码实例

// 允许上传文件后缀
private static final String[] ALLOWED_FILE_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "doc", "docx", "xls", "xlsx", "pdf", "ppt", "pptx"};
// 允许上传文件头魔数十六进制字符串
private static final List<String> ALLOWED_MAGIC_NUMBERS = Arrays.asList("FFD8FF", "89504E47", "47494638", "25504446", "D0CF11E0", "504B0304"
);	// JPEG (jpg),PNG (png),GIF (gif),pdf,(doc、xls、ppt),(xls、pptx)// 允许上传文件的MIME类型  
private static final Set<String> ALLOWED_MIME_TYPES = new HashSet<>();
static {ALLOWED_MIME_TYPES.add("image/jpeg"); // jpg, jpeg  ALLOWED_MIME_TYPES.add("image/png");  // png  ALLOWED_MIME_TYPES.add("image/gif");  // gif  ALLOWED_MIME_TYPES.add("application/msword"); // doc  ALLOWED_MIME_TYPES.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // docx  ALLOWED_MIME_TYPES.add("application/vnd.ms-excel"); // xls  ALLOWED_MIME_TYPES.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // xlsx  ALLOWED_MIME_TYPES.add("application/pdf"); // pdf  ALLOWED_MIME_TYPES.add("application/vnd.ms-powerpoint"); // pptALLOWED_MIME_TYPES.add("application/vnd.openxmlformats-officedocument.presentationml.presentation"); // pptx  
}  @SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String fileType="";// 1.创建文件上传工厂类DiskFileItemFactory fac = new DiskFileItemFactory();// 2.创建文件上传核心类对象ServletFileUpload upload = new ServletFileUpload(fac);// 【一、设置单个文件最大1024M】upload.setFileSizeMax(1024 * 1024 * 1024);// 1024MM// 【二、设置总文件大小:2048M】upload.setSizeMax(2048 * 1024 * 1024); // 2048MList<String> StringArr=new  ArrayList<String>();// 判断,当前表单是否为文件上传表单if (upload.isMultipartContent(request)) {try {// 3.把请求数据转换为FileItem对象的集合List<FileItem> list = upload.parseRequest(request);Calendar calendar = Calendar.getInstance();int year = calendar.get(Calendar.YEAR);// 遍历,得到每一个上传项for (FileItem item : list) {// 判断:是普通表单项,还是文件上传表单项if (item.isFormField()) {// 普通表单xString fieldName = item.getFieldName();// 获取元素名称String value = item.getString("UTF-8"); // 获取元素值fileType=value;System.out.println(fieldName + " : " + value);} else {// 文件上传表单//文件保存目录路径String savePath = getServletContext().getRealPath("/") + "uploadFiles/wjgl/"+fileType+"/"+year+"/";File uploadFile = new File(savePath);if (!uploadFile.exists()) {uploadFile.mkdirs();}String oldname = item.getName(); // 上传的文件名称String fileExtension = item.getName().substring(item.getName().lastIndexOf(".") + 1);//获取到文件后缀if (!Arrays.asList(ALLOWED_FILE_EXTENSIONS).contains(fileExtension)) {//验证文件后缀response.setStatus(500);throw new FileUploadException("if1无效的文件扩展名: " + fileExtension);}String contentType = item.getContentType();if(!ALLOWED_MIME_TYPES.contains(contentType)){response.setStatus(500);throw new FileUploadException("if2无效的文件扩展名: " + fileExtension);}if (!isFileValid(item)) {// 文件有效,进行处理response.setStatus(500);throw new FileUploadException("被改了后缀,判断文件内容魔术无效的文件扩展名: " + fileExtension);}//时间戳String time=String.valueOf(new Date().getTime());String name = time+oldname;// 【三、上传到指定目录:获取上传目录路径】String realPath =  "uploadFiles/wjgl/"+fileType+"/"+year+"/";// 创建文件对象File file = new File(savePath, name);item.write(file);item.delete();response.setContentType("application/json");response.setCharacterEncoding("UTF-8");JSONObject obj = new JSONObject();obj.put("fileName", oldname);obj.put("filePath", realPath + name);StringArr.add(obj.toString());}}response.getWriter().println(StringArr);} catch (Exception e) {e.printStackTrace();}} else {System.out.println("不处理!");}}//校验是否为jpg,jpeg,png,gif,doc,docx,xls,xlsx,pdf,pptx格式
public static boolean isFileValid(FileItem fileItem) throws IOException {String fileName = fileItem.getName();try (InputStream inputStream = fileItem.getInputStream()) {return isValidFileMagicNumber(inputStream);}
}
//验证文件魔数
public static boolean isValidFileMagicNumber(InputStream inputStream) throws IOException {boolean bl=false;byte[] buffer = new byte[8];inputStream.read(buffer, 0, 8);String hexMagicNumber = bytesToHex(buffer);for(int i = 0; i<ALLOWED_MAGIC_NUMBERS.size(); i++){String ms=ALLOWED_MAGIC_NUMBERS.get(i);if(hexMagicNumber.toUpperCase().startsWith(ms)){bl=true;break;}}return bl;
}
//字节转换16进制
private static String bytesToHex(byte[] bytes) {StringBuilder hexString = new StringBuilder();for (byte b : bytes) {hexString.append(String.format("%02X", b));}return hexString.toString();
}
http://www.lryc.cn/news/307627.html

相关文章:

  • LeetCode 热题 100 | 二叉树(二)
  • mini-spring|定义标记类型Aware接口,实现感知容器对象
  • 83. 删除排序链表中的重复元素
  • 贪心算法
  • MySQL基本知识
  • Vue3 (unplugin-auto-import自动导入的使用)
  • 【漏洞复现】大华智慧园区综合管理平台信息泄露漏洞
  • JavaScript的书写方式
  • 第二十篇-推荐-纯CPU(E5-2680)推理-llama.cpp-qwen1_5-72b-chat-q4_k_m.gguf
  • CSS常见选择器
  • [LWC] Components Communication
  • Unity中URP实现水体(水下的扭曲)
  • anaconda指定目录创建环境无效/环境无法创建到指定位置
  • 《Docker极简教程》--Docker在生产环境的应用--Docker在生产环境的部署
  • 算法D31 | 贪心算法1 | 455.分发饼干 376. 摆动序列 53. 最大子序和
  • 在IDEA中创建vue hello-world项目
  • 如何获取pnpm存储目录
  • QT两个类之间使用信号槽
  • 【Ubuntu】使用WSL安装Ubuntu
  • 【Node.js】自动生成 API 文档
  • 小红书3C家电行业种草营销策略打法,纯干货
  • 防火墙的内容安全
  • Redis 管道详解
  • 【Redis】理论进阶篇------浅谈Redis的缓存穿透和雪崩原理
  • Rocky Linux安装部署Elasticsearch(ELK日志服务器)
  • Linux浅学笔记04
  • 【Day59】代码随想录之动态规划_647回文子串_516最长回文子序列
  • ECLIP
  • STM32 +合宙1.54“ 电子墨水屏(e-paper)驱动显示示例
  • 使用Postman和JMeter进行signature签名