Accumulator
Accumulator

Reputation: 903

Safely execute arbitrary Lua code with only C

I know that you can safely execute arbitrary code from Lua by whitelisting safe things with the Lua function setfenv. But if I do this through a script, not only is it untidy, but (user-moddable game) an unsuspecting user installing a mod could just click "replace all" or something when installing a mod into a folder, without thinking anything of it. I'm sure there are other ways it could be bypassed super-easily too.

Overall the safest way to be safe should be to do this with direct C calls, with no Lua code/strings involved in setting the sandbox. How can I do this?

Upvotes: 2

Views: 555

Answers (2)

Dafoosa
Dafoosa

Reputation: 123

Anything you code in a Lua script can also be performed in C via the Lua C API. But it's harder to follow in C than the equivalent Lua script. When I have wanted to have some protected Lua scripts for a host program I have done things like for example:

  • put them in a separate directory.
  • Encrypt them into an archive that only my C program knows the private key for.
  • Embedded them as multi-line strings in the C source code.
  • Embed the compiled scripts as binary strings in my C source code so that they not as easily hack-able via the binary edit of program's exe. (Sometimes I use a SHA of the scripts to prevent them from being edited within the exe) ...and so on.

You definitely want to protect the computer running your game from malicious scripts by using sandboxes. E.g no file system access. But note, that to also protect your host program from all forms of malicious scripts (e.g. hanging the game's Lua instance thread via a while 1 loop; or huge memory use, complex string.match calls for e.g.) you have to do more complex work and add more constraints to the environment given to mod scripts.

E.g. even a while 1 do end will still hang the WOW UI.

Hope that helps.

Upvotes: 1

Ace shinigami
Ace shinigami

Reputation: 1484

just don't use luaL_openlibs. Another option would be to have some lua code exist in your c program as a string or bytecode, that you execute before anything else.

Upvotes: 0

Related Questions