Base · Medium

CWE-476: NULL Pointer Dereference

The product dereferences a pointer that it expects to be valid but is NULL.

CWE-476 · Base Level ·25 CVEs ·5 Mitigations

Description

The product dereferences a pointer that it expects to be valid but is NULL.

Potential Impact

Availability

DoS: Crash, Exit, or Restart

Integrity, Confidentiality

Execute Unauthorized Code or Commands, Read Memory, Modify Memory

Demonstrative Examples

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.
Bad
void host_lookup(char *user_supplied_addr){
                        struct hostent *hp;in_addr_t *addr;char hostname[64];in_addr_t inet_addr(const char *cp);
                           
                           /*routine that ensures user_supplied_addr is in the right format for conversion */
                           
                           validate_addr_form(user_supplied_addr);addr = inet_addr(user_supplied_addr);hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);strcpy(hostname, hp->h_name);
                     }
If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy().
Note that this code is also vulnerable to a buffer overflow (CWE-119).
In the following code, the programmer assumes that the system always has a property named "cmd" defined. If an attacker can control the program's environment so that "cmd" is not defined, the program throws a NULL pointer exception when it attempts to call the trim() method.
Bad
String cmd = System.getProperty("cmd");cmd = cmd.trim();
This Android application has registered to handle a URL when sent an intent:
Bad
...
                     IntentFilter filter = new IntentFilter("com.example.URLHandler.openURL");MyReceiver receiver = new MyReceiver();registerReceiver(receiver, filter);
                     ...
                     
                     public class UrlHandlerReceiver extends BroadcastReceiver {
                        @Overridepublic void onReceive(Context context, Intent intent) {
                              if("com.example.URLHandler.openURL".equals(intent.getAction())) {String URL = intent.getStringExtra("URLToOpen");int length = URL.length();
                                 
                                 ...
                                 }
                           }
                     }
The application assumes the URL will always be included in the intent. When the URL is not present, the call to getStringExtra() will return null, thus causing a null pointer exception when length() is called.
Consider the following example of a typical client server exchange. The HandleRequest function is intended to perform a request and use a defer to close the connection whenever the function returns.
Bad
func HandleRequest(client http.Client, request *http.Request) (*http.Response, error) {
                     
                        response, err := client.Do(request)
                        defer response.Body.Close()
                        if err != nil {
                           
                              return nil, err
                           
                        }...
                     }
If a user supplies a malformed request or violates the client policy, the Do method can return a nil response and a non-nil err.
This HandleRequest Function evaluates the close before checking the error. A deferred call's arguments are evaluated immediately, so the defer statement panics due to a nil response.

Mitigations & Prevention

Implementation

For any pointers that could have been modified or provided from a function that can return NULL, check the pointer for NULL before use. When working with a multithreaded or otherwise asynchronous environment, ensure that proper locking APIs are used to lock before the check, and unlock when it has finished [REF-1484].

Requirements

Select a programming language that is not susceptible to these issues.

Implementation Moderate

Check the results of all functions that return a value and verify that the value is non-null before acting upon it.

Architecture and Design

Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.

Implementation

Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.

Detection Methods

  • Automated Dynamic Analysis Moderate — This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash
  • Manual Dynamic Analysis — Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the program under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services su
  • Automated Static Analysis High — Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then sea
  • Automated Dynamic Analysis Moderate — Use tools that are integrated during compilation to insert runtime error-checking mechanisms related to memory safety errors, such as AddressSanitizer (ASan) for C/C++ [REF-1518].

Real-World CVE Examples

CVE IDDescription
CVE-2024-41130C++ library for LLM inference has NULL pointer dereference if a read operation fails
CVE-2005-3274race 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-1912large number of packets leads to NULL dereference
CVE-2005-0772packet with invalid error status value triggers NULL dereference
CVE-2009-4895Chain: race condition for an argument value, possibly resulting in NULL dereference
CVE-2020-29652ssh component for Go allows clients to cause a denial of service (nil pointer dereference) against SSH servers.
CVE-2009-2692Chain: Use of an unimplemented network socket operation pointing to an uninitialized handler function (CWE-456) causes a crash because of a null pointer dereference (CWE-476).
CVE-2009-3547Chain: race condition (CWE-362) might allow resource to be released before operating on it, leading to NULL dereference (CWE-476)
CVE-2009-3620Chain: some unprivileged ioctls do not verify that a structure has been initialized before invocation, leading to NULL dereference
CVE-2009-2698Chain: IP and UDP layers each track the same value with different mechanisms that can get out of sync, possibly resulting in a NULL dereference
CVE-2009-2692Chain: Use of an unimplemented network socket operation pointing to an uninitialized handler function (CWE-456) causes a crash because of a null pointer dereference (CWE-476)
CVE-2009-0949Chain: improper initialization of memory can lead to NULL dereference
CVE-2008-3597Chain: game server can access player data structures before initialization has happened leading to NULL dereference
CVE-2020-6078Chain: The return value of a function returning a pointer is not checked for success (CWE-252) resulting in the later use of an uninitialized variable (CWE-456) and a null pointer dereference (CWE-476
CVE-2008-0062Chain: a message having an unknown message type may cause a reference to uninitialized memory resulting in a null pointer dereference (CWE-476) or dangling pointer (CWE-825), possibly crashing the sys

Showing 15 of 25 observed examples.

Taxonomy Mappings

  • 7 Pernicious Kingdoms: — Null Dereference
  • CLASP: — Null-pointer dereference
  • PLOVER: — Null Dereference (Null Pointer Dereference)
  • OWASP Top Ten 2004: A9 — Denial of Service
  • CERT C Secure Coding: EXP34-C — Do not dereference null pointers
  • Software Fault Patterns: SFP7 — Faulty Pointer Use

Frequently Asked Questions

What is CWE-476?

CWE-476 (NULL Pointer Dereference) is a software weakness identified by MITRE's Common Weakness Enumeration. It is classified as a Base-level weakness. The product dereferences a pointer that it expects to be valid but is NULL.

How can CWE-476 be exploited?

Attackers can exploit CWE-476 (NULL Pointer Dereference) to dos: crash, exit, or restart. This weakness is typically introduced during the Implementation phase of software development.

How do I prevent CWE-476?

Key mitigations include: For any pointers that could have been modified or provided from a function that can return NULL, check the pointer for NULL before use. When working with a multithreaded or otherwise asynchronous envi

What is the severity of CWE-476?

CWE-476 is classified as a Base-level weakness (Medium abstraction). It has been observed in 25 real-world CVEs.