1. Overview:
In Python, strings can be formatted using
f-strings,
.format(), or
% formatting.
F-strings allow inline expression evaluation and string interpolation.
Example:
name = "Dipesh"
print(f"My name is {name}")
Here, the
f before the string tells Python to evaluate expressions inside
{} before printing.
Not vulnerable in Python:
Python’s
print() function does not interpret user input as a format string in an unsafe way.
Even with f-strings, Python evaluates expressions before printing—you cannot inject arbitrary format specifiers into raw print calls like in C.
Format string vulnerabilities happen in lower-level languages like C, where unsanitized user input is passed to formatting functions such as
printf().
2. Vulnerability from an Attacker Perspective:
2.1 Attempts of an attacker (C example for comparison):
char user_input[100]; // Creates a string buffer
scanf("%s", user_input); // Reads user input
printf(user_input); // Prints directly (vulnerable)
If an attacker enters:
%x %x %x %x
They can read memory and potentially execute arbitrary code.
Python is safe because it does not interpret user input as format specifiers in print statements.
3. Vulnerability from a Defender Perspective:
3.1 Solutions for defenders (best practices in Python):
- Always treat user input as data, not code.
- Use
f-strings, .format(), or string concatenation safely:
user_input = input("Enter your name: ")
print(f"Hello {user_input}") # Safe
print("Hello {}".format(user_input)) # Safe
Avoid
eval() on untrusted input—this is the only Python operation that can execute user-provided code.