Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can locals() be exploited in python code?

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!

like image 421
Praveen Gollakota Avatar asked Apr 07 '11 18:04

Praveen Gollakota


People also ask

What does locals () do in Python?

Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.

How do I use globals and locals in Python?

The globals(), locals() and reload() Functions in PythonIf locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function.

What do you mean by global () and locals () functions?

Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function. It is possible to have local variables with the same name in different functions.

What does local mean in Python?

In Python or any other programming languages, the definition of local variables remains the same, which is “A variable declared inside the function is called local function”. We can access a local variable inside but not outside the function.


1 Answers

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

like image 200
yan Avatar answered Sep 17 '22 17:09

yan