336
}
message[index] = '\0';
// process message
success = processMessage(message);
}
return success;
}
However, the message length variable from the structure is used as the condition for ending the
for loop without validating that the message length variable accurately reflects the length of the
message body (CWE-606). This can result in a buffer over-read (CWE-125) by reading from
memory beyond the bounds of the buffer if the message length variable indicates a length that is
longer than the size of a message body (CWE-130).
Example 2:
The following C/C++ example demonstrates a buffer over-read due to a missing NULL terminator.
The main method of a pattern matching utility that looks for a specific pattern within a specific file
uses the string strncopy() method to copy the command line user input file name and pattern to the
Filename and Pattern character arrays respectively.
Example Language: C (Bad)
int main(int argc, char **argv)
{
char Filename[256];
char Pattern[32];
/* Validate number of parameters and ensure valid content */
...
/* copy filename parameter to variable, may cause off-by-one overflow */
strncpy(Filename, argv[1], sizeof(Filename));
/* copy pattern parameter to variable, may cause off-by-one overflow */
strncpy(Pattern, argv[2], sizeof(Pattern));
printf("Searching file: %s for the pattern: %s\n", Filename, Pattern);
Scan_File(Filename, Pattern);
}
However, the code do not take into account that strncpy() will not add a NULL terminator when the
source buffer is equal in length of longer than that provide size attribute. Therefore if a user enters
a filename or pattern that are the same size as (or larger than) their respective character arrays, a
NULL terminator will not be added (CWE-170) which leads to the printf() read beyond the expected
end of the Filename and Pattern buffers.
To fix this problem, be sure to subtract 1 from the sizeof() call to allow room for the null byte to be
added.
Example Language: C (Good)
/* copy filename parameter to variable, no off-by-one overflow */
strncpy(Filename, argv[2], sizeof(Filename)-1);
Filename[255]='\0';
/* copy pattern parameter to variable, no off-by-one overflow */
strncpy(Pattern, argv[3], sizeof(Pattern)-1);
Pattern[31]='\0';
Observed Examples
Reference Description
CVE-2022-1733 Text editor has out-of-bounds read past end of line while indenting C code
https://www.cve.org/CVERecord?id=CVE-2022-1733
CVE-2014-0160 Chain: "Heartbleed" bug receives an inconsistent length parameter (CWE-130)
enabling an out-of-bounds read (CWE-126), returning memory that could
include private cryptographic keys and other sensitive data.
CWE Version 4.14
CWE-127: Buffer Under-read
CWE-127: Buffer Under-read