Python Forum
str.format security vulnerability
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
str.format security vulnerability
#1
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?
Reply
#2
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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Complete novice: Want to run a vulnerability script bhanney23 1 2,993 Sep-18-2020, 09:27 AM
Last Post: Aspire2Inspire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020