Description
Calling an instance method or accessing an instance field through a null reference throws NullPointerException.
Potential impact
An unhandled exception interrupts the request or background task. Repeated failures can affect service availability.
Remediation
Validate required inputs and define what a lookup returns when a value is absent. If a missing result is expected, handle it before using the value.
Examples
Before
The declarations of userService, User and UserNotFoundException are omitted.
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();
}
}
The revised lookup throws UserNotFoundException when no user is found. Map that exception to an appropriate response and check that the successful User.toString() response contains no sensitive information.
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