I am creating a program, and I need to create a logic that handles user input for the eval() function.
The input will be a math function, I want to handle some irregularities and make sure the string is a math function and not malicious code.
For this I created a logic that compares all characters of the string with blacklist and whitelist, the problem is that the string can only contain a few characters in a specific arrangement, for example cos
, the string cannot contain c + o * s
.
whitelist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', ')',
'x', 'y', 'sin', 'cos', 'tg', '+', '-', '*', '/', ' ']
blacklist = ['a', 'b', 'd', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'p', 'q',
'r', 'u', 'v', 'w', 'z']
def stringTreat(string):
if not any(ch in string for ch in blacklist):
if all(ch in whitelist for ch in string):
print('OK!!')
else:
print('stop at whitelist')
else:
print('stop at blacklist')
string = input('input:')
stringTreat(string)
If I set 12 + 67 - 82
to the input of this example, the output is OK!!
, but if cos(x)
is the input, the output changes to stop at whitelist
.
How can I create a logic to accept substrings e.g. (sin, cos, tg), characters e.g. (0, 1, 2, 3...) and doesn't accept other substrings and characters e.g. (a, f, @, $, ls, mv)?