Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

security - List of Lua commands/statements to watch out?

I'm making a moddable game and thinking about using Lua as the language for my players to write their own scripts.

But like any programming language, Lua bound to have some "loopholes" for not-so-nice users to do bad things.

I'm new to Lua, so I don't really know what Lua "can" do.

I did a little reasearch online and found that Metatable and ob.exit could be used for doing bad things, is there any other things?

Could somebody please be so kind and give me a list of the things I should watch out and block it (maybe by replacing it with empty string)?

Much appreciated!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lua's built-in math, string, and table libraries will always be safe. coroutine is also safe, and extremely useful to some advanced lua programmers.

There are some other, not-so-safe libraries lua loads in by default (which you can easily disable)

  • os lets you execute commands, and do other nasty things. However, os.time and os.date are useful functions, so keep those in.
  • io allows you to read- and edit- any file on the computer. Probably best to leave it out.
  • debug allows you to "reflect" on the program. This means that the program can edit certain parts about itself, and can be unwanted. It's a safe bet that user programs won't need this. Ever.

Instead of replacing something with an empty string, you can always replace it with setfenv (Lua 5.1), like so:

   local badCode = readFile("./code.lua")
   local Func = loadstring(badCode)
   setfenv(Func, {
       -- If we leave nothing here, then the script will not be able to access any global variable.
       -- It's perfectly sandboxed. But let's give it some stuff:
       print = print, pcall = pcall, pairs = pairs, ipairs = ipairs, error = error, string = string, table = table, math = math, coroutine = coroutine,
       -- Now, let's give it some functions that *could* be useful, from an otherwise sandboxed library
       os = {
           time = os.time,
           date = os.date,
           clock = os.clock,
       },
       -- All of these are "kind of" useful to the program.

   })
   -- Now that Func is properly sandboxed, let's run it!
   Func()
   -- This is how you should treat user code.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...