Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbarkhau/6867bf46b2ed6a70ca80 to your computer and use it in GitHub Desktop.
Save mbarkhau/6867bf46b2ed6a70ca80 to your computer and use it in GitHub Desktop.
safe python eval
try:
import builtins
except ImportError:
# PY2 compat
import __builtin__ as builtins
import re
import math
from functools import partial
# ctx setup
safe_math = [
'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp',
'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'
]
safe_builtins = [
'len', 'any', 'all', 'sum', 'max', 'min', 'int', 'float',
'hex', 'abs', 'bool'
]
SAFE_GLOBALS = {"__builtins__": None}
for attrname in safe_math:
SAFE_GLOBALS[attrname] = getattr(math, attrname)
for attrname in safe_builtins:
SAFE_GLOBALS[attrname] = getattr(builtins, attrname)
def compile_expr(expr):
# sanitize
expr = re.sub(r"\.[^\d]", "", expr) # remove scope resolution
expr = expr.replace("\\", "") # prevent escaping
return partial(eval, expr, SAFE_GLOBALS)
@mbarkhau
Copy link
Author

If you find a way to break out of this or use it for a dos attack, please let me know and add an example.

@bdauvergne
Copy link

compile_expr('"c"*10000000000') ?

@mbarkhau
Copy link
Author

Yeah stupid of me. I guess it's impossible to prevent memory/cpu ddos attacks using this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment