(1)风险概述
    文件上传功能允许用户将本地的文件通过Web页面提交到网站服务器上,如果不对用户上传的文件进行合法性验证,攻击者可利用Web应用系统文件上传功能(如文件上传、图像上传等)的代码缺陷来上传任意文件或者Webshell,并在服务器上运行,以达到获取Web应用系统控制权限或其他目的。
    (2)缺陷编码示例:
    如下是一段没有检查文件上传类型的代码,导致攻击者上传webshell脚本文件:

    1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    2. response.setContentType("text/html");
    3. PrintWriter out = response.getWriter();
    4. String contentType = request.getContentType();
    5. int ind = contentType.indexOf("boundary=");
    6. String boundary = contentType.substring(ind + 9);
    7. String pLine = new String();
    8. String uploadLocation = new String(UPLOAD_DIRECTORY_STRING);
    9. // 判断contentType是否是multipart/form-data
    10. if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
    11. // 从HttpHeader中提取文件名
    12. BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    13. pLine = br.readLine();
    14. String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));
    15. // 把文件输出到上传目录
    16. try {
    17. BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation + filename, true));
    18. for (String line; (line = br.readLine()) != null; ) {
    19. if (line.indexOf(boundary) == -1) {
    20. bw.write(line);
    21. bw.newLine();
    22. bw.flush();
    23. }
    24. } //循环结束
    25. bw.close();
    26. } catch (IOException ex) {...}
    27. // output successful upload response HTML page
    28. }
    29. // output unsuccessful upload response HTML page
    30. else {...}
    31. }