type of software vulnerability
Wikipedia
en.wikipedia.org › wiki › Uncontrolled_format_string
Uncontrolled format string - Wikipedia
December 21, 2025 - Uncontrolled format string is a type of code injection vulnerability discovered around 1989 that can be used in security exploits. Originally thought harmless, format string exploits can be used to crash a program or to execute harmful code. The problem stems from the use of unchecked user ...
Top answer 1 of 3
9
Good instinct. Yes, an attacker being able to supply arbitrary format string is a vulnerability under python.
- The denial of service is probably the most simple to address. In this case, limiting the size of the string or the number of operators within the string will mitigate this issue. There should be a setting where no reasonable user will need to generate a string with more variables than X, and this amount of computation isn't at risk of being exploited in a DoS attack.
- Being able to access attributes within an object could be dangerous.
However, I don't think that the
Objectparent class has any useful information. The object supplied to the format would have to contain something sensitive. In any case, this type of notation can limited with a regular expression. - If the format strings are user supplied then a user might need to know the error message for debugging. However, error mesages can contain senstive information such as local paths or class names. Make sure to limit the information that an attacker can obtain.
Look over the python format string specification and forbid functionality you don't want the user to have with a regex.
2 of 3
4
This simple Formatter override blocks users from accessing attributes. It still allows formatting and conversion of types.
from string import Formatter
class SafeFormatter(Formatter):
def get_field(self, field_name, args, kwargs):
if not str.isidentifier(field_name):
raise ValueError(
f"Invalid format string, {field_name!r} is not a valid identifier"
)
return super().get_field(field_name, args, kwargs)
Usage example:
>>> safe_formatter = SafeFormatter()
>>> safe_formatter.format("Number {num} is id={id}", num=1, id="hello")
'Number 1 is hello'
>>> safe_formatter.format("Number {num} is {id.__class__}", num=1, id="hello")
Traceback (most recent call last):
File "<python-input-3>", line 1, in <module>
safe_formatter.format("Number {num} is {id.__class__}", num=1, id="hello")
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[...omitted...]
File "<python-input-0>", line 6, in get_field
raise ValueError(
f"Invalid format string, {field_name!r} is not a valid identifier"
)
ValueError: Invalid format string, 'id.__class__' is not a valid identifier
>>>
Why use string.format instead of f strings?
In the example you provided, there's no reason not to use an f-string. Corey Schafer's videos are good, so I'm going to assume he just didn't cover f-strings yet. But sometimes, str.format can be useful. You can construct string templates and provide the arguments later, while f-strings are instantly evaluated. # Not the best use-case, but I wanted to focus on the idea example = "Hello, {}, how are you?" john = example.format('John') kevin = example.format('Kevin') More on reddit.com
String formatting, what's the best practice ?
3 is IMO the best but it's not supported on anything before Python 3.6. 2 is good but I personally prefer to put the numbers in the placeholders as it just makes it easier to track which of the parameters to format is slotting in each placeholder. More on reddit.com
The 4 Major Ways to Do String Formatting in Python (+ When to Use Them)
Four major ways, but according to OP only three of them should be used ... no love for % formatting, then?
More on reddit.comHard time understanding string formatting in Python
Might be worth noting that the % operator for string formatting is deprecated . If you want to learn the preferred way of doing things, look into the format method instead. Using % and .format() for great good! has a comparison of the 'old' (% style) and 'new' (format) approaches. The new method basically makes caring about %s vs %d irrelevant. What you said is essentially right though, %s just converts what you pass it to a str, as the docs say : 's' - String (converts any Python object using str()). If you try str(5) in IDLE, you'll notice you get the string '5' back. That essentially means you can use %s for anything that will convert with str(x). Using %d conveys your intentions more clearly, but %s will still technically work. Being clear with what your code is trying to do is always a good thing though. More on reddit.com
Videos
Real Python
realpython.com › python-string-formatting
Python String Formatting: Available Tools and Their Features – Real Python
December 2, 2024 - These tools include f-strings, the .format() method, and the modulo operator. String interpolation involves generating strings by inserting other strings or objects into specific places in a base string or template. For example, here’s how you can do some string interpolation using an f-string: ... In this quick example, you first have a Python variable containing a string object, "Bob".
Podalirius
podalirius.net › en › articles › python-format-string-vulnerabilities
Python format string vulnerabilities · Podalirius
March 24, 2021 - We will try to inject payloads int format string placeholders of the template. I made a simple script taking arguments and executing API’s render function : ... #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys config = { 'API_KEY' : "212817d980b9a03add91e5814d02" } class API(object): def __init__(self, apikey): self.apikey = apikey def renderHTML(self, templateHTML, title, text): return (templateHTML.format(self=self, title=title, text=text)) if __name__ == '__main__': if len(sys.argv) != 3: print("Usage : python3 "+sys.argv[0]+" TEMPLATE CONTENT") else : a = API(config['API_KEY']) print(a.renderHTML(sys.argv[1], "Vuln web render App", sys.argv[2]))
MITRE
cwe.mitre.org › data › definitions › 134.html
CWE - CWE-134: Use of Externally-Controlled Format String (4.20)
Common Weakness Enumeration (CWE) is a list of software weaknesses.
Appmarq
appmarq.com › public › tqi,8098,Avoid-uncontrolled-format-string-CWE-134
Avoid uncontrolled format string (CWE-134)
public class FormatterCase { FormatterCase() {} public void printStreamFormat(String val) throws SQLException { PrintStream ps = new PrintStream(new FileOutputStream(FileDescriptor.out)); // format a string ps.printf(val, "Hello");// VIOLATION // flush the stream ps.flush(); } } public class PrintWithReqFormat { FormatterCase formatter = FormatterCase(); PrintReq() {} public void execute(ServletRequest req) throws Exception { String format = req.getParameter("format"); formatter.printStreamFormat(format); } }
W3Schools
w3schools.com › python › ref_string_format.asp
Python String format() Method
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... The format() method formats the specified value(s) and insert them inside the string's placeholder.
Codearcana
codearcana.com › posts › 2013 › 05 › 02 › introduction-to-format-string-exploits.html
Introduction to format string exploits
May 2, 2013 - For every format string exploit, our payload will eventually look something like this: <address><address+2>%<number>x%<offset>$hn%<other number>x%<offset+1>$hn. We prepare a payload that will be the same length as our final payload so we can start computing the correct offsets and addresses (note that we use %hp and 000x so we can just modify the string in the last step without modifying its length): $ env -i ./a.out "$(python -c 'import sys; sys.stdout.write("sh;#AAAABBBB 000x$hp 000x$hp")')" sh;#AAAABBBB00xf7fcbff48048449(nil)
Grokipedia
grokipedia.com › uncontrolled format string
Uncontrolled format string — Grokipedia
January 14, 2026 - These methods scan for direct use of user input as format strings or track potentially tainted data propagating to format arguments, enabling early vulnerability identification during development.[23] Simple lexical analyzers, such as Flawfinder and ITS4, perform pattern-based scans to flag calls to format functions where the first argument appears to be non-literal or derived from untrusted sources. Flawfinder, a Python-based tool, examines C and C++ code for security weaknesses by assigning risk levels to potentially vulnerable patterns, including format string misuse, and outputs warnings prioritized by severity.
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Further details about these two formatting methods can be found in the official Python documentation: ... If you want to contribute more examples, feel free to create a pull-request on Github! ... Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate. Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.
Acunetix
acunetix.com › vulnerabilities › web › uncontrolled-format-string
Uncontrolled format string - Vulnerabilities - Acunetix
scut (TESO): Exploiting Format String Vulnerabilities · Rails mass assignment · Python object deserialization of user-supplied data · Deserialization of Untrusted Data (.NET BinaryFormatter Object Deserialization) webadmin.php script · Email Header Injection ·
iO Flood
ioflood.com › blog › python-format-string
Python Format String: Techniques and Examples
June 18, 2024 - For example, you can control the number of decimal places for a float, or add padding to a string. Here’s an example: pi = 3.14159 print(f'The value of pi to 2 decimal places is {pi:.2f}') # Output: # 'The value of pi to 2 decimal places is 3.14' In this case, the :.2f inside the placeholder is a formatting specifier. It tells Python to format the variable pi as a float with 2 decimal places.
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.6 documentation
Given field_name, convert it to an object to be formatted. Auto-numbering of field_name returned from parse() is done by vformat() before calling this method. Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101, such as “0[name]” or “label.title”. args and kwargs are as passed in to vformat().