Python Forum

Full Version: make eval() safe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is there a way to easily make eval() safe to use with a string from an untrusted source?
You might find this interesting.

https://wiki.python.org/moin/SandboxedPython

The problem, as I see it, is disallowing import. If you can control import you can evaluate Python expressions in a carefully controlled context that eliminates access to all the dangerous parts.
I think you have asked a similar question before and Simple Eval is still the best choice.
So he has done the work bye writing a parser with ast to parse expressions.
This is the way to go to make a safer eval(),it's a lot of work.
He have done nice job as can add own class/function if needed.
So it i test bye writing a own function,it can work like this.
from simpleeval import simple_eval
from math import sqrt

def new_sqrt(arg: int) -> float:
     return sqrt(arg) + 10

if __name__ == '__main__':
    power_sqrt = simple_eval("power_sqrt(5) ** 2", functions={"power_sqrt":new_sqrt})
    print(power_sqrt)
Output:
149.7213595499958
So if most use something like this,then this is one a good choice and not trying simple fix(safe) with eval() yourself.

danthedeckie Wrote:I've done the best I can with this library - but there's no warranty, no guarantee, nada.
A lot of very clever people think the whole idea of trying to sandbox CPython is impossible.
Read the code yourself, and use it at your own risk.
i want to protect more than just the system. for example, a web server in Python running some untrusted code with a call to "exit()". preventing this was my first thought.
(Mar-22-2022, 05:29 PM)Skaperen Wrote: [ -> ]i want to protect more than just the system. for example, a web server in Python running some untrusted code with a call to "exit()". preventing this was my first thought.
danthedeckie Wrote:Or if you want to allow simple formulae in a web application, but don't want to give full eval() access,
or don't want to run in javascript on the client side
That's one usage case.

Maybe your doing stuff you should not do in first placešŸ’„
Don't know if you have looked into Template engine as eg Jinja .
Has safe way to render code on server and also call stuff tough macros.
jinja Wrote:
  • Template inheritance and inclusion.
  • Define and import macros within templates.
  • HTML templates can use autoescaping to prevent XSS from untrusted user input.
  • A sandboxed environment can safely render untrusted templates.
    .....
(Mar-22-2022, 07:15 PM)snippsat Wrote: [ -> ]Has safe way to render code on server and also call stuff tough macros
user provided arithmetic expressions are to be provided by a web user. the web engine will do a lot of calculation with it while changing x and y and producing a plot. failures are to be commonly expected. speed helps.