430
Automated Static Analysis
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.)
Effectiveness = High
Potential Mitigations
Phase: 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.
Phase: 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.
Phase: 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.
Phase: Implementation
Switch to bounded string manipulation functions. Inspect buffer lengths involved in the buffer
overrun trace reported with the defect.
Phase: 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).
Demonstrative Examples
Example 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.
Example Language: C (Bad)
#define MAXLEN 1024
...
char *pathbuf[MAXLEN];
...
read(cfgfile,inputbuf,MAXLEN); //does not null terminate
strcpy(pathbuf,inputbuf); //requires null terminated input
...
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.
Example 2:
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().
CWE Version 4.14
CWE-170: Improper Null Termination
CWE-170: Improper Null Termination