Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#java# 规范 1.2.1 条修订建议 #30

Closed
laingke opened this issue May 26, 2021 · 1 comment
Closed

#java# 规范 1.2.1 条修订建议 #30

laingke opened this issue May 26, 2021 · 1 comment

Comments

@laingke
Copy link

laingke commented May 26, 2021

1、问题描述
java 代码安全规范的【1.2.1 条】 文件类型限制 需补充

2、解决建议
通过后缀名进行文件类型校验不总是可靠的,建议补充魔数的校验方式

参考 List of file signatures

通用解决方案:
定义白名单的文件类型魔数枚举类,通过 commons-io 的 FileFilterUtils 类的 magicNumberFileFilter 进行过滤。

@martinzhou2015
Copy link
Collaborator

感谢贡献!同事讨论后觉得,如下方案会更简洁一些。

  1. 【建议】如果文件保存在文件服务器映射的目录(或者专门的文件管理目录),则不必对文件后缀名做控制,只要确保无法跨目录即可

  2. 如果文件保存在web容器的可执行目录,在确保无法跨目录的前提下,还必须对文件类型进行控制。禁止对.jsp、.jspx、.class、.java、.jar、.war、.xml、.js、.html、.shtml、.vbs等类型文件进行操作。最好结合业务采用白名单限制:

    • 图片类型:.jpg、.jpeg、.png、.gif、.bmp
    • 文档类型:.doc、.docx、.ppt、.pptx、.xls、.xlsx、.pdf

    可以通过以下方式限制文件类型:

@RequestMapping("/path/delete")
public void safe_delete(HttpServletRequest request) {
    /*
    *  防护方法:判断用户输入的文件后缀名是否在白名单中,是的话执行下一步操作
    */
    String webRootPath = request.getSession().getServletContext().getRealPath("/");
    String fileName = request.getParameter("name");
    if(fileName.contains("..")) {
        return;
    }
    int pos = fileName.lastIndexOf(".");
    String ext = fileName.substring(pos);
    String whiteExt = ".jpg.jpeg.png.gif.bmp";   // 文件类型白名单,根据具体情况而定
    if(whiteExt.contains(ext)) {
        new File(webRootPath + fileName).delete();
    }
}

如有不同考虑,欢迎重开问题讨论,我们将有专人跟进。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants