You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 22 Next »

Never call any formatted I/O function with a format string containing user input.

If the user can control a format string, they can write to arbitrary memory locations. The most common form of this error is in output operation. The rarely used and often forgotten %n format specification causes the number of characters written to be written to a pointer passed on the stack.

Non-Compliant Code Example 1

In this example, the input is outputted directly as a format string. By putting %n in the input, the user can write arbitrary values to whatever the stack happens to point to. This can frequently be leveraged to execute arbitrary code. In any case, by including other point operations (such as %s), fprintf() will interpret values on the stack as pointers. This can be used to learn secret information and almost certainly can be used to crash the program.

char input[1000];
fgets(input, sizeof(input)-1, stdin);
input[sizeof(input)-1] = '\0';
fprintf(stdout, input);

Non-Compliant Code Example 2

In this example, the library function syslog() interprets the string msg as a format string, resulting in the same security problem as before. This is a common idiom for displaying the same message in multiple locations or when the message is difficult to build.

void check_password(char *user, char *password) {
  if (strcmpy(password(user), password) != 0) {
    char *msg = malloc(strlen(user) + 100);
    if (!msg) return;
    sprintf (msg, "%s password incorrect", user);
    syslog(LOG_INFO, msg);
    free(msg);
  }
}

Compliant Solution 1

This example outputs the string directly instead of building it and then outputting it.

void check_password(char *user, char *password) {
  if (strcmpy(password(user), password) \!= 0) {
    fprintf (stderr, "%s password incorrect", user);
  }
}

Compliant Solution 2

In this example, the message is built normally, but is then outputted as a string instead of a format string.

void check_password(char *user, char *password) {
  if (strcmpy(password(user), password) \!= 0) {
    char *msg = malloc(strlen(user) + 100);
    if (!msg) return;
    sprintf (msg, "%s password incorrect", user);
    fprintf (stderr, "%s", user);
    syslog(LOG_INFO, "%s", msg);
    free(msg);
  }
}

Risk Assessment

Failing to exclude user input from format specifiers may allow an attacker to execute arbitrary code.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO30-C

3 (high)

3 (probable)

3 (low)

P27

L1

References

[[ISO/IEC 9899-1999]] Section 7.19.6, "Formatted input/output functions"
[[Seacord 05]] Chapter 6, "Formatted Output"
[[Viega 05]] Section 5.2.23, "Format string problem"
[VU#649732], [VU#286468], More

  • No labels