lua-users home
lua-l archive

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


Repeating Pedro's suggestion...

Or take a look at
http://tcs01.les.inf.puc-rio.br/wiki/w/LuaLanguage/ScriptSandboxing

Explaining the significance of the suggestion...
The construct...
    for k,v in pairs( _G ) do
        t[ k ] = v
    end
is insufficient because it is not a "deep" copy.  Any global tables will be
"linked to" in both environments, and their members can be globally changed.
So for instance, no library functions are protected from being changed.


-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br]On Behalf Of Kevin Baca
Sent: Friday, November 14, 2003 12:00 PM
To: 'Lua list'
Subject: RE: setfenv, how to...


Another possibility is:

function instantiate( chunk )
    local t = {}
    for k,v in pairs( _G ) do
        t[ k ] = v
    end

    setfenv( chunk, t )

    chunk()

    return t
end

local chunk = loadfile( "somefile.lua" )

local obj0 = instantiate( chunk )
local obj1 = instantiate( chunk )
local obj2 = instantiate( chunk )

Where somefile.lua might contain:

value = 0

function setValue( n )
{
    value = n
}

Now you can:

obj0.setValue( 2 )
obj1.setValue( 4 )
obj2.setValue( 6 )

print( obj0.value )
> 2
print( obj1.value )
> 4
print( obj2.value )
> 6

-Kevin

>
> Hello,
>
>     Thanx Kevin and Pedro by trying to solve my problem, but
> a "working"
> (temporally) solution is in setfenv.lua, file attached.
>     The problem was after adding functions to the "protected"
> global, for
> example:
>     -- block code
>     function addGlobalVarI()
>             I = 123;
>             print(I);
>     end
>
>     tab.addGlobalVarI = addGlobalVarI;
>     -- end of block
>
>     Well, adding this function in tab without setfenv'ing it
> to tab (protecting), has 2 secure problems: 1) the function
> will set I in the old global table, and 2) a function inside
> tab can call getfenv to it and, well, then will have the real
> global table, and can add anything to it, breaking the
> protection. This is true to any function added to tab.
>     But, if I setfenv it, then if this function is inside
> other "enviromments", the I will be written inside the wrong
> one. What's the best? At momment, in runtime, inside lua, the
> best is to use wrapper functions, who do nothing more than
> prior to call the real function, setfenv to his global table,
> call the function, and than restore the enviromment to its original.
>
>     Someone has a better way/idea? Or comments? See the code
> to test this in setfenv.lua. The file is incomplete.
>     Beware that this code is to making things without loading
> or dofile'ing anything.
>
>
>       The God's Peace,
>
>
> Leandro.
>