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.)
Improper Null Termination
This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.
What is CWE-170?
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).
Ruta del atacante paso a paso
- 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
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
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
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
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:
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.
#define MAXLEN 1024
...
char *pathbuf[MAXLEN];
...
read(cfgfile,inputbuf,MAXLEN); //does not null terminate
strcpy(pathbuf,inputbuf); //requires null terminated input
... Secure pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
const safe = validateAndEscape(input);
return executeWithGuards(safe);
} 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).
How to detect CWE-170
Plexicus detecta automáticamente CWE-170 y abre un PR de corrección en menos de 60 segundos.
Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.
Frequently asked questions
¿Qué es CWE-170?
This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.
¿Qué gravedad tiene CWE-170?
MITRE califica la probabilidad de explotación como Media — la explotación es realista pero suele requerir condiciones específicas.
¿Qué lenguajes o plataformas se ven afectados por CWE-170?
MITRE lists the following affected platforms: C, C++.
¿Cómo puedo prevenir 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.
¿Cómo detecta y corrige Plexicus CWE-170?
El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-170 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.
¿Dónde puedo aprender más sobre CWE-170?
MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/170.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.
Weaknesses related to CWE-170
Improper Neutralization
This vulnerability occurs when an application fails to properly validate or sanitize structured data before it's received from an external…
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…
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…
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…
Encoding Error
This vulnerability occurs when software incorrectly transforms data between different formats, leading to corrupted or misinterpreted…
Collapse of Data into Unsafe Value
This vulnerability occurs when an application's data filtering or transformation process incorrectly merges or simplifies information,…
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…
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,…
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…
Deja de pagar por desarrollador.
Empieza a cerrar el bucle.
Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.