Python Forum

Full Version: str.format security vulnerability
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was reading about str.format() and the security vulnerability that exists allowing an attacker access to sensitive information.

This code example is from the linked site:

>>> # This is our super secret key:
>>> SECRET = 'this-is-a-secret'

>>> class Error:
...      def __init__(self):
...          pass

>>> # A malicious user can craft a format string that
>>> # can read data from the global namespace:
>>> user_input = '{error.__init__.__globals__[SECRET]}'

>>> # This allows them to exfiltrate sensitive information,
>>> # like the secret key:
>>> err = Error()
>>> user_input.format(error=err)
'this-is-a-secret'
The recommendation was to use template strings when ever users have to supply values to the program.

Do f-strings have the same security vulnerability as str.format()? What code sample would you write to prove that it is or isn't vulnerable?
I think that the scope of the threat is very limited - the security vulnerability may occur if

Quote:you’re handling formatted strings generated by users of your program
see the source

It means that using formatting strings created by a developer is safe - and frankly, I do not see many systems providing an option for a user to provide his/her own formatting string.

I see this warning as related to some esoteric and rare scenarios - that most developers probably would never encounter.

Template Strings is a very old and cumbersome mechanism.

Theoretically, f-strings may possess the same level of threat - may be, even bigger, since you can include executable code in them - but again, in a very unlikely scenario.

In some cases old str.format provides better options than f-strings - e.g., when printing a dictionary or list content