431
Example Language: C (Bad)
char buf[MAXPATH];
...
readlink(pathname, buf, MAXPATH);
int length = strlen(buf);
...
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.
Example 3:
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:
Example Language: C (Bad)
#include <stdio.h>
#include <string.h>
int main() {
char longString[] = "String signifying nothing";
char shortString[16];
strncpy(shortString, longString, 16);
printf("The last character in shortString is: %c (%1$x)\n", shortString[15]);
return (0);
}
The above code gives the following output: "The last character in shortString is: n (6e)". So, the
shortString array does not end in a NULL character, even though the "safe" string function strncpy()
was used. The reason is that strncpy() does not impliciitly add a NULL character at the end of the
string when the source is equal in length or longer than the provided size.
Observed Examples
Reference Description
CVE-2000-0312 Attacker does not null-terminate argv[] when invoking another program.
https://www.cve.org/CVERecord?id=CVE-2000-0312
CVE-2003-0777 Interrupted step causes resultant lack of null termination.
https://www.cve.org/CVERecord?id=CVE-2003-0777
CVE-2004-1072 Fault causes resultant lack of null termination, leading to buffer expansion.
https://www.cve.org/CVERecord?id=CVE-2004-1072
CVE-2001-1389 Multiple vulnerabilities related to improper null termination.
https://www.cve.org/CVERecord?id=CVE-2001-1389
CVE-2003-0143 Product does not null terminate a message buffer after snprintf-like call,
leading to overflow.
https://www.cve.org/CVERecord?id=CVE-2003-0143
CVE-2009-2523 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).
https://www.cve.org/CVERecord?id=CVE-2009-2523
MemberOf Relationships
CWE Version 4.14
CWE-170: Improper Null Termination
CWE-170: Improper Null Termination