CWE-476 Base Estável 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.

Definição

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.
Impacto no mundo real

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

Como os atacantes a exploram

Trajeto do atacante passo a passo

  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:

Exemplo de código vulnerável

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.

Vulnerável 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);}
Exemplo de código seguro

Secure pseudo

Seguro 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.
Lista de verificação de prevenção

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.
Sinais de deteção

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

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-476 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o 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.

Qual a gravidade do CWE-476?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

Que linguagens ou plataformas são afetadas pelo CWE-476?

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

Como posso prevenir o 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.

Como é que o Plexicus deteta e corrige o CWE-476?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-476 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-476?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/476.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-476

CWE-710 Pai

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 Irmão

Use of Redundant Code

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

CWE-1044 Irmão

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 Irmão

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 Irmão

Insufficient Technical Documentation

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

CWE-1061 Irmão

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 Irmão

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 Irmão

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 Irmão

Inconsistency Between Implementation and Documented Design

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

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.