Last active
August 29, 2015 14:04
-
-
Save mbarkhau/6867bf46b2ed6a70ca80 to your computer and use it in GitHub Desktop.
safe python eval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
compile_expr('"c"*10000000000') ?
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
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.