Lua的setfenv/metatable沙箱无法与ROBLOX方法一起使用。

在 ROBLOX Lua 中,我正在编写一个涉及用户创建和运行 Lua 脚本的游戏。显然,我需要防止某些服务和函数的使用,比如在 Player 类上的 Kick 函数,或者和 DataStore 或 TeleportService 相关的任何内容。

到目前为止,我成功地通过使用 setfenv 将函数的环境设置为绑定在“沙盒”表中的元表来创建沙盒环境。在 __index 中,如果沙盒表中未找到任何内容,它将像通常一样查找真实环境。这使我能够将假函数放入沙盒表中,以便在其真实对应函数的位置使用它们。

但是,假设我将 ClearAllChildren 函数放入沙盒中。玩家可以轻易地通过执行以下操作来逃离沙盒:

someObject.Parent.someObject:ClearAllChildren()

这是因为获取实例的 Parent 会给他们真实版本而不是沙盒版本。这个漏洞还有许多其他方式可以被利用。

因此我创建了一个对象包装器。在实例上调用 wrap(obj) 会返回一个使用 newproxy(true) 创建的假版本。其元表的 __index 确保对象的任何子代(或实例属性,如 Parent)都将返回一个包装版本。

我的问题可能与对象包装器的设置方式有关。在沙盒中调用任何对象方法,比如这样:

x = someObject:GetChildren()

会导致以下错误:

Expected ':' not '.' calling member function GetChildren

这是我目前的沙盒的完整代码:

local _ENV = getfenv(); -- main environment

-- custom object wrapper
function wrap(obj)
    if pcall(function() return obj.IsA end) then -- hacky way to make sure it's real
        local realObj = obj;
        local fakeObj = newproxy(true);
        local meta = getmetatable(fakeObj);
        meta['__index'] = function(_, key)
            -- TODO: logic here to sandbox wrapped objects
            return wrap(realObj[key]) -- this is likely the source of method problem
        end;
        meta['__tostring'] = function()
            return realObj.Name or realObj;
        end;
        meta['__metatable'] = "Locked";
        return fakeObj;
    else
        return obj;
    end;
end;

-- sandbox table (fake objects/functions)
local sandbox = {
    game = wrap(game);
    Game = wrap(Game);
    workspace = wrap(workspace);
    Workspace = wrap(Workspace);
    script = wrap(script);
    Instance = {
        new = function(a, b)
            return wrap(Instance.new(a, b))
        end;
    };
};

-- sandboxed function
function run()
    print(script.Parent:GetChildren())
    print(script.Parent)
    script.Parent:ClearAllChildren()
end;

-- setting up the function environment
setfenv(run, setmetatable(sandbox, {__index = _ENV;}));

run();

我该如何解决这个问题?

点赞