0

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!

John
  • 303
  • 4
  • 13
  • 1
    Does this answer your question? [Python eval: is it still dangerous if I disable builtins and attribute access?](https://stackoverflow.com/questions/35804961/python-eval-is-it-still-dangerous-if-i-disable-builtins-and-attribute-access) – kahveciderin Aug 09 '21 at 12:05
  • As a general rule, filtering out only things you can think of ahead of time and know are dangerous is not an adequate way to secure a system that parses data as code. It's a pattern that gets followed frequently, and attackers successfully exploit it time and time again. No responsible security professional would put their reputation behind anything like this being "safe". – Charles Duffy Aug 09 '21 at 12:56

0 Answers0