9

We know Python's eval() is evil

http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

and threads throughout StackOverflow suggest to use SymPy's evalf().

As a Python newbie, I can't really convince myself that evalf() is safe as I lack the skills. Can anyone elaborate on what evalf() does (different)?

Jk1
  • 11,233
  • 9
  • 54
  • 64
arney
  • 795
  • 7
  • 20
  • There are no suggestions to use `evalf` instead of `eval` as they have nothing in common. There are suggestions to use `sympify` instead of `eval`, but (from a security standpoint) they are misguided as these to are basically the same. – Krastanov May 24 '13 at 10:02

1 Answers1

9

There is nothing common between python eval and sympy evalf (the latter is for calculating the numeric value of sympy expression trees and it has nothing to do with parsing, while eval is all about parsing a string and evaluating it as if it is code).

On the other hand, sympify is just as dangerous as eval, because it actually uses eval.

There are two basic modes in which sympify is used and probably it is a bad idea that they got mixed in the same function:

  • sympify(some_object) would return a representation of the object more suited for use in a CAS, like transforming int(1) into sympy.Integer(1)

  • sympify("some_text") would parse the text almost directly through eval (search for the import from sympy.parsing present in sympify and follow it). It is safer as there are some constraints but it is not safe.

Krastanov
  • 6,479
  • 3
  • 29
  • 42
  • Thank you for your answer. Could you please elaborate on the second basic mode, `sympify("some text")`, and how this could be exploited maliciously? For example, does [Ned Batchelder's eval dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) example work in SymPy? EG calling `f = sympy.sympify('__import__("os")')` does not give me a callable object. – Mark Mikofski Aug 07 '13 at 04:41
  • 3
    OK, I was able to get access to `subprocess.Popen` using sympify and run a system command, EG `f = sympy.sympify("""[].__class__.__base__.__subclasses__()[158]('ls')""")` listed my directory contents. From there is just a simple step to `rm -rf \`. Well done [@Krastanov](http://stackoverflow.com/users/669329/krastanov) you have proven that sympy is **not** safe! Sympy is dangerous. – Mark Mikofski Aug 07 '13 at 06:58