I need to take input from the user of a simple bit of math, they want to solve. Rather than parse there input myself, I want to just use the lua, loadstring function to load their input and evaluate it.
But I don't want to let them execute abaritary code, So I am passing the string though a whitelist to make sure they are only using mathematical characters.
function calc(inputEquationStr)
local startValid, endValid = string.find(inputEquationStr,"[%(%)%.%^%*%+%-/%d]+")
if startValid>1 or endValid<string.len(inputEquationStr) then
print("Error: Input doesn't look like math.")
else
local funcStr = "return " .. inputEquation
local mathFunction = loadstring(funcStr)
assert(mathFunction, "Syntax Error, in input")
print(mathFunction())
end
end
function calcOuter(inputStr)
local success, err = pcall(calc, inputStr)
if not success then
print("Error : " .. tostring(err))
end
end
So the important part as i see it is that I whitelist to only allow +,-,.,*,/,^, () and digits.
Which is done with string.find(inputEquationStr,"[%(%)%.%^%*%+%-/%d]+"
Is this going to be enough to protect against injection? Is there some kind of way, like hex-encoded strings that I need to watch out for?