Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created November 13, 2012 00:22
Show Gist options
  • Save gabrielfalcao/4063003 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/4063003 to your computer and use it in GitHub Desktop.
import ast
def get_safe_function(code):
expression = ast.parse(code).body[0]
if expression.value.__class__.__name__ == 'Lambda':
return eval(code)
else:
logger.warning("Got an unsafe code: %s", repr(code))
return lambda x: x
exec1 = get_safe function('lambda x: x.strip()')
exec2 = get_safe function('__import__("os").system("rm -rf /")')
assert exec1(" aaa ") == "aaa"
assert exec2(" aaa ") == " aaa "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment