472,356 Members | 1,939 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,356 software developers and data experts.

Re: Simple and safe evaluator


Okay guys. I have the _ast based safe eval installed and working in my
program. It appears to be working just fine. Thanks for the help.

Now, a few more questions:

1. I see that _ast is a 2.5 module?? So, for folks using my code with
<2.5 I could do something like this:

# I've got some imports here to look after the error() and warning()
funcs ....

emsg_done = 0
etx = ""

def unsafe_eval(s):
""" safe eval for < python 2.5 (lacks _ast) """
global emsg_done
if not emsg_done:
warning("You are using an unsafe eval() function. Please
upgrade to Python version 2.5 or greater.")
emsg_done=1
# need error trap here as well ...
return eval(s, {"__builtins__":None}, {} )

def safe_eval(text):
"similar to eval, but only works on numerical values."
global etx
try:
ast = compile(text, "<string>", 'eval', _ast.PyCF_ONLY_AST)
except:
error("Expression error in '%s'" % text)
etx = text # for error reporting, bvdp
return _traverse(ast.body)
try:
import _ast
num_eval = safe_eval
except:
num_eval = unsafe_eval

# rest of matt's ast code follows.

Which appears to do the following: if there isn't an _ast module we just
define an alternate, not-so-safe, function and warn the user; otherwise
we use the safe version. I'm a bit uncomfortable with the import _ast
being after the function which uses the code, but it seems to work.

2. I thought I'd be happy with * / + -, etc. Of course now I want to add
a few more funcs like int() and sin(). How would I do that?

Thanks. This is looking very nice indeed.

Bob.
Jun 27 '08 #1
7 1560
On Jun 16, 4:47 pm, bvdp <b...@mellowood.cawrote:
2. I thought I'd be happy with * / + -, etc. Of course now I want to add
a few more funcs like int() and sin(). How would I do that?
For the builtin eval, just populate the globals dict with the names
you want to make available:

import math

globs = {'__builtins__' : None}

# expose selected builtins
for name in 'True False int float round abs divmod'.split():
globs[name] = eval(name)

# expose selected math constants and functions
for name in 'e pi sqrt exp log ceil floor sin cos tan'.split():
globs[name] = getattr(math,name)

return eval(s, globs, {})
The change to the _ast version is left as an exercise to the reader ;)

George
Jun 27 '08 #2
George Sakkis wrote:
On Jun 16, 4:47 pm, bvdp <b...@mellowood.cawrote:
>2. I thought I'd be happy with * / + -, etc. Of course now I want to add
a few more funcs like int() and sin(). How would I do that?

For the builtin eval, just populate the globals dict with the names
you want to make available:

import math

globs = {'__builtins__' : None}

# expose selected builtins
for name in 'True False int float round abs divmod'.split():
globs[name] = eval(name)

# expose selected math constants and functions
for name in 'e pi sqrt exp log ceil floor sin cos tan'.split():
globs[name] = getattr(math,name)

return eval(s, globs, {})
Thanks. That was easy :)
The change to the _ast version is left as an exercise to the reader ;)
And I have absolutely no idea on how to do this. I can't even find the
_ast import file on my system. I'm assuming that the _ast definitions
are buried in the C part of python, but that is just a silly guess.

Bob.
Jun 27 '08 #3
On Jun 17, 8:02 am, bvdp <b...@mellowood.cawrote:
Thanks. That was easy :)
The change to the _ast version is left as an exercise to the reader ;)

And I have absolutely no idea on how to do this. I can't even find the
_ast import file on my system. I'm assuming that the _ast definitions
are buried in the C part of python, but that is just a silly guess.

Bob.
If you just need numeric expressions with a small number of functions,
I would suggest checking the expression string first with a simple
regular expression, then using the standard eval() to evaluate the
result. This blocks the attacks mentioned above, and is simple to
implement. This will not work if you want to allow string values in
expressions though.

import re
def safe_eval( expr, safe_cmds=[] ):
toks = re.split( r'([a-zA-Z_\.]+|.)', expr )
bad = [t for t in toks if len(t)>1 and t not in safe_cmds]
if not bad:
return eval( expr )
>>safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)", 'int float sum abs'.split() )
351.9000000023085
>>safe_eval( "abs(5*-77+33.1) + (int(405.3) * 5.7e-12)" )
safe_eval( "open('thesis.tex').write('')" )
Mike.
Jun 27 '08 #4
sw******@acm.org wrote:
On Jun 17, 8:02 am, bvdp <b...@mellowood.cawrote:
>Thanks. That was easy :)
>>The change to the _ast version is left as an exercise to the reader ;)
And I have absolutely no idea on how to do this. I can't even find the
_ast import file on my system. I'm assuming that the _ast definitions
are buried in the C part of python, but that is just a silly guess.

Bob.

