Skip to content

Instantly share code, notes, and snippets.

@aliartiza75
Created February 19, 2018 09:40
Show Gist options
  • Save aliartiza75/770860880c3d6230e95cd52626b8f6a3 to your computer and use it in GitHub Desktop.
Save aliartiza75/770860880c3d6230e95cd52626b8f6a3 to your computer and use it in GitHub Desktop.
How to secure eval function
def evaluate_expression(expression):
"""
It evaluates whether a function is valid to be executed in or not
"""
invalid_params = ['*', ' *', '* ', ' * ', '/', ' /', '/ ', ' / ', '+', ' +', '+ ', ' + ', '-', ' -', '- ', ' - ', ' pow(', 'pow(', ' pow( ', 'pow(','rm ', ' rm ',
' rm', 'rm', ' exec(', 'exec(']
for item in invalid_params:
if item in expression:
return False
return True
if (evaluate_expression(expression)):
result = eval(expression, {"__builtins__":None})
Credits and further details can be found in the links below:
https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
http://www.diveintopython3.net/advanced-iterators.html#eval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment