NEVER use printf
directly with user input as the format string. ALWAYS sanitize user inputs to prevent format string attacks and other injection vulnerabilities.
printf
or similar functions.Bad Code:
char *input = readAString();
printf(input); // Vulnerable to format string attacks
%
signs, printf
will attempt to use them as format specifiers, causing unintended behavior.%d
or %s
to read memory contents.%n
format specifier writes the number of characters printed so far to a specified memory location, allowing attackers to modify memory.Correct Code:
char *input = readAString();
printf("%s", input); // Safe usage
%s
to print user input to avoid interpreting it as a format string.Safe Conditional Format String:
const char *fmt = "%d\\\\n";
if (printInHex) {
fmt = "%x\\\\n";
}
printf(fmt, someNumber);
Command Injection:
// Dangerous: if strFromUser contains backticks, it can execute commands
char command[256];
snprintf(command, sizeof(command), "someCommand %s", strFromUser);
system(command);
SQL Injection:
// Vulnerable: user input can terminate the current SQL statement and inject new ones
char query[256];
snprintf(query, sizeof(query), "SELECT * from Users WHERE name='%s'", strFromUser);
executeSQL(query);