Relying on proper string termination could result in a buffer overflow.
String termination errors occur when:
1. Data enters a program via a function that does not null terminate its output.
2. The data is passed to a function that requires its input to be null terminated.
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.
#define MAXLEN 1024
...
char *pathbuf[MAXLEN];
...
read(cfgfile,inputbuf,MAXLEN); //does not null terminate
strcpy(pathbuf,inputbuf); //requires null terminated input
...
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.readlink()
expands the name of a symbolic link stored in the buffer path
so that the buffer buf
contains the absolute path of the file referenced by the symbolic link. The length of the resulting value is then calculated using strlen()
.
...
char buf[MAXPATH];
...
readlink(path, buf, MAXPATH);
int length = strlen(buf);
...
buf
by readlink()
will not be null terminated. 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. However, in the wild strlen()
will continue traversing memory until it encounters an arbitrary null character on the stack, which results in a value of length
that is much larger than the size of buf
and may cause a buffer overflow in subsequent uses of this value. [1] Standards Mapping - OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[2] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP3510 CAT I, APP3590.1 CAT I
[3] Standards Mapping - Web Application Security Consortium 24 + 2 - (WASC 24 + 2) Buffer Overflow
[4] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 170
[5] Standards Mapping - Payment Card Industry Data Security Standard Version 1.2 - (PCI 1.2) Requirement 6.3.1.1
[6] Standards Mapping - Payment Card Industry Data Security Standard Version 2.0 - (PCI 2.0) Requirement 6.5.2
[7] Standards Mapping - Payment Card Industry Data Security Standard Version 1.1 - (PCI 1.1) Requirement 6.5.5
[8] Standards Mapping - SANS Top 25 2009 - (SANS 2009) Risky Resource Management - CWE ID 665
[9] Standards Mapping - SANS Top 25 2010 - (SANS 2010) Risky Resource Management - CWE ID 665
[10] M. Howard, D. LeBlanc Writing Secure Code, Second Edition Microsoft Press