If you just need numeric expressions with a small number of functions,
I would suggest checking the expression string first with a simple
regular expression, then using the standard eval() to evaluate the
result. This blocks the attacks mentioned above, and is simple to
implement. This will not work if you want to allow string values in
expressions though.

import re
def safe_eval( expr, safe_cmds=[] ):
toks = re.split( r'([a-zA-Z_\.]+|.)', expr )
bad = [t for t in toks if len(t)>1 and t not in safe_cmds]
if not bad:
return eval( expr )
Yes, this appears to be about as good (better?) an idea as any.
Certainly beats writing my own recursive decent parser for this :)

And it is not dependent on python versions. Cool.

I've run a few tests with your code and it appears to work just fine.
Just a matter of populating the save_cmds[] array and putting in some
error traps. Piece of cake. And should be fast as well.

Thanks!!!

Bob.
Jun 27 '08 #5
On Jun 16, 8:32*pm, bvdp <b...@mellowood.cawrote:
sween...@acm.org wrote:
On Jun 17, 8:02 am, bvdp <b...@mellowood.cawrote:
Thanks. That was easy :)
>The change to the _ast version is left as an exercise to the reader ;)
And I have absolutely no idea on how to do this. I can't even find the
_ast import file on my system. I'm assuming that the _ast definitions
are buried in the C part of python, but that is just a silly guess.
Bob.
If you just need numeric expressions with a small number of functions,
I would suggest checking the expression string first with a simple
regular expression, then using the standard eval() to evaluate the
result. *This blocks the attacks mentioned above, and is simple to
implement. *This will not work if you want to allow string values in
expressions though.
import re
def safe_eval( expr, safe_cmds=[] ):
* *toks = re.split( r'([a-zA-Z_\.]+|.)', expr )
* *bad = [t for t in toks if len(t)>1 and t not in safe_cmds]
* *if not bad:
* * * * * *return eval( expr )

Yes, this appears to be about as good (better?) an idea as any.
Certainly beats writing my own recursive decent parser for this :)

And it is not dependent on python versions. Cool.

I've run a few tests with your code and it appears to work just fine.
Just a matter of populating the save_cmds[] array and putting in some
error traps. Piece of cake. And should be fast as well.

Thanks!!!

Bob.
FWIW, I got around to implementing a function that checks if a string
is safe to evaluate (that it consists only of numbers, operators, and
"(" and ")"). Here it is. :)

import cStringIO, tokenize
def evalSafe(source):
'''
Return True if a source string is composed only of numbers,
operators
or parentheses, otherwise return False.
'''
try:
src = cStringIO.StringIO(source).readline
src = tokenize.generate_tokens(src)
src = (token for token in src if token[0] is not tokenize.NL)

for token in src:
ttype, tstr = token[:2]

if (
tstr in "()" or
ttype in (tokenize.NUMBER, tokenize.OP)
and not tstr == ',' # comma is an OP.
):
continue
raise SyntaxError("unsafe token: %r" % tstr)

except (tokenize.TokenError, SyntaxError):
return False

return True

for s in (

'(1 2)', # Works, but isn't math..

'1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 ))', # Works

'1001 * 99 / (73.8 ^ 88 % (88 + 23e-10 )',
# Raises TokenError due to missing close parenthesis.

'(1, 2)', # Raises SyntaxError due to comma.

'a * 21', # Raises SyntaxError due to identifier.

'import sys', # Raises SyntaxError.

):
print evalSafe(s), '<--', repr(s)

Jun 27 '08 #6
In article <f4**********************************@u12g2000prd. googlegroups.com>,
Simon Forman <sa*******@gmail.comwrote:
>
FWIW, I got around to implementing a function that checks if a string
is safe to evaluate (that it consists only of numbers, operators, and
"(" and ")"). Here it is. :)
What's safe about "10000000 ** 10000000"?
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jun 27 '08 #7
Aahz wrote:
In article <f4**********************************@u12g2000prd. googlegroups.com>,
Simon Forman <sa*******@gmail.comwrote:
>FWIW, I got around to implementing a function that checks if a string
is safe to evaluate (that it consists only of numbers, operators, and
"(" and ")"). Here it is. :)

What's safe about "10000000 ** 10000000"?
Guess it depends on your definition of safe. I think that in most cases
folks looking for "safe" are concerned about a malicious interjection of
a command like "rm *" ... your example hangs the system for a long time
and eventually will error out when it runs out of memory, but (probably)
doesn't cause data corruption.

It would be nice if in a future version of Python we could have a
safe/limited eval() ... which would limit the resources.
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: bvdp | last post by:
Is there a simple/safe expression evaluator I can use in a python program. I just want to pass along a string in the form "1 + 44 / 3" or perhaps "1 + (-4.3*5)" and get a numeric result. I can...
7
by: bvdp | last post by:
I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file)...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
1
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. header("Location:".$urlback); Is this the right layout the...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.