0

Here is the situation: I am building application that can take a mathematical expression and evaluate it (works as a calculator). I do not have the os module imported, so I probably would not be able to execute rm -rf / or anything super malicious like that; but I want to be completely sure. I stumbled across the parser module in Python, and it has a parser function that claims to be much safer than eval. There is somewhere eval() shows up:

    expression = expression.split(";")

    expression_outputs = []

    for i in range(len(expression)):
        result = parser.expr(expression[i].strip()).compile()
        expression_outputs.append(complex(eval(result)))
    
    print("Answer(s): " + str(expression_outputs))

Is this code safe? If not, what would be some alternatives?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 2
    if `ast.literal_eval` would work for you, it would be more safe. https://docs.python.org/3/library/ast.html#ast.literal_eval – jkr Dec 02 '20 at 19:48
  • 3
    The os module is part of the standard library, so it is installed already. – snakecharmerb Dec 02 '20 at 19:48
  • It depends whether the user can type anything into `expression`. For example, I made a calculator that limits what the user can type, so in my case `eval` is relatively safe. – M-Chen-3 Dec 02 '20 at 19:48
  • 3
    You aren't providing the important detail, where does `expression` come from? If it is from untrusted input, then yes, this is an unsafe use of `eval`. I'm not sure what you mean "I do not have the os module installed", that is part of the standard library. – juanpa.arrivillaga Dec 02 '20 at 19:51
  • ```expression``` is what the user puts in. Also, I meant to say "imported" when I said "installed" (my bad). ```expression``` is heavily modified before being parsed (the main thing being done is the addition of math and cmath, so a user can type sin(0) instead of having to type cmath.sin(0)). – PythonProgrammer314 Dec 02 '20 at 19:56
  • 2
    Sanitizing input will make it safer, but it is never safe as eval will execute the input given to it. – Jakob L Dec 02 '20 at 20:11
  • Does this answer your question? [Python eval: is it still dangerous if I disable builtins and attribute access?](https://stackoverflow.com/questions/35804961/python-eval-is-it-still-dangerous-if-i-disable-builtins-and-attribute-access) – Tomerikoo Dec 02 '20 at 20:15
  • @PythonProgrammer314 please provide a *complete example*. Anyway, the fact that you aren't importing `os` is irrelevant. The code you are evaluating could import `os`. – juanpa.arrivillaga Dec 02 '20 at 20:20
  • @juanpa.arrivillaga ```expression``` is defined here if this answers your question: ```expression = input("Write an expression or set of expressions seperated by semicolons: ")``` – PythonProgrammer314 Dec 02 '20 at 20:26

0 Answers0