Loadstring() for one specific restricted use - any security risks?

This’ll work.

local function IsSafe(String)
    String = string.gsub(string.lower(String), "x", "")

    local Safe = true

    for Match in string.gmatch(String, "math%.(%w+)") do
        if not math[Match] then
            Safe = false
        end

        String = string.gsub(String, "math%." .. Match, "")
    end

    return Safe and string.find(String, "%a") == nil
end

print(IsSafe("math.sqrt(1 + 2) x 5"))
print(IsSafe("workspace:ClearAllChildren()"))

This doesn’t prevent making the server allocate huge amounts of memory by inputting huge tables. :troll:

Oh yeah I forgot about tables, since math library in this case never needs tables you can add a literal check to the function:

local CharacterLimit = 50

local function IsSafe(String)
    String = string.gsub(string.lower(String), "x", "")
    if #String > CharacterLimit then return false end

    local Safe = true

    for Match in string.gmatch(String, "math%.(%w+)") do
        if not math[Match] then
            Safe = false
        end

        String = string.gsub(String, "math%." .. Match, "")
    end

    return Safe and string.find(String, "[%a{}]") == nil
end

print(IsSafe("math.sqrt(1 + 2) x 5"))
print(IsSafe("{{{{}}}}}"))

Though just make sure to add a debounce and a character limit, since it’s still possible to spam math functions which could lag the server. I’ll edit the function to also have a character limit

Then I will make the code I want to load go through that function first. As for debouncing, the code I made that needs the loadstring() will be executed once every 0.1 seconds with a debounce.

You mean the cooldown for the client is 0.1 seconds? But yeah you first call that function, if it returns false you cancel and if it returns true you can put it in loadstring like this:

local Result = loadstring("return " .. MathString)()

The script is on the server and has no input from the client. The code is constantly going to calculate a string formula that is constantly changing, so it will calculate the string every 0.1 seconds.
Anyways, I will do it as you said. Thanks for the help.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.