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

到目前为止,我已经成功地通过使用setfenv将函数的环境设置为metatable来创建沙盒环境,metatable附加到“沙箱”表 . 在__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();

我怎样才能解决这个问题?