Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua why is 'require' unsafe to use in a sandbox environment?

Tags:

lua

Via this page: http://lua-users.org/wiki/SandBoxes require is marked as unsafe and it's because:

  • modifies globals (e.g. package.loaded)
  • provides access to environments outside the sandbox
  • and accesses the file system

Pretty much all pure Lua libraries use 'require' so not having this be safe is a huge pain because you can't use any pure Lua libraries. I don't understand these unsafe reasons. It loads other Lua files in a library. Why is that unsafe?

like image 809
user441521 Avatar asked Feb 06 '23 12:02

user441521


2 Answers

Require loads and executes code in the global environment.

For example, lets create a simple sandbox (Lua >= 5.2):

-- example.lua
my_global = 42

local sandbox
do
  local _ENV = { require = require, print = print }

  function sandbox()
    print('<sandbox> my_global =', my_global)
    require 'example_module'
  end
end

print('<global> my_global =', my_global)
sandbox()
print('<global> my_global =', my_global)

Now, lets create a module that changes my_global:

-- example_module.lua
print('<module> my_global =', my_global)
my_global = nil

The expectation is that inside the sandbox the only functions available are require and print. Code inside the sandbox should not be able to access the global my_global.

Run the example and you will see:

$ lua example.lua
<global> my_global =    42      -- The global environment, Ok.
<sandbox> my_global =   nil     -- Inside the sandbox, Ok.
<module> my_global =    42      -- Inside the sandbox, but loaded with require. Whoops, we have access to the global environment.
<global> my_global =    nil     -- The module changed the value and it is reflected in the global environment.

The module has broken out of the sandbox.

like image 61
Adam Avatar answered Feb 09 '23 01:02

Adam


Since it has access to the file system and the global environment, it can execute code and modify values it's not supposed to modify.

You can implement and make available your own require method that satisfies your sandbox requirements. For example, you can preload those libraries you verified and have "require" only return preloaded results.

like image 31
Paul Kulchenko Avatar answered Feb 09 '23 00:02

Paul Kulchenko