logo

Database

Java Uncontrolled Memory Allocation

Description

Detects Java applications vulnerable to denial of service attacks through uncontrolled memory allocation when HashMap objects are initialized with user-controlled input from HTTP requests. An attacker could exploit this by sending malicious requests that cause the application to allocate excessive memory, potentially crashing the application.

Weakness:

317 - Improper resource allocation - Memory leak

Category: Functionality Abuse

Detection Strategy

    • Check if the code imports both HashMap (from java.util) and HttpServletRequest (from jakarta.servlet.http or javax.servlet.http)

    • Look for HashMap constructor calls in the code

    • Verify if any arguments passed to the HashMap constructor are derived from user input (like HTTP request parameters)

    • Report a vulnerability if HashMap initialization uses unvalidated user input that could control the initial capacity or load factor

Vulnerable code example

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;

public class VulnerableController {
    public String allocate(HttpServletRequest request) {
        int size = Integer.parseInt(request.getParameter("size")); // Vulnerable: unchecked user input controls memory allocation
        HashMap<String, String> map = new HashMap<>(size);
        return "Created map with size: " + size;...

✅ Secure code example

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;

public class SecureController {
    private static final int MAX_MAP_SIZE = 10_000; // Limit maximum allocation size
    
    private void validateSize(String sizeParam) {
        if (sizeParam == null) {...