Vulnerability in str.format() in Python Last Updated : 06 Jan, 2025 Comments Improve Suggest changes Like Article Like Report 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.Table of ContentWhy is Case 2 a Vulnerability?Using f-stringsUsing string.Template classWhy 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-stringsf-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 : Person 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.s1and person.s2.Using string.Template classThis 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. Comment More infoAdvertise with us Next Article Vulnerability in str.format() in Python S Sowmya.L.R Follow Improve Article Tags : Python Programming Language python-string Python-string-functions Practice Tags : python 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 Formatted text in Linux Terminal using Python This article demonstrates how to print formatted text in Linux terminal using Python programming language. Formatted text(also called styled text or rich text) as opposed to plain text, has styling information like: color (text color, background color), style (bold or italic), and some other special 4 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 Python String Formatting - How to format String? String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string.You will learn different methods of string formatting with examples for better understanding. Let's look at them now!How to Format Strings in Pyt 9 min read Convert integer to string in Python In this article, weâll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function.Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string.Pythonn = 42 s = str(n) p 2 min read Convert String to Long in Python Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long. Converting String to long A long is an integer type value that has unlimited length. By converting a string into long we are transl 1 min read How to Format date using strftime() in Python ? In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime(). Syntax: time.strftime(format[, sec]) sec: This i 2 min read Like