Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protecting imported modules from being corrupted by third party code

Tags:

python

If my code uses third party modules that cannot be trusted, is there anything to prevent situation like this:

UntrustedModule.py:

import random

random.random = lambda : 4

MyModule.py:

import random
import UntrustedModule

print (random.random())

where just importing this module breaks assumptions about other, unrelated ones?

like image 710
Kim Strauss Avatar asked Mar 13 '13 12:03

Kim Strauss


1 Answers

No, you can't have any such guarantee in Python, at least not in the CPython implementation. When you import a module its code is run, and it has full access to every part of the interpreter (and likely big parts of your system). No way to avoid this. It is unwise to ever load untrusted code, because there is so much it can do.

However you may be interested in running the process in an isolated process, and only communicate with it by IPC. This is a huge topic and it depends on the degree of isolation you need and how much you trust the external code.


PyPy implements some sandboxing features. It's not as simple as just "turning sandboxing on" but it's one of many ways to isolate untrusted code.

like image 173
Davide R. Avatar answered Nov 15 '22 11:11

Davide R.