75

So Lua seems ideal for implementing secure "user scripts" inside my application.

However, most examples of embedding lua seem to include loading all the standard libraries, including "io" and "package".

So I can exclude those libs from my interpreter, but even the base library includes the functions "dofile" and "loadfile" which access the filesystem.

How can I remove/block any unsafe functions like these, without just ending up with an interpreter that doesn't even have basic stuff like the "ipairs" function?

4

7 に答える 7

53

setfenv ()を介して、信頼できないコードを実行する関数環境を設定できます。概要は次のとおりです。

local env = {ipairs}
setfenv(user_script, env)
pcall(user_script)

関数は、そのuser_script環境にあるものにのみアクセスできます。そのため、信頼できないコードにアクセスさせたい関数を明示的に追加できます (ホワイトリスト)。この場合、ユーザー スクリプトにはアクセス権しかありipairsません ( dofileloadfileなど)。

Lua サンドボックスの例と詳細については、 Lua サンドボックスを参照してください。

于 2009-08-03T21:37:00.960 に答える
35

Lua 5.2のソリューションは次のとおりです(5.1でも機能するサンプル環境を含む)。

-- save a pointer to globals that would be unreachable in sandbox
local e=_ENV

-- sample sandbox environment
sandbox_env = {
  ipairs = ipairs,
  next = next,
  pairs = pairs,
  pcall = pcall,
  tonumber = tonumber,
  tostring = tostring,
  type = type,
  unpack = unpack,
  coroutine = { create = coroutine.create, resume = coroutine.resume, 
      running = coroutine.running, status = coroutine.status, 
      wrap = coroutine.wrap },
  string = { byte = string.byte, char = string.char, find = string.find, 
      format = string.format, gmatch = string.gmatch, gsub = string.gsub, 
      len = string.len, lower = string.lower, match = string.match, 
      rep = string.rep, reverse = string.reverse, sub = string.sub, 
      upper = string.upper },
  table = { insert = table.insert, maxn = table.maxn, remove = table.remove, 
      sort = table.sort },
  math = { abs = math.abs, acos = math.acos, asin = math.asin, 
      atan = math.atan, atan2 = math.atan2, ceil = math.ceil, cos = math.cos, 
      cosh = math.cosh, deg = math.deg, exp = math.exp, floor = math.floor, 
      fmod = math.fmod, frexp = math.frexp, huge = math.huge, 
      ldexp = math.ldexp, log = math.log, log10 = math.log10, max = math.max, 
      min = math.min, modf = math.modf, pi = math.pi, pow = math.pow, 
      rad = math.rad, random = math.random, sin = math.sin, sinh = math.sinh, 
      sqrt = math.sqrt, tan = math.tan, tanh = math.tanh },
  os = { clock = os.clock, difftime = os.difftime, time = os.time },
}

function run_sandbox(sb_env, sb_func, ...)
  local sb_orig_env=_ENV
  if (not sb_func) then return nil end
  _ENV=sb_env
  local sb_ret={e.pcall(sb_func, ...)}
  _ENV=sb_orig_env
  return e.table.unpack(sb_ret)
end

my_func次に、それを使用するには、次のように関数()を呼び出します。

pcall_rc, result_or_err_msg = run_sandbox(sandbox_env, my_func, arg1, arg2)
于 2011-08-08T12:25:49.183 に答える
14

Lua ライブ デモには、(専用の) サンドボックスが含まれています。ソースは自由に入手できます。

于 2009-08-04T01:31:09.273 に答える
5

望ましくないものを取り除く最も簡単な方法の1つは、最初に独自の工夫をしたLuaスクリプトをロードすることです。これは、次のようなことを行います。

load = nil
loadfile = nil
dofile = nil

または、setfenv特定の安全な機能を挿入できる制限された環境を作成するために使用できます。

完全に安全なサンドボックス化は少し難しいです。どこからでもコードをロードする場合は、プリコンパイルされたコードがLuaをクラッシュさせる可能性があることに注意してください。完全に制限されたコードでも、シャットダウンするシステムがない場合は、無限ループに入り、無期限にブロックされる可能性があります。

于 2009-08-04T00:22:17.597 に答える
3

Lua API が提供する関数を使用しlua_setglobalて、グローバル名前空間にこれらの値を設定し、nilユーザー スクリプトがそれらにアクセスできないようにすることができます。

lua_pushnil(state_pointer);
lua_setglobal(state_pointer, "io");

lua_pushnil(state_pointer);
lua_setglobal(state_pointer, "loadfile");

...etc...
于 2009-08-03T21:33:39.500 に答える
1

Lua 5.1 を使用している場合は、これを試してください。

blockedThings = {'os', 'debug', 'loadstring', 'loadfile', 'setfenv', 'getfenv'}
scriptName = "user_script.lua"

function InList(list, val) 
    for i=1, #list do if list[i] == val then 
        return true 
    end 
end

local f, msg = loadfile(scriptName)

local env = {}
local envMT = {}
local blockedStorageOverride = {}
envMT.__index = function(tab, key)
    if InList(blockedThings, key) then return blockedStorageOverride[key] end
    return rawget(tab, key) or getfenv(0)[key]
end
envMT.__newindex = function(tab, key, val)
    if InList(blockedThings, key) then
        blockedStorageOverride[key] = val
    else
        rawset(tab, key, val)
    end
end

if not f then
    print("ERROR: " .. msg)
else
    setfenv(f, env)
    local a, b = pcall(f)
    if not a then print("ERROR: " .. b) end
end
于 2013-10-07T03:09:59.707 に答える
-2

必要な Lua 関数をオーバーライド (無効化) することができ、メタテーブルを使用してさらに制御することもできます。

于 2009-08-03T21:34:31.010 に答える