[Python-ideas] Security: remove "." from sys.path?

Niki Spahiev niki.spahiev at gmail.com
Fri Jun 2 03:52:28 EDT 2017


On  1.06.2017 19:46, Chris Angelico wrote:
> On Fri, Jun 2, 2017 at 2:30 AM, Victor Stinner <victor.stinner at gmail.com> wrote:
>> Perl 5.26 succeeded to remove the current working directory from the
>> default include path (our Python sys.path):
>>
>> https://metacpan.org/pod/release/XSAWYERX/perl-5.26.0/pod/perldelta.pod#Removal-of-the-current-directory-(%22.%22)-from- at INC
>>
>> Would it technically possible to make this change in Python? Or would
>> it destroy the world? Sorry, it's a naive question (but honestly, I
>> don't know the answer.)
> 
> (AIUI, the *current directory* is never on Python's path, but the
> *script directory* is. They're the same thing a lot of the time.)
> 
> All it'd take is one tiny change to Python, and then one tiny change
> to any multi-file non-package Python app.
> 
> 1) Make the script directory implicitly function as a package. In
> effect, assume that there is an empty __init__.py in the same
> directory as the thing you just ran.
> 
> 2) Any time a Python app wants to import from its own directory, it
> needs to "from . import blah" instead of simply "import blah".
> 
> Then the removal you suggest could be done, without any loss of
> functionality. The change could alternatively be done as an import
> hack rather than an actual fake package if that's easier, such that
> "from . import blah" means either "import from the script directory"
> or "import from the current package" as appropriate.

Hack for tesing this idea:

#!/bin/env python3

__path__ = '.'
import sys; sys.modules[''] = sys.modules['__main__']

# rest of the script

+1

Niki



More information about the Python-ideas mailing list