Sign in to follow this  
TheBuzzSaw

Lua safety/security

Recommended Posts

I have two questions regarding Lua integration into C programs. First off, I am not sure how to load libraries in Lua 5.1 from C. The documentation mentions: The luaopen_* functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function. http://www.lua.org/manual/5.1/manual.html#7.3 Is that implying that I need to make a call to Lua referencing the package.loadlib function? Or something else? How do I selectively load libraries that I want available to my Lua scripts? This brings me to my second question: can I prevent Lua scripts from loading libraries? Looking over the Lua language, I really only want to grant access to math, string, and maybe table. I don't want scripts calling io or anything that can access the system outside of my program. However, it seems that Lua openly allows the loading of libraries from Lua itself. Can I prevent that?

Share this post


Link to post
Share on other sites
That part of the documentation simply says that you shouldn't open libraries from C, unless you're doing it as part of luaL_openlibs, or you'd have to invoke them through lua_call.

In order to prevent lua from opening more libraries; you can overwrite the functions that do the loading to do nothing (or log something). Look at Sandboxing Lua for more information.

Share this post


Link to post
Share on other sites
The way the manual describes it can be a bit confusing. If you look at luaL_openlibs defined in linit.c it should make more sense. You basically just push the library along with the name of the table/namespace that you want to open onto the stack and call it.

You can, of course, just remove the libraries you don't want Lua to open from the lualibs array in linit.c and call luaL_openlibs like you normally would.

Share this post


Link to post
Share on other sites
You can sandbox scripts by setting the various interfaces you want to limit to nil, like :

os = nil;

this will clear the entire os functions set. They still exist, but only on the C side now. The only issue is that someone could have squirreled away the interface for whatever reason. So you have to do this very early or just not load up the libraries at all (by modifying linit.c as others have suggested).

I've implemented a simple sandbox for Lua using that technique, but I found without require and setmetatable Lua becomes too limited so I left those in, but modified somewhat.

Good Luck!

-ddn

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this