More likely than not, sandboxing is a key feature in your MoonSharp usage. Unless you control, in some way, the script providers (and maybe also the users), there is a fundamental trust problem in loading scripts (or any kind of code and sometimes even data) at runtime: security.
For example, let’s say that you are writing a videogame and you use Lua to make the game “moddable”. Users can go to some community website and download a mod containing
new levels, AIs and what-not all scripted using MoonSharp for the maximum flexibility. Everybody is happy. Now think of what would happen to your game’s reputation if some
evil user uploads some malicious scripts well hidden in some beautiful level.. like a script creating an .exe file on the desktop, where other users are likely to click
accidentally.
You don’t want to expose some APIs (like ‘os’, ‘io’ and ‘file’) to the general users unless either you trust them or it’s plainly evident that malicious use is possible.
A Sandboxing checklist
This checklist is something to get you started, but it’s not comprehensive.
Check that you made all “dangerous” standard APIs inaccessibile to scripts. This include ‘io’, ‘os’ and ‘file’ for sure, but depending on your scripts and your level of paranoia more could be included. See the next chapter to see how to make whole sets of APIs inaccessible in an easy way.
Do NOT use InteropRegistrationPolicy.Automatic. Ever.
Check that you are not exposing to scripts types, or member of types, which shouldn’t be exposed. Avoid exposing directly types you don’t own, like .NET framework types or Unity types. If needed, check the section about “proxy objects” and how to use MoonSharpHide and MoonSharpHidden.
If you want parts of your scripts to access some of these dangerous APIs, keep them in separate Script objects and ensure no access to those objects is given to other scripts.
If you absolutely must “sandbox” only a part of your script, refer to this evergreen guide.
Removing “dangerous” APIs
The easiest way to remove dangerous APIs is to use the constructor of Script which accepts a CoreModules enumeration.
The CoreModules enumeration is pretty self-explanatory: