Vulnerability in str.format() in Python
Last Updated :
06 Jan, 2025
str.format() is one of the string formatting methods in Python, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. But the vulnerability comes when our Python app uses str.format in the user-controlled string.
Let’s understand with the help of an example:
Python
# Sensitive configuration data
CONFIG = {
"KEY": "ASXFYFGK78989"
}
class Person:
def __init__(self, s1, s2):
self.s1 = s1
self.s2 = s2
def fun(template, person):
return template.format(person_obj=person)
# Create a person object
person = Person("GEEKS", "FORGEEKS")
# Case 1: Safe input
a= "Avatar_{person_obj.s1}_{person_obj.s2}"
print(fun(a, person))
# Case 2: Malicious input
b= "{person_obj.__init__.__globals__[CONFIG][KEY]}"
print(fun(b, person))
OutputAvatar_GEEKS_FORGEEKS
ASXFYFGK78989
Explanation:
Person
Class: This class defines a template for creating people with s1
and s2
attributes.fun
Function: This function dynamically formats a string using the person
object.- Case 1 (Safe input):This is the expected, safe result, where the placeholders are replaced with valid values from the
person
object. - Case 2(Malicious Input):This is a dangerous situation where a malicious user can exploit the
str.format()
method to retrieve sensitive data from the global context.
Why is Case 2 a Vulnerability?
str.format()
method can evaluate expressions within the format string, allowing access to variables and object details. This means a user can manipulate the input to access sensitive data, like the CONFIG
dictionary. This creates a security risk because attackers could retrieve information they should not have access to.
Using f-strings
f-strings provide a more controlled way of formatting strings and do not evaluate arbitrary expressions. They are safer and faster than str.format()
.
Python
class Person:
def __init__(self, s1, s2):
self.s1 = s1
self.s2= s2
# Create a person object
person = Person("Geeks", "ForGeeks")
# Use f-string for formatting
a = f"Avatar_{person.s1}_{person.s2}"
print(a)
OutputAvatar_Geeks_ForGeeks
Explanation:
- Class and Object : P
erson
class is defined with attributes s1
and s2
, and an object person
is created with values "Geeks"
fors1
and "ForGeeks"
for s2
. - f-string Formatting: This is used to format and print the string as
"Avatar_Geeks_ForGeeks"
, inserting the values of person.s1
and person.s2
.
Using string.Template class
This is a
simpler, safer alternative to str.format()
, as it only supports simple placeholder replacements ($variable
) and does not evaluate Python expressions.
Python
from string import Template
class Person:
def __init__(self, s1, s2):
self.s1 = s1
self.s2= s2
# Create a person object
person = Person("Geeks", "ForGeeks")
# Safe way using string.Template
template = Template("Avatar_${s1}_${s2}")
a = template.substitute(s1=person.s1, s2=person.s2)
print(a)
OutputAvatar_Geeks_ForGeeks
Explanation:
- Class and Object:
Person
class is created with s1
and s2
attributes, and a person
object is initialized with "Geeks"
and "ForGeeks"
. - Template Substitution:
This
substitutes ${s1}
and ${s2}
with the object's attributes.
Similar Reads
Vulnerability in input() function â Python 2.x This article aims to explain and explore the vulnerability in the input() function in Python 2.x. In Python 3, the raw_input() function was erased, and its functionality was transferred to a new built-in function known as input(). Different Ways to Input Data in Python 2.xThere are two common method
5 min read
How to use String Formatters in Python In Python, we use string formatting to control how text is displayed. It allows us to insert values into strings and organize the output in a clear and readable way. In this article, weâll explore different methods of formatting strings in Python to make our code more structured and user-friendly.Us
3 min read
What does %s mean in a Python format string? In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable. This placeholder is part of Python's older string formatting method, using the % o
3 min read
Python Modulo String Formatting In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f -
2 min read
Format a Number Width in Python Formatting numbers to a fixed width is a common requirement in various programming tasks, especially when dealing with data presentation or storage. By understanding these techniques, developers can ensure consistent and visually appealing formatting of numerical data in their Python. Format a Numbe
3 min read