Why should exec() and eval() be avoided?

后端 未结 11 1992
Happy的楠姐
Happy的楠姐 2020-11-22 00:16

I\'ve seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case.

So, hopefully, one will be prese

相关标签:
11条回答
  • 2020-11-22 00:38

    Same reason you shouldn't login as root: it's too easy to shoot yourself in the foot.

    0 讨论(0)
  • 2020-11-22 00:48

    Try this in the interactive interpreter and see what happens:

    >>> import sys
    >>> eval('{"name" : %s}' % ("sys.exit(1)"))
    

    Of course, this is a corner case, but it can be tricky to prevent things like this.

    0 讨论(0)
  • 2020-11-22 00:52

    Reason #1: One security flaw (ie. programming errors... and we can't claim those can be avoided) and you've just given the user access to the shell of the server.

    0 讨论(0)
  • 2020-11-22 00:53

    In contrast to what most answers are saying here, exec is actually part of the recipe for building super-complete decorators in Python, as you can duplicate everything about the decorated function exactly, producing the same signature for the purposes of documentation and such. It's key to the functionality of the widely used decorator module (http://pypi.python.org/pypi/decorator/). Other cases where exec/eval are essential is when constructing any kind of "interpreted Python" type of application, such as a Python-parsed template language (like Mako or Jinja).

    So it's not like the presence of these functions are an immediate sign of an "insecure" application or library. Using them in the naive javascripty way to evaluate incoming JSON or something, yes that's very insecure. But as always, its all in the way you use it and these are very essential functions.

    0 讨论(0)
  • 2020-11-22 00:55
    s = "import shutil; shutil.rmtree('/nonexisting')"
    eval(s)
    

    Now assume somebody can control s from a web application, for example.

    Don't try to do this on your computer

    0 讨论(0)
  • 2020-11-22 00:56

    eval() and exec() can promote lazy programming. More importantly it indicates the code being executed may not have been written at design time therefore not tested. In other words, how do you test dynamically generated code? Especially across browsers.

    0 讨论(0)
提交回复
热议问题