Skip to content

Commit

Permalink
Remove /usr/bin from sys.path to avoid accidentally importing garbage
Browse files Browse the repository at this point in the history
See https://bugzilla.redhat.com/show_bug.cgi?id=2057340
and benjaminp/six#359

dnf should never import Python modules from /usr/bin but users can
have files in there that look like Python modules and Python will
try to import them and fail.

Consider a tool that is *not* written in Python and is called "copy.pyc".
Naturally, it resides in /usr/bin/copy.pyc and dnf fails:

    Traceback (most recent call last):
      File "/usr/bin/dnf", line 57, in <module>
        from dnf.cli import main
      File "/usr/lib/python3.10/site-packages/dnf/__init__.py", line 30, in <module>
        import dnf.base
      File "/usr/lib/python3.10/site-packages/dnf/base.py", line 31, in <module>
        from copy import deepcopy
    ImportError: bad magic number in 'copy': b'...'

Similarly, a tool actually written in Python, called "copy.py"
might as well own /usr/bin/copy.py and dnf fails as well:

    Traceback (most recent call last):
      File "/usr/bin/dnf", line 57, in <module>
        from dnf.cli import main
      File "/usr/lib/python3.10/site-packages/dnf/__init__.py", line 30, in <module>
        import dnf.base
      File "/usr/lib/python3.10/site-packages/dnf/base.py", line 31, in <module>
        from copy import deepcopy
    ImportError: cannot import name 'deepcopy' from 'copy' (/usr/bin/copy.py)

Either problem can happen for a variety of names.
We better not let that happen.

A more general solution that would prevent Python doing this entirely
does not exists yet, see https://discuss.python.org/t/4235

Hence, proposing this to dnf, which is a critical piece of the system.
  • Loading branch information
hroncok authored and lukash committed Feb 25, 2022
1 parent e87aa5d commit c68038f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion bin/dnf-automatic.in
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ import os
import sys

here = sys.path[0]
if here != '/usr/bin':
if here == '/usr/bin':
# we never import Python modules from /usr/bin
# removing this lowers the risk of accidental imports of weird files
del sys.path[0]
else:
# git checkout
dnf_toplevel = os.path.dirname(here)
sys.path[0] = dnf_toplevel
Expand Down
6 changes: 5 additions & 1 deletion bin/dnf.in
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ if __name__ != "__main__":
sys.exit(1)

here = sys.path[0]
if here != '/usr/bin':
if here == '/usr/bin':
# we never import Python modules from /usr/bin
# removing this lowers the risk of accidental imports of weird files
del sys.path[0]
else:
# git checkout
import os
dnf_toplevel = os.path.dirname(here)
Expand Down

0 comments on commit c68038f

Please sign in to comment.