Is there any way to build a sandbox to evaluate untrusted Mathematica expressions in order to prevent them from having (malicious or accidental) harmful side effects?
Context: I'm developing a system wherein students will enter code into designated notebook cells, and my package will extract the code, evaluate it, and offer feedback. The problem is, even if I evaluate their code within a separate context (and I'm having trouble making that happen), they could still use explicit contexts to affect a different context, invoke Quit
, or use filesystem manipulation functions to mess with my computer.
It seems to me that there are two aspects to this problem: isolating execution of their code from everything else the kernel is doing (like running my package), and isolating their code from everything on my computer external to Mathematica. The first might be accomplished by using a separate kernel (somehow), but I have no ideas for the second.
Wolfram must have addressed this problem while developing WebMathematica, right?
Answer
You should consider using the sandbox functionality. You can create a subkernel and put it in sandbox mode this way:
link = LinkLaunch[First[$CommandLine]<> " -wstp -noicon"];
LinkWrite[link, Unevaluated@EvaluatePacket[Developer`StartProtectedMode[]]];
You can then interact with this subkernel using the standard LinkWrite
and LinkRead
functions. If you don't mind your master kernel being sandboxed, you can even just evaluate Developer`StartProtectedMode[]
there, but it disables a lot of functionality (mostly import/export and file system manipulation).
Note that sandbox mode also will only allow you to load .m
/.wl
files from very specific directories. You can set this in the call itself as well:
Developer`StartProtectedMode[{"Read" -> {$myPath}, "Write" -> {$myPath}, "Execute" -> {$myPath}}]
where $myPath
is the path to where you store the code you wish to interact with.
Comments
Post a Comment