Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Basic sandboxing code?

Asked by
LuaQuest 450 Moderation Voter
8 years ago

What i do know

So i know what a sandbox is. I know what it's used for, and how it can be useful in the right situation. I also know about a lot about function environments, tables, and metatables. Just a small overview on stuff i know to spare any explanation on.

The question

How can i make my sandbox attempt more secure? More specifically, how can i prevent it from being bypassed with the following code:


setfenv(1,setmetatable({},{ __index = function(t,k) if k == "workspace" then return nil else return getfenv()[k] end end })) print(workspace) -- > nil setfenv(1,getfenv(print)) -- bypassed, because i can set a new environment with the original one from print. print(workspace) -- > nil

The problem

So, i know what the problem is, but have no idea how to fix it. I could say any of the following to bypass this little sandbox:

setfenv(1,getfenv(print))
setfenv(1,getfenv(unpack))
setfenv(1,getfenv(script))

-- Or any other built-in global that the __index metamethod returns.

So, if anyone happens to have some insight on sandboxing, or even environments and metatables, i'd really appreciate some help. Thanks for reading.

0
Define sandbox because I never heard that in any programming language ever .-. User#5978 25 — 8y
0
A sandbox is a virtual space (a program) where code can be ran under certain instruction (i.e, disabling access to potentially harmful information). For example, one person may remove another person from a game with unsandboxed code, but with sandboxed code that would prevent that from happening. LuaQuest 450 — 8y

1 answer

Log in to vote
2
Answered by
Unclear 1776 Moderation Voter
8 years ago

Usually when you construct a sandbox, you don't define a blacklist. There are too many possibly out there that you aren't quite sure about. You define whitelist instead.

This is generally the strategy when it comes to sandboxing...

  1. Enumerating all whitelisted global variables.
  2. Putting the whitelisted global variables in a dictionary.
  3. Associating a global metatable with the dictionary
  4. Overwriting the global environment with your dictionary

For example, this would be a sandboxed environment that only allows references to print...

local newEnvironment = {
    print = print
}
local metatable = {
    __metatable = "locked" -- Lock the global metatable
}
setmetatable(newEnvironment, metatable)
setfenv(1, newEnvironment)
print(1) --> 1
setfenv(1, { }) --> attempt to call global 'setfenv' (a nil value)
Ad

Answer this question