Debian Codegraph @

modules/module-lua-scripting/wplua/sandbox.lua

raw
1 -- WirePlumber
2 --
3 -- Copyright © 2020 Collabora Ltd.
4 -- @author George Kiagiadakis <[email protected]>
5 --
6 -- Based on https://github.com/kikito/sandbox.lua
7 -- Copyright © 2013 Enrique García Cota
8 --
9 -- SPDX-License-Identifier: MIT
10
11 local SANDBOX_CONFIG = ...
12 local SANDBOX_ENV = {}
13
14 function create_sandbox_env()
15 local function populate_env(id)
16 local module, method = id:match('([^%.]+)%.([^%.]+)')
17 if module then
18 SANDBOX_ENV[module] = SANDBOX_ENV[module] or {}
19 SANDBOX_ENV[module][method] = _G[module][method]
20 else
21 SANDBOX_ENV[id] = _G[id]
22 end
23 end
24
25 if not SANDBOX_ENV._VERSION then
26 -- List of exported functions and packages
27 ([[ _VERSION assert error ipairs next pairs tonumber
28 pcall select print tostring type xpcall require
29 table string math package utf8 debug coroutine
30 os.clock os.difftime os.time os.date os.getenv
31 setmetatable getmetatable
32 ]]):gsub('%S+', populate_env)
33
34 -- Additionally export everything in SANDBOX_EXPORT
35 if type(SANDBOX_EXPORT) == "table" then
36 for k, v in pairs(SANDBOX_EXPORT) do
37 SANDBOX_ENV[k] = v
38 end
39 end
40
41 -- Additionally protect packages from malicious scripts trying to override methods
42 for k, v in pairs(SANDBOX_ENV) do
43 if type(v) == "table" then
44 SANDBOX_ENV[k] = setmetatable({}, {
45 __index = v,
46 __call = function(t, ...)
47 return t["__new"](...)
48 end,
49 __newindex = function(_, attr_name, _)
50 error('Can not modify ' .. k .. '.' .. attr_name .. '. Protected by the sandbox.')
51 end
52 })
53 end
54 end
55 end
56
57 -- chunk's environment will be an empty table with __index
58 -- to access our SANDBOX_ENV (without being able to write it)
59 return setmetatable({}, {
60 __index = SANDBOX_ENV,
61 })
62 end
63
64 if SANDBOX_CONFIG["isolate_env"] then
65 -- in isolate_env mode, use a separate environment for each loaded chunk and
66 -- store all of them in a global table so that they are not garbage collected
67 SANDBOX_ENV_LIST = {}
68
69 function sandbox(chunk, ...)
70 local env = create_sandbox_env()
71 -- store the chunk's environment so that it is not garbage collected
72 table.insert(SANDBOX_ENV_LIST, env)
73 -- set it as the chunk's 1st upvalue (__ENV)
74 debug.setupvalue(chunk, 1, env)
75 -- execute the chunk
76 return chunk(...)
77 end
78 else
79 -- in common_env mode, use the same environment for all loaded chunks
80 -- chunk's environment will be an empty table with __index
81 -- to access our SANDBOX_ENV (without being able to write it)
82 SANDBOX_COMMON_ENV = create_sandbox_env()
83
84 function sandbox(chunk, ...)
85 -- set it as the chunk's 1st upvalue (__ENV)
86 debug.setupvalue(chunk, 1, SANDBOX_COMMON_ENV)
87 -- execute the chunk
88 return chunk(...)
89 end
90 end