Unbounded write¶
ID: cpp/unbounded-writeKind: path-problemSecurity severity: 9.3Severity: errorPrecision: mediumTags: - reliability - security - external/cwe/cwe-120 - external/cwe/cwe-787 - external/cwe/cwe-805Query suites: - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
The program performs a buffer copy or write operation with no upper limit on the size of the copy. An unexpectedly long input that reaches this code will cause the buffer to overflow. 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 overstrcpy,snprintf oversprintf, and in other cases ‘n-variant’ functions should be preferred.
Example¶
voidcongratulateUser(constchar*userName){charbuffer[80];// BAD: this could overflow the buffer if the UserName is longsprintf(buffer,"Congratulations, %s!",userName);MessageBox(hWnd,buffer,"New Message",MB_OK);}
In this example, the call tosprintf may overflowbuffer. This occurs if the argumentuserName is very long, such that the resulting string is more than the 80 characters allowed.
To fix the problem the call tosprintf should be replaced withsnprintf, 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 null terminator.
Common Weakness Enumeration:CWE-120.
Common Weakness Enumeration:CWE-787.
Common Weakness Enumeration:CWE-805.