Is there a way to secure strings for Python's eval?

后端 未结 7 2062
悲哀的现实
悲哀的现实 2021-02-08 07:43

There are many questions on SO about using Python\'s eval on insecure strings (eg.: Security of Python\'s eval() on untrusted strings?, Python: make eval safe).

7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 08:16

    No, there isn't, or at least, not a sensible, truly secure way. Python is a highly dynamic language, and the flipside of that is that it's very easy to subvert any attempt to lock the language down.

    You either need to write your own parser for the subset you want, or use something existing, like ast.literal_eval(), for particular cases as you come across them. Use a tool designed for the job at hand, rather than trying to force an existing one to do the job you want, badly.

    Edit:

    An example of two strings, that, while fitting your description, if eval()ed in order, would execute arbitrary code (this particular example running evil.__method__().

    "from binascii import *"
    "eval(unhexlify('6576696c2e5f5f6d6574686f645f5f2829'))"
    

提交回复
热议问题