Sandboxing eval() (was: Calculator)
Paul Moore
p.f.moore at gmail.com
Sun Jan 19 12:53:46 EST 2020
On Sun, 19 Jan 2020 at 17:45, <musbur at posteo.org> wrote:
>
> Is it actually possible to build a "sandbox" around eval, permitting it
> only to do some arithmetic and use some math functions, but no
> filesystem acces or module imports?
No. This has been tried before, and it simply isn't safe in the face
of malicious input.
> I have an application that loads calculation recipes (a few lines of
> variable assignments and arithmetic) from a database.
>
> exec(string, globals, locals)
>
> with locals containing the input variables, and globals has a
> __builtin__ object with a few math functions. It works, but is it safe?
If you trust the source, it's OK, but a creative attacker who had the
ability to create a recipe could execute arbitrary code.
If you require safety, you really need to write your own parser/evaluator.
Paul
More information about the Python-list
mailing list