1473
Demonstrative Examples
Example 1:
The following code demonstrates the unrestricted upload of a file with a Java servlet and a path
traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the
Java servlet.
Example Language: HTML (Good)
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Choose a file to upload:
<input type="file" name="filename"/>
<br/>
<input type="submit" name="submit" value="Submit"/>
</form>
When submitted the Java servlet's doPost method will receive the request, extract the name of the
file from the Http request header, read the file contents from the request and output the file to the
local upload directory.
Example Language: Java (Bad)
public class FileUploadServlet extends HttpServlet {
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contentType = request.getContentType();
// the starting position of the boundary header
int ind = contentType.indexOf("boundary=");
String boundary = contentType.substring(ind+9);
String pLine = new String();
String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value
// verify that content type is multipart form data
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
// extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
...
pLine = br.readLine();
String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));
...
// output the file to the local upload directory
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();
}
} //end of for loop
bw.close();
} catch (IOException ex) {...}
// output successful upload response HTML page
}
// output unsuccessful upload response HTML page
else
{...}
}
...
}
This code does not perform a check on the type of the file being uploaded (CWE-434). This could
allow an attacker to upload any executable file or other file with malicious code.
CWE Version 4.14
CWE-669: Incorrect Resource Transfer Between Spheres
CWE-669: Incorrect Resource Transfer Between Spheres