Java代码审计:文件上传

admin 2022年1月17日03:11:34评论171 views字数 1312阅读4分22秒阅读模式
文件上传漏洞
    文件上传漏洞,是指用户上传了一个可执行的脚本文件(如jspphpasp),并通过此脚本文件获得了执行服务器端命令的能力。常见场景是web服务器允许用户上传图片或者普通文本文件保存,这种漏洞属于低成本高杀伤力。
Java代码审计:文件上传
2 漏洞代码
    允许上传任意文件导致的安全风险。
public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {    try {        byte[] bytes = file.getBytes();        Path dir = Paths.get(UPLOADED_FOLDER);        Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes); redirectAttributes.addFlashAttribute("message","上传文件成功:" + path + ""); } catch (Exception e) { return e.toString(); } return "redirect:upload_status";}
Java代码审计:文件上传

Java代码审计:文件上传

3 安全代码
    对上传文件后缀名做白名单处理。
public String singleFileUploadSafe(@RequestParam("file") MultipartFile file,                                   RedirectAttributes redirectAttributes) {    try {        byte[] bytes = file.getBytes();        String fileName = file.getOriginalFilename();        Path dir = Paths.get(UPLOADED_FOLDER);        Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
// 获取文件后缀名 String Suffix = fileName.substring(fileName.lastIndexOf("."));
String[] SuffixSafe = {".jpg", ".png", ".jpeg", ".gif", ".bmp", ".ico"}; boolean flag = false;
for (String s : SuffixSafe) { if (Suffix.toLowerCase().equals(s)) { flag = true; break; } }
if (!flag) { return "只允许上传图片,[.jpg, .png, .jpeg, .gif, .bmp, .ico]"; }
4 编码建议
  • 必须在服务器端采用白名单方式对上传或下载的文件类型、大小进行严格的限制。

  • 仅允许业务所需文件类型上传,避免上传.jsp、.jspx、.html、.exe等文件。

5 代码链接
https://github.com/j3ers3/Hello-Java-Sec
6 上期文章
Java代码审计:路径穿越

原文始发于微信公众号(Reset安全):Java代码审计:文件上传

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年1月17日03:11:34
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Java代码审计:文件上传https://cn-sec.com/archives/740780.html

发表评论

匿名网友 填写信息