CWE-170 Base Incompleto Medium likelihood

Improper Null Termination

This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.

Definição

What is CWE-170?

This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.
Improper null termination typically stems from two common coding mistakes. The first is an off-by-one error, where a null character is written just outside the allocated memory boundary, which can corrupt adjacent data or trigger a buffer overflow. The second frequent cause is the incorrect use of functions like `strncpy()`, which does not automatically append a null terminator if the source string is too long, leaving the destination array without a valid end marker. Without this crucial terminator, string-handling functions will continue reading memory until they encounter a null byte by chance, leading to information disclosure, crashes, or unpredictable behavior. Developers should always ensure buffers are sized to hold the content plus the terminator and prefer safer, bounded string functions that guarantee proper termination.
Impacto no mundo real

Real-world CVEs caused by CWE-170

  • Attacker does not null-terminate argv[] when invoking another program.

  • Interrupted step causes resultant lack of null termination.

  • Fault causes resultant lack of null termination, leading to buffer expansion.

  • Multiple vulnerabilities related to improper null termination.

  • Product does not null terminate a message buffer after snprintf-like call, leading to overflow.

  • Chain: product does not handle when an input string is not NULL terminated (CWE-170), leading to buffer over-read (CWE-125) or heap-based buffer overflow (CWE-122).

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    The following code reads from cfgfile and copies the input into inputbuf using strcpy(). The code mistakenly assumes that inputbuf will always contain a NULL terminator.

  2. 2

    The code above will behave correctly if the data read from cfgfile is null terminated on disk as expected. But if an attacker is able to modify this input so that it does not contain the expected NULL character, the call to strcpy() will continue copying from memory until it encounters an arbitrary NULL character. This will likely overflow the destination buffer and, if the attacker can control the contents of memory immediately following inputbuf, can leave the application susceptible to a buffer overflow attack.

  3. 3

    In the following code, readlink() expands the name of a symbolic link stored in pathname and puts the absolute path into buf. The length of the resulting value is then calculated using strlen().

  4. 4

    The code above will not always behave correctly as readlink() does not append a NULL byte to buf. Readlink() will stop copying characters once the maximum size of buf has been reached to avoid overflowing the buffer, this will leave the value buf not NULL terminated. In this situation, strlen() will continue traversing memory until it encounters an arbitrary NULL character further on down the stack, resulting in a length value that is much larger than the size of string. Readlink() does return the number of bytes copied, but when this return value is the same as stated buf size (in this case MAXPATH), it is impossible to know whether the pathname is precisely that many bytes long, or whether readlink() has truncated the name to avoid overrunning the buffer. In testing, vulnerabilities like this one might not be caught because the unused contents of buf and the memory immediately following it may be NULL, thereby causing strlen() to appear as if it is behaving correctly.

  5. 5

    While the following example is not exploitable, it provides a good example of how nulls can be omitted or misplaced, even when "safe" functions are used:

Exemplo de código vulnerável

Vulnerable C

The following code reads from cfgfile and copies the input into inputbuf using strcpy(). The code mistakenly assumes that inputbuf will always contain a NULL terminator.

Vulnerável C
#define MAXLEN 1024
  ...
  char *pathbuf[MAXLEN];
  ...
  read(cfgfile,inputbuf,MAXLEN); //does not null terminate
  strcpy(pathbuf,inputbuf); //requires null terminated input
  ...
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-170

  • Requirements Use a language that is not susceptible to these issues. However, be careful of null byte interaction errors (CWE-626) with lower-level constructs that may be written in a language that is susceptible.
  • Implementation Ensure that all string functions used are understood fully as to how they append null characters. Also, be wary of off-by-one errors when appending nulls to the end of strings.
  • Implementation If performance constraints permit, special code can be added that validates null-termination of string buffers, this is a rather naive and error-prone solution.
  • Implementation Switch to bounded string manipulation functions. Inspect buffer lengths involved in the buffer overrun trace reported with the defect.
  • Implementation Add code that fills buffers with nulls (however, the length of buffers still needs to be inspected, to ensure that the non null-terminated string is not written at the physical end of the buffer).
Sinais de deteção

How to detect CWE-170

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-170 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-170?

This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.

Qual a gravidade do CWE-170?

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-170?

MITRE lists the following affected platforms: C, C++.

Como posso prevenir o CWE-170?

Use a language that is not susceptible to these issues. However, be careful of null byte interaction errors (CWE-626) with lower-level constructs that may be written in a language that is susceptible. Ensure that all string functions used are understood fully as to how they append null characters. Also, be wary of off-by-one errors when appending nulls to the end of strings.

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

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-170 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-170?

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

Fraquezas relacionadas

Weaknesses related to CWE-170

CWE-707 Pai

Improper Neutralization

This vulnerability occurs when an application fails to properly validate or sanitize structured data before it's received from an external…

CWE-116 Irmão

Improper Encoding or Escaping of Output

This vulnerability occurs when an application builds a structured message—like a query, command, or request—for another component but…

CWE-138 Irmão

Improper Neutralization of Special Elements

This vulnerability occurs when an application accepts external input but fails to properly sanitize special characters or syntax that have…

CWE-1426 Irmão

Improper Validation of Generative AI Output

This vulnerability occurs when an application uses a generative AI model (like an LLM) but fails to properly check the AI's output before…

CWE-172 Irmão

Encoding Error

This vulnerability occurs when software incorrectly transforms data between different formats, leading to corrupted or misinterpreted…

CWE-182 Irmão

Collapse of Data into Unsafe Value

This vulnerability occurs when an application's data filtering or transformation process incorrectly merges or simplifies information,…

CWE-20 Irmão

Improper Input Validation

This vulnerability occurs when an application accepts data from an external source but fails to properly verify that the data is safe and…

CWE-228 Irmão

Improper Handling of Syntactically Invalid Structure

This vulnerability occurs when software fails to properly reject or process input that doesn't follow the expected format or structure,…

CWE-240 Irmão

Improper Handling of Inconsistent Structural Elements

This vulnerability occurs when a system fails to properly manage situations where related data structures or elements should match but are…

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.