lua-users home
lua-l archive

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


It was thus said that the Great Nagaev Boris once stated:
> 
> Even some built-in string methods are considered dangerous, at least
> string.dump [1]. Not to mention methods added to string by 3d party
> libraries.

  Any problems with this?

local old_print = print
function print(...)
  old_print(...)
end

DANGEROUS = [[
        x = string.dump(print)
        
        if x then
          print "Ha ha ha!  I have the power!"
        end
        
        x = "foobar"
        dump = x.dump
        
        x = dump(print)
        
        if x then
          print "Ha ha!  I still have the power"
        end
        
	os.exit(0) -- or some other nefarious code
]]

local new_string =
{
  reverse = string.reverse, -- keep some functions
  gsub    = string.gsub,    -- salt to taste
  lower   = string.lower,
  upper   = string.upper,
  format  = string.format,
}

local old_string_mt = debug.getmetatable("")
debug.setmetatable("",{ __index = new_string })

safe,err = load(DANGEROUS,"WARNING","t",{ print = print , string = new_string }

if not safe then
  print(err)
else
  okay,err = pcall(safe)
  if not okay then
    print(err)
  end
end

debug.setmetatable("",old_string_mt)

x = string.dump(print)
if x then
  print "The MCP still retains power"
end

  -spc (Granted, if you want to keep calling safe() over and over, you'll
	need to reset the string metatable prior to each call ... )