Description
Calling an instance method or accessing a field through a null reference in Java throws NullPointerException. Using a lookup result or external input without checking whether it exists may cause a request or task to fail.
Potential impact
- An unhandled exception may interrupt a request or background task. Repeated failures can affect availability, but dereferencing an ordinary Java
nullreference does not by itself imply termination of the whole process or memory corruption.
Remediation
- Check inputs and lookup results that may be
nullbefore using them. - Distinguish an expected missing value from a programming error, and provide the appropriate response or error handling.
- Validate required inputs and define clear return-value contracts.
Examples
Before
Declarations for userService, User and UserNotFoundException are omitted. Map the after example’s exception to an appropriate error response, and check that User.toString() does not expose sensitive information.
java
public class UserController {
public String getUserById(HttpServletRequest request) {
String userId = request.getParameter("id");
User user = userService.findUserById(userId);
return user.toString(); // Throws NullPointerException if user is null.
}
}
After
java
public class UserController {
public String getUserById(HttpServletRequest request) {
String userId = request.getParameter("id");
User user = userService.findUserById(userId);
if (user == null) {
throw new UserNotFoundException("User not found for id: " + userId);
}
return user.toString();
}
}
Explanation:
- Before:
findUserByIdmay returnnull; immediately callinguser.toString()then throwsNullPointerException. - After: Checks the lookup result and throws an application-specific exception when no user exists, avoiding that null dereference.
Related CVEs
- CVE-2005-3274: race condition causes a table to be corrupted if a timer activates while it is being modified, leading to resultant NULL dereference; also involves locking.
- CVE-2002-1912: large number of packets leads to NULL dereference
- CVE-2005-0772: packet with invalid error status value triggers NULL dereference