如何在python代码中利用locals()? [英] How can locals() be exploited in python code?

查看:85
本文介绍了如何在python代码中利用locals()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读类似于Pythonista的代码时,我偶然发现了以下警告:惯用的Python 大卫·古杰(David Goodger).

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.

但是电源可能很危险. 强大的力量带来了巨大的成功 责任."如果您使用 locals()来自 外部提供的模板字符串, 您公开了整个本地名称空间 给来电者.这只是东西 要牢记.

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()的存在的任何示例.谢谢!

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!

推荐答案

一个简单的示例:如果您在Webapp视图的本地命名空间中具有一些魔术超重要的加密密钥enc_key,则可以使用用户提供的字符串通过这种方式:

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

比攻击者可以将Encryption key is %(enc_key)s之类的内容传递为user_supplied_string并获得您的密钥.

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

我承认,这是一个极不可能且构造良好的例子.通常,只要您不使用用户提供的数据作为格式字符串,就可以使用locals()进行保存.

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.

这篇关于如何在python代码中利用locals()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