(1)风险概述
文件上传功能允许用户将本地的文件通过Web页面提交到网站服务器上,如果不对用户上传的文件进行合法性验证,攻击者可利用Web应用系统文件上传功能(如文件上传、图像上传等)的代码缺陷来上传任意文件或者Webshell,并在服务器上运行,以达到获取Web应用系统控制权限或其他目的。
(2)缺陷编码示例:
如下是一段没有检查文件上传类型的代码,导致攻击者上传webshell脚本文件:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String contentType = request.getContentType();int ind = contentType.indexOf("boundary=");String boundary = contentType.substring(ind + 9);String pLine = new String();String uploadLocation = new String(UPLOAD_DIRECTORY_STRING);// 判断contentType是否是multipart/form-dataif (contentType != null && contentType.indexOf("multipart/form-data") != -1) {// 从HttpHeader中提取文件名BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));pLine = br.readLine();String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));// 把文件输出到上传目录try {BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation + filename, true));for (String line; (line = br.readLine()) != null; ) {if (line.indexOf(boundary) == -1) {bw.write(line);bw.newLine();bw.flush();}} //循环结束bw.close();} catch (IOException ex) {...}// output successful upload response HTML page}// output unsuccessful upload response HTML pageelse {...}}
