I have a code where I want the user to input a mathematical function in order to costumize the process. For exemple :
import numpy as np
x = linspace(0, np.pi)
y = eval(input('y(x)='))
# some treatment with the customized y(x)...
But obviously, eval() is very dangerous since someone could remove all files from my computer by typing eval("__import__('os').system('clear')", {})
(which is not what I want from my programm :D)
So I searched on Google and came up with that routine :
import numpy as np
x = np.linspace(0, 2*np.pi)
y = None
user_input = str(input('y(x)='))
# Anti dangerous function filter
forbidden_strings = ['import', '\n', '.py', '.exe', '.npz', '.npy', 'load', 'exec', 'compile', ';']
for forbidden_string in forbidden_strings:
if forbidden_string in user_input:
raise ValueError("FORBIDDEN COMMAND IN INPUT !")
# set the list of allowed numpy functions the user can call
allowed_functions = 'mean, max, min, sum, pi, cos, sin, tan, arccos, arcsin, arctan, log, exp, sqrt, power, gradient'
code = "from numpy import " + allowed_functions +"\ny=" + user_input
# The code will looks like :
# from numpy import all allowed functions
# y= user input
exec(compile(code, filename="", mode="exec"))
Would you say this is safe ? Is there a way to strengthen it even more ? Thanks in advance for your help!