This is a student-friendly explanation of the software weakness CWE-787 “Out-of-bounds write”, where the vulnerable entity writes data past the end, or before the beginning, of the intended buffer.
This can be caused by incorrect pointer arithmetic (see Example 1), accessing invalid pointers due to incomplete initialisation or memory release (see Example 2), etc.
Example 1
In the adjacent C code, char pointer p is allocated only 1 byte, but two bytes away from p, a value of 1 is stored.
Reminder: In a POSIX environment, a C program can be compiled and linked into an executable using command gcc cfilename -o exefilename.
#include <stdlib.h>
int main() {
char *p;
p = (char *)malloc(1);
*(p+2) = 1;
return 0;
}
Example 2
In the adjacent C code, after the memory allocated to p is freed, p points to a non-existent buffer, but then a value is stored in the nonexistent buffer.
Typically, the weakness CWE-787 can result in corruption of data, a crash, or code execution.
🛡 General mitigation
A long list of mitigation measures exist, so only a few are mentioned here:
Use a safe programming language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows.
Other languages, such as Ada and C# (see Example 3), typically provide overflow protection, but the protection can be disabled by the programmer.
Nevertheless, a language’s interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Use a vetted library or framework that is not vulnerable to CWE-787, e.g., Intel’s Safe String Library, and Microsoft’s Strsafe.h library. 👈 These libraries provide safer versions of overflow-prone string-handling functions.
Use compilers or compiler extensions that support automatic detection of buffer overflows, e.g., Microsoft Visual Studio with its buffer security check (/GS) flag, the FORTIFY_SOURCE macro on Red Hat Linux platforms, GCC with a range of stack protection flags (that evolved from StackGuard and ProPolice).