pythonchdirgetcwdpython-exec

Isolate state change of chdir within python exec scope


Running a script with exec, how does one "backup" python process global state in its entirety and restores it afterwards?

code example:

import os
print(os.getcwd())
a = 8
print(a)
exec_scope = {}
exec("""
import os
os.chdir('../new place')
a = 9
print(a)
""", exec_scope)
print(os.getcwd())
print(a)

output:

C:\original place
8
9
C:\new place
8

The goal is to exec non-malicious code without having any global side-effect by backing up the current state and undoing any changes that may occur legitimately during the exec of the external (but safe) script.

This question was changes because the original wording would be interpreted that there is a need to protect against malicious code and that is not the focus. The assumption is that the external code is completely safe and holds not ill intentions but may affect the global state of the process for legitimate reasons and this effect was decided is undesirable.

So the goal of the question is to find the easiest/fastest/simplest way to undo any changes to the global state that can be undone.


Solution

  • The goal is to safely exec

    Yeah, no, that's not going to happen.

    You could spawn (or fork()) a subprocess that runs the exec()'d code, but that only isolates you from some state changes, not the code going rogue and e.g. destroying your file system.

    On that note, you can't use exec() safely on any arbitrary code; the best you could do is pre-parse the code to see if there are "unsafe" constructs in there, and either deny running them or get rid of them altogether (and of course hope that you've thought of everything).