Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "safe_eval" really safe?

I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).

The functionality to do this (the rexec module) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is this Python Cookbok recipe, "safe_eval".

Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?

EDIT: I just discovered RestrictedPython, which is part of Zope. Any opinions on this are welcome.

like image 201
dF. Avatar asked Aug 26 '08 15:08

dF.


People also ask

Is it safe to use eval in Python?

it depends what the source of the string is that you pass to eval. If your code has generated that string, and you know that it's contents don't call anything malicious then eval is safe.

What is Safe_eval in Odoo?

The first use, safe_eval is usually used to evaluate some string domains. For example in the pos_loyalty module in odoo 14 enterprise.


2 Answers

Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files:

>>> names['f'] = open('foo', 'w+')
>>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names)
>>> names['baz']
<open file 'baz', mode 'w+' at 0x413da0>

Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random.

On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast:

>>> import compiler
>>> ast = compiler.parse("print 'Hello world!'")

That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.

like image 164
Aaron Maenpaa Avatar answered Sep 22 '22 05:09

Aaron Maenpaa


Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel, etc) and not Python when they're entering formulas. I'm not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation.

like image 29
pix0r Avatar answered Sep 25 '22 05:09

pix0r