Sandboxing loadstring()

I’ve been reading in multiple places that loadstring(), a server side function, can be sandboxed. But how?

I do not intend to use LoadString in most places, would just be good knowledge

1 Like

Sandboxing the loadstring environment shouldn’t be done like that.
The function loadstring returns a function, which you can sandbox.

function sandboxObject(o)
  -- sandboxing logic goes here, return a proxy object

function sandboxFunction(f)
  -- unsandbox arguments, call function, sandbox returned values

local f = loadstring(...)
local env = getfenv(f) = sandboxObject(game)

You can sandbox loadstring quite easily actually.

local loadStringRef = loadstring("print('Example')")
setfenv(loadStringRef, new_env) -- new_env will be your sandbox's env
loadStringRef() -- Run the loadstring.

In my opinion you want a sandbox to limit things while giving full access though, such as if you wanted to limit _G you could instead allow them to use _G but provide them a “special” table instead of the actual _G. I can provide you an example sandbox I made in the past which does also sandbox loadstring if you’d like. Feel free to ask questions! :+1: