Allowing an attacker to control a function's format string can result in a buffer overflow.
Format string vulnerabilities occur when an attacker is allowed to control the format string argument to a function like sprintf()
, FormatMessageW()
, or syslog()
.
Example 1: The following code copies a command line argument into a buffer using snprintf()
.
int main(int argc, char **argv){
char buf[128];
...
snprintf(buf,128,argv[1]);
}
%x
, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.) By using the %n
formatting directive, the attacker can write to the stack, causing snprintf()
to write the number of bytes output thus far to the specified argument (rather than reading a value from the argument, which is the intended behavior). A sophisticated version of this attack will use four staggered writes to completely control the value of a pointer on the stack.
printf("%d %d %1$d %1$d\n", 5, 9);
5 9 5 5
syslog()
function is sometimes used as follows:
...
syslog(LOG_ERR, cmdBuf);
...
syslog()
is a format string, any formatting directives included in cmdBuf
are interpreted as described in Example 1. syslog()
:
...
syslog(LOG_ERR, "%s", cmdBuf);
...
[1] Standards Mapping - OWASP Top 10 2004 - (OWASP 2004) A5 Buffer Overflow
[2] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP3510 CAT I, APP3560 CAT I
[3] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP3510 CAT I, APP3590.1 CAT I
[4] Standards Mapping - Web Application Security Consortium 24 + 2 - (WASC 24 + 2) Buffer Overflow
[5] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 134
[6] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 787, CWE ID 120, CWE ID 129, CWE ID 131
[7] Standards Mapping - Web Application Security Consortium 24 + 2 - (WASC 24 + 2) Format String Attack
[8] T. Newsham Format String Attacks Guardent, Inc.
[9] Standards Mapping - Payment Card Industry Data Security Standard Version 1.2 - (PCI 1.2) Requirement 6.3.1.1
[10] Standards Mapping - Payment Card Industry Data Security Standard Version 2.0 - (PCI 2.0) Requirement 6.5.2
[11] Standards Mapping - Payment Card Industry Data Security Standard Version 1.1 - (PCI 1.1) Requirement 6.5.5
[12] Standards Mapping - SANS Top 25 2009 - (SANS 2009) Risky Resource Management - CWE ID 119
[13] Standards Mapping - SANS Top 25 2010 - (SANS 2010) Risky Resource Management - CWE ID 120, Risky Resource Management - CWE ID 129, Risky Resource Management - CWE ID 131