使用eval进行表达评估的安全性如何? [英] How safe is expression evaluation using eval?

查看:122
本文介绍了使用eval进行表达评估的安全性如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站,我需要用户应该能够根据数据库表中的值评估某些表达式,而不是使用pyparsing等工具,而是考虑使用python本身,并且一个足以满足我目的的解决方案。我基本上是使用eval来评估表达式,并使用空的 __ builtins __ 传递全局变量,以便如果用户需要某些功能,则无法访问任何内容,并且可以从DB获取值的局部变量dict我也可以传递这些信息,例如

I am building a website where I have a need that user should be able to evaluate some expression based from the value in DB tables, instead of using tools like pyparsing etc, I am thinking of using python itself, and have come up with a solution which is sufficient for my purpose. I am basically using eval to evaluate the expression and passing globals dict with empty __builtins__ so that nothing can be accessed and a locals dict for values from DB, if user will need some functions I can pass those too e.g.

import datetime
def today():
    return datetime.datetime.now()

expression = """ first_name.lower() == "anurag" and today().year == 2010 """

print eval(expression, {'__builtins__':{}}, {'first_name':'Anurag', 'today':today})

所以我的问题是它将有多安全,我有三个条件

So my question is how safe it would be , I have three criteria


  1. 用户可以访问我程序的当前状态还是表等someshow?

  2. 用户可以访问操作系统级别的呼叫吗?

  3. 用户可以通过循环或使用大量内存来暂停我的系统吗?通过设置range(10 * 8),在某些情况下他可以例如100 ** 1000等,因此3并不是什么大问题。我可能会用tokenize检查此类操作,无论如何我都将使用GAE,所以它并不是很多问题。

编辑:IMO并非 Q:661084 因为这是从哪里开始的,所以我想知道即使在 __ builtins __ 被阻止的情况下,用户也可以做坏事吗?

Edit: IMO this is not the duplicate of Q:661084 because where it ends this one starts, I want to know even with __builtins__ blocked, can user do bad things?

推荐答案

使用 eval 是完全不安全的,即使清空并阻止了内置程序,攻击者也可以使用文字,得到其 __ class __ 等,依此类推,直到 object ,其 __ subclasses __ ,依此类推...基本上,Python内省功能太强大了,无法抵御熟练的,坚定的攻击者。

It's completely unsafe to use eval, even with built-ins emptied and blocked -- the attacker can start with a literal, get its __class__, etc, etc, up to object, its __subclasses__, and so forth... basically, Python introspection is just too strong to stand up to a skilled, determined attacker.

ast.literal_eval <如果是,则strong>是安全的 ou可以忍受其局限性...

ast.literal_eval is safe, if you can live by its limitations...

这篇关于使用eval进行表达评估的安全性如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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