CWE-476 Base Stable Medium likelihood

NULL Pointer Dereference

This vulnerability occurs when a program attempts to access or manipulate memory using a pointer that is set to NULL, causing a crash or unexpected behavior.

Définition

What is CWE-476?

This vulnerability occurs when a program attempts to access or manipulate memory using a pointer that is set to NULL, causing a crash or unexpected behavior.
A NULL pointer dereference happens when software fails to properly validate that a pointer points to a valid memory location before using it. This typically stems from missing or incorrect error checks after function calls that can return NULL, or from mishandling unexpected states in the code's logic. When the program then tries to read from or write to this NULL address, the system halts execution, leading to a crash, denial of service, or in some environments, a potential avenue for further exploitation. To prevent this, developers should adopt defensive programming practices. Always check pointers for NULL values after any operation that could potentially return one, especially system calls, memory allocations, or functions that fetch resources. Using static analysis tools can help catch these issues early, and implementing safe default behaviors or graceful error handling ensures the program remains stable even when unexpected NULL values are encountered.
Vulnerability Diagram CWE-476
NULL Pointer Dereference getUser(id) return null on miss u = getUser(id) u.email ← no null check SIGSEGV / NPE crash → DoS Dereferencing a missing/empty result crashes the process.
Impact réel

Real-world CVEs caused by CWE-476

  • 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.

  • large number of packets leads to NULL dereference

  • packet with invalid error status value triggers NULL dereference

  • Chain: race condition for an argument value, possibly resulting in NULL dereference

  • ssh component for Go allows clients to cause a denial of service (nil pointer dereference) against SSH servers.

  • Chain: 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).

  • Chain: race condition (CWE-362) might allow resource to be released before operating on it, leading to NULL dereference (CWE-476)

  • Chain: some unprivileged ioctls do not verify that a structure has been initialized before invocation, leading to NULL dereference

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  1. 1

    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.

  2. 2

    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().

  3. 3

    Note that this code is also vulnerable to a buffer overflow (CWE-119).

  4. 4

    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.

  5. 5

    This Android application has registered to handle a URL when sent an intent:

Exemple de code vulnérable

Vulnerable C

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.

Vulnérable C
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);}
Exemple de code sécurisé

Secure pseudo

Sécurisé pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Liste de contrôle de prévention

How to prevent CWE-476

  • 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 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.
Signaux de détection

How to detect CWE-476

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, or generate incorrect results.

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 such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself.

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 searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-476 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que CWE-476 ?

This vulnerability occurs when a program attempts to access or manipulate memory using a pointer that is set to NULL, causing a crash or unexpected behavior.

Quelle est la gravité de CWE-476 ?

MITRE évalue la probabilité d'exploitation comme Moyenne — l'exploitation est réaliste mais nécessite généralement des conditions spécifiques.

Quels langages ou plateformes sont affectés par CWE-476 ?

MITRE lists the following affected platforms: C, C++, Java, C#, Go.

Comment puis-je prévenir CWE-476 ?

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]. Select a programming language that is not susceptible to these issues.

Comment Plexicus détecte et corrige CWE-476 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-476 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-476 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/476.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Faiblesses associées

Weaknesses related to CWE-476

CWE-710 Parent

Improper Adherence to Coding Standards

This weakness occurs when developers don't consistently follow established coding standards and best practices, which can introduce…

CWE-1041 Frère

Use of Redundant Code

This weakness occurs when a codebase contains identical or nearly identical logic duplicated across multiple functions, methods, or…

CWE-1044 Frère

Architecture with Number of Horizontal Layers Outside of Expected Range

This occurs when a software system is built with either too many or too few distinct architectural layers, falling outside a recommended…

CWE-1048 Frère

Invokable Control Element with Large Number of Outward Calls

This weakness occurs when a single function, method, or callable code block makes an excessively high number of calls to other objects or…

CWE-1059 Frère

Insufficient Technical Documentation

This weakness occurs when a software or hardware product lacks comprehensive technical documentation. Missing or incomplete details about…

CWE-1061 Frère

Insufficient Encapsulation

This weakness occurs when a software component exposes too much of its internal workings, such as data structures or implementation logic.…

CWE-1065 Frère

Runtime Resource Management Control Element in a Component Built to Run on Application Servers

This weakness occurs when an application built to run on a managed application server bypasses the server's high-level APIs and instead…

CWE-1066 Frère

Missing Serialization Control Element

This weakness occurs when a class or data structure is marked as serializable but lacks the required control methods to properly handle…

CWE-1068 Frère

Inconsistency Between Implementation and Documented Design

This weakness occurs when the actual code implementation deviates from the intended design described in its official documentation,…

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.