8

I stumbled across the following warning when I was reading Code Like a Pythonista: Idiomatic Python by David Goodger.

Excerpt from the article ...

print('Hello %(name)s, you have %(messages)i messages' % locals())

This is very powerful. With this, you can do all the string formatting you want without having to worry about matching the interpolation values to the template.

But power can be dangerous. "With great power comes great responsibility." If you use the locals() from with an externally-supplied template string, you expose your entire local namespace to the caller. This is just something to keep in mind.

I am trying to understand the specific scenarios in which using locals() can be dangerous. Any examples of how the presence of locals() in a code can be exploited are appreciated. Thanks!

2 Answers 2

6

Sample, trivial code:

script_name = 'readpw.py'
...
entered_pw = raw_input()
if entered_pw != real_pw:
    print "%(script_name)s: The password you entered: "+entered_pw+" is incorrect."%locals()

Consider the case where entered_pw is %(real_pw)s

Sign up to request clarification or add additional context in comments.

Comments

4

A simple example: If you have some magic ultra important encryption key enc_key in your local namespace of a webapp-view and you would use a user supplied string in this way:

 a_var_that_gets_display = user_supplied_string % locals()

Than an attacker could pass something like Encryption key is %(enc_key)s as user_supplied_stringand would get your key.

I admit that this a highly unlikely and constructed example. Generally using locals() is save as long as you don't use user supplied data as format string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.