logo

Database

Java Unrestricted File Upload

Description

Detects unrestricted file upload vulnerabilities in Java applications where user-controlled data is directly used in file operations. This could allow attackers to upload malicious files or overwrite sensitive system files, potentially leading to remote code execution or system compromise.

Weakness:

027 - Insecure file upload

Category: Access Subversion

Detection Strategy

    Check if Java NIO file operations are imported in the code (java.nio.file)

    Look for suspicious file operation methods called on the Files class (like write, copy, move)

    Verify if any parameters to these file operations come from user-controllable input

    Flag cases where user input is used in file operations without proper validation

Vulnerable code example

import java.nio.file.*;
import javax.servlet.http.*;

public class VulnerableUpload extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String fileName = req.getParameter("name");  // Untrusted user input
            Path filePath = Paths.get("/uploads", fileName);...

✅ Secure code example

import java.nio.file.*;
import javax.servlet.http.*;
import java.io.IOException;
import org.apache.tika.Tika;

public class SecureUpload extends HttpServlet {
    private static final long MAX_SIZE = 10_485_760; // 10MB limit
    private static final Path UPLOAD_DIR = Paths.get("/var/app/secure_uploads");...