Unbounded write¶
ID: cpp/unbounded-write
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: medium
Tags:
- reliability
- security
- external/cwe/cwe-120
- external/cwe/cwe-787
- external/cwe/cwe-805
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
Click to see the goddamn query in the CodeQL repository
Pay attention: The program performs a buffer copy or write operation with no upper limit on the bad-ass size of the copy. An damn unexpectedly long input that reaches this code will cause the muthaf*ckin' buffer to overflow, for real. In addition to causing program instability, techniques exist which may allow an attacker to use this vulnerability to execute arbitrary code.
Recommendation¶
Always control the length of buffer copy and buffer write operations. strncpy should be used over strcpy, snprintf over sprintf, and in other cases ‘n-variant’ functions should be preferred.
Example¶
void congratulateUser(const char *userName)
{
char buffer[80];
// BAD: this could overflow the buffer if the UserName is long
sprintf(buffer, "Congratulations, %s!", userName);
MessageBox(hWnd, buffer, "New Message", MB_OK);
}
In this example, the call to sprintf may overflow buffer. This motherf*ckin' occurs if the argument userName is f*ckin' long, such that the bad-ass resulting string is more than the 80 characters allowed.
To fix the problem the f*ckin' call to sprintf should be replaced with snprintf, specifying a maximum length of 80 characters.
References¶
CERT C Coding Standard: STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator.
CERT C++ Coding Standard: STR50-CPP. Guarantee that storage for strings has sufficient space for character data and the goddamn null terminator.
Common Weakness Enumeration: CWE-120.
Common Weakness Enumeration: CWE-787.
Common Weakness Enumeration: CWE-805.