lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Peter Cawley writes:
> The setfenv function in loadlib.c obtains the function calling
> 'module' and then sets the environment of said function. I see two
> potential problems here:
> 1) No check is made to ensure that there _is_ a calling function. Thus
> if module is called directly from C with no other functions on the
> stack, then the lua_Debug structure will be uninitialized, leading to
> a seg fault in most cases.
> 2) Base lib's 'setfenv' function makes sure that you do not set the
> environment of a C function, while 'module' does not. Thus if the
> calling function is a C one, then bad things could happen as the C
> function's environment is overwritten.

On point 2....The intention of Lua's standard libraries seems to be that setting
the environment of a C function from Lua should only be possible from the debug
library--e.g. debug.setfenv rather that setfenv:

  setfenv(string.gsub, {})        -- fails
  debug.setfenv(string.gsub, {})  -- ok

However, the current implementation of the module function allows the following:

  local env = {}
  assert(debug.getfenv(string.gsub) ~= env)
  package.loaded['_'] = env
  string.gsub('_', '_', module)
  assert(debug.getfenv(string.gsub) == env)  -- changed!

So, I think that should be fixed.

The module function is somewhat unsafe anyway for the purpose of sandboxing

Point 1 seems valid too, for top-level C code may run a script that replaces
some function that the top-level C code later calls directly with the module
function.  (The good practice of wrapping any C code in a pcall would avoid that