SV.FMT_STR.BAD_SCAN_FORMAT
Missing width field for format string
Improper string-length checking can result in a buffer overflow situation that can be exploited by a malicious user. The SV.FMT_STR.BAD_SCAN_FORMAT checker finds instances of omitted width specification (%s) in a format string.
Vulnerability and risk
Several string-width checking issues can result in an exploitable vulnerability. The most common are when a wide or multibyte character string is incorrectly calculated as single-byte characters, or in a case of mixed standard-width and wide-string functions for a single string. In either case, an exploitable buffer overflow condition can arise.
Mitigation and prevention
To avoid this type of error:
- Verify the length of the string unit character
- Make sure the destination buffer can handle the size of the string
- Compute the width of the string dynamically
Vulnerable code example
void main() {
char s[16];
scanf("%s",s);
}
Klockwork flags an error at line 3 because the width of the string is missing from the %s specification. Any situation in which the width field for the string is missing can result in a buffer overflow condition that can be exploited by a malicious user.
Fixed code example
void main() {
char s[16];
scanf("%15s",s);
}
In the fixed code, width of the string is provided correctly, ensuring that the destination buffer won't overflow.
Related checkers
External guidance
- CERT STR31-C: Guarantee that storage for strings has sufficient space for character data and the null terminator
- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE-125: Out-of-bounds Read
- CWE-135: Incorrect Calculation of Multi-Byte String Length
- CWE-686: Function Call With Incorrect Argument Type
- CWE-787: Out-of-bounds Write
- STIG-ID:APP3560 Application contains format string vulnerabilities
- STIG-ID:APP3590.2 Application is vulnerable to buffer overflows
Security training
Application security training materials provided by Secure Code Warrior.