Python代码中如何利用locals()函数?

8

我在阅读David Goodger的像Pythonista一样编写代码:Python惯用法时,偶然发现了以下警告。

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.

我正试图理解使用locals()可能存在潜在风险的具体场景。欢迎提供locals()存在的情况下可能被利用的任何示例。谢谢!
2个回答

6

示例,简单的代码:

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()

考虑输入密码为%(real_pw)s的情况。

4
一个简单的例子:如果你在webapp-view的本地命名空间中有一些魔法级别的超重要加密密钥enc_key,并且你想以以下方式使用用户提供的字符串:
 a_var_that_gets_display = user_supplied_string % locals()

攻击者可能会将Encryption key is %(enc_key)s这样的内容作为user_supplied_string传递,从而获取你的密钥。

我承认这只是一个高度不太可能的构造示例。通常情况下,只要不使用用户提供的数据作为格式字符串,使用locals()是安全的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接