Via this page: http://lua-users.org/wiki/SandBoxes require is marked as unsafe and it's because:
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With