Lesson 07 · 45 minutes
Install packages and check them before you trust them
- Install packages with pip inside a virtual environment and pin their versions
- Check a package file against a hash before it installs
- Inspect a package before you trust it, and spot a name that copies another
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A colleague pastes a line into the team chat: "Run pip install reqeusts, it has the helper that we need." Another colleague asks you to prepare the tool for the build server, where nobody must install "whatever is newest" on the day of the build. Your task is to pin the packages with hashes, to check a delivery of package files against a list of known fingerprints, and to catch names that copy popular ones. Each of these is a small program that you can write.
Recall
Lesson 1: how do you prove from inside Python that you run in a virtual environment, and not in the system Python?
Print sys.prefix and sys.base_prefix. In a venv they differ: the first is the venv folder, the second is the system Python that it came from. which python also shows a path inside .venv/bin.
Lesson 6: where does a program read an API key from, and why not from its own source file?
From an environment variable, with os.environ. A key in a source file is copied into Git, backups and screenshots, and a deleted line stays in the history. The environment keeps the key out of the code.
The idea
pip is the package installer. It fetches a package and everything that it depends on. The result is a tree: you ask for one package and get five.
| Tool | Job |
|---|---|
pip install name | Install the newest version. |
pip freeze | Print every installed package with its exact version. |
requirements.txt | A file with those lines. pip install -r rebuilds the environment from it. |
--require-hashes | Refuse any file whose SHA-256 hash is not in your file. |
A hash is a fingerprint of a file. One changed byte gives a different fingerprint. If you record the hash of a file that you checked, pip can detect a file that has changed since.
- requirements.txt → pip: name==version and SHA-256
- pip → Package index: send me that exact file
- Package index → pip: the file
- pip: hash the file, compare with the pin
- pip → .venv: install only when they match
Always work inside a virtual environment (lesson 1), so that a bad package stays in one project folder. Steps 1, 4, 5 and 8 of the worked example need an internet connection, because they talk to the package index (PyPI). The task in "Your turn" works offline.
Worked example
1. Install a package
pip install downloads a package and its dependencies into the active venv. This step builds a new venv, so that the lists below start clean.
mkdir -p ~/krlab/python/supply
cd ~/krlab/python/supply
python3 -m venv .venv
source .venv/bin/activate
pip install requestsInstalling collected packages: urllib3, idna, charset_normalizer, certifi, requests
Successfully installed certifi-2026.11.20 charset_normalizer-3.5.2 idna-3.20 requests-2.34.2 urllib3-2.8.0You asked for one package and got five. Your versions can be newer.
2. Look at what is installed
pip list shows the installed packages. pip show name shows one package, with its dependencies (Requires) and the packages that need it (Required-by).
pip list
pip show requestsPackage Version
------------------ ----------
certifi 2026.11.20
charset-normalizer 3.5.2
idna 3.20
pip 25.1.1
requests 2.34.2
urllib3 2.8.0
Name: requests
Version: 2.34.2
Summary: Python HTTP for Humans.
License: Apache-2.0
Requires: certifi, charset_normalizer, idna, urllib3
Required-by: The output of pip show is shortened.
3. Pin the versions
pip freeze writes each installed package as name==version. The sign > sends it into a file, and cat prints the file.
pip freeze > requirements.txt
cat requirements.txtcertifi==2026.11.20
charset-normalizer==3.5.2
idna==3.20
requests==2.34.2
urllib3==2.8.0A pin means that the same file gives the same program next month. Without a pin, a new release reaches your tool the day it is published, bad or not.
4. Rebuild from the file
Delete the environment and make it again, as a colleague or a server would. rm -rf deletes a folder with everything in it and asks nothing: read the name twice. pip install -r file installs what the file lists. pip check tests that the installed packages fit together.
deactivate
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip checkNo broken requirements found.5. Require a hash
pip download fetches a package file without installing it. --only-binary=:all: stops pip from running any build code, --no-deps fetches only this package, and -d wheels names the folder. A wheel is a package file. pip hash prints its SHA-256.
pip download --only-binary=:all: --no-deps -d wheels idna==3.20
pip hash wheels/idna-3.20-py3-none-any.whlwheels/idna-3.20-py3-none-any.whl:
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582cPut the pin and the hash in requirements-hashed.txt. A backslash continues the line. The file has this shape:
requirements-hashed.txt
idna==3.20 \
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582cpip uninstall -y removes a package without a question. sed 's/ab7ae/00000/' copies the file and replaces the first ab7ae of each line with 00000: five characters of the hash change. Install with the hash required, then with the changed hash.
pip uninstall -y idna
pip install --require-hashes -r requirements-hashed.txt
sed 's/ab7ae/00000/' requirements-hashed.txt > bad.txt
pip install --require-hashes --force-reinstall -r bad.txtSuccessfully installed idna-3.20
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.The install with the wrong hash fails, and pip prints the expected and the real hash (the output is shortened). For a whole tree, the tool pip-tools writes the pins and all the hashes for you: pip install pip-tools, then pip-compile --generate-hashes requirements.in.
6. Compute a hash yourself
You do not need pip to make a fingerprint. The module hashlib makes hashes. Path(...).read_bytes() reads a whole file as bytes, hashlib.sha256(data) hashes them, and .hexdigest() gives the hash as text. The command sha256sum does the same job in the shell, so you can compare. printf writes a text with no extras, and \n is a line end.
printf 'hello\n' > hello.txt
sha256sum hello.txt
python3 -c "
import hashlib
from pathlib import Path
print(hashlib.sha256(Path('hello.txt').read_bytes()).hexdigest())"5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 hello.txt
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03Both give the same 64 characters. Change one letter of hello.txt and run again: the hash is completely different. Read the whole file in memory only when it is small; for a big file, feed hashlib in chunks.
7. Read the name twice
A typosquat is a package whose name copies a popular one with a small change. It relies on a quick glance. Here is the attack that the scenario began with:
- Attacker → Package index: uploads reqeusts, a copy of requests
- Colleague → pip: pip install reqeusts
- pip → Package index: asks for reqeusts, gets the attacker's file
- pip → .venv: installs it: its code runs with your access
namecheck.py compares each name in a requirements file with popular names and flags a near match. The module difflib rates how much two texts look alike. get_close_matches(name, KNOWN, n=1, cutoff=0.8) returns the one name of KNOWN that is at least 80 percent alike, if there is one. sys.argv[1] is the file name that you give on the command line, and .lower() and .replace("_", "-") bring a name to one form.
namecheck.py
import difflib
import sys
KNOWN = ["requests", "urllib3", "numpy", "pandas", "cryptography", "flask", "django", "pyyaml", "scapy", "paramiko"]
with open(sys.argv[1], encoding="utf-8") as handle:
for line in handle:
name = line.split("==")[0].strip().lower().replace("_", "-")
if not name or name.startswith(("#", "-")):
continue
close = [k for k in difflib.get_close_matches(name, KNOWN, n=1, cutoff=0.8) if k != name]
if close:
print(f"{name:<22} LOOKS LIKE {close[0]}")
else:
print(f"{name:<22} ok")startswith(("#", "-")) is true when the text starts with either of the two: a comment, or an option line. continue skips to the next line of the loop. if close: is true when the list is not empty (lesson 2). Test it on a file with two bad names.
printf 'requests==2.34.2\nreqeusts==1.0\nnumpi==1.0\ncertifi==2026.11.20\n' > check.txt
python3 namecheck.py check.txtrequests ok
reqeusts LOOKS LIKE requests
numpi LOOKS LIKE numpy
certifi ok8. Look inside before you trust
A wheel is a zip file. python3 -m zipfile -l lists the files of a zip, and head -4 keeps the first four lines of the output.
pip download --only-binary=:all: --no-deps -d wheels requests==2.34.2
python3 -m zipfile -l wheels/requests-2.34.2-py3-none-any.whl | head -4File Name Modified Size
requests/__init__.py 2026-05-14 19:21:52 5922
requests/__version__.py 2026-05-14 19:21:52 435
requests/_internal_utils.py 2026-05-14 19:21:52 1542Look for files that do not belong: a .pth file (Python runs code from it at start-up), or a large file with a random name.
Your turn
Do the task of the build server. There is no code here: use what the worked example showed. This task needs no internet.
Save gen7.py in ~/krlab/python/supply. It invents a delivery of seven package files and a list of fingerprints, with a fixed seed. Two of the files were changed after the list was made. It also writes a requirements file with some invented names. (The files are random bytes, not real packages. Do not run them.) You do not need to study this generator: it only makes the data.
gen7.py
import hashlib
import random
from pathlib import Path
rng = random.Random(7)
NAMES = ["netscan-1.4.0.whl", "logtools-2.0.1.whl", "yamlsafe-0.9.3.whl", "pcapkit-3.1.0.whl",
"hashutil-1.0.0.whl", "sigmatch-0.5.2.whl", "dnsprobe-1.2.4.whl"]
TAMPERED = {"logtools-2.0.1.whl", "dnsprobe-1.2.4.whl"}
Path("incoming").mkdir(exist_ok=True)
manifest = []
for name in NAMES:
data = bytes(rng.randrange(256) for _ in range(200))
manifest.append(f"{hashlib.sha256(data).hexdigest()} {name}")
if name in TAMPERED:
data = data[:100] + bytes([data[100] ^ 1]) + data[101:]
Path("incoming", name).write_bytes(data)
Path("manifest.txt").write_text("\n".join(manifest) + "\n", encoding="utf-8")
Path("requirements-new.txt").write_text(
"requests==2.34.2\nreqursts==2.0\ncryptograpy==1.0\nflask==3.0.0\nnumpyy==1.0\nrich==13.0\n", encoding="utf-8")Run python3 gen7.py. The file manifest.txt has one line for each package: the SHA-256, two spaces, and the file name. Write verify.py, which:
- Reads
manifest.txt, hashes each file of the folderincomingand prints the name withOKorBAD. At the end it prints how many are bad. - Reads
requirements-new.txtand prints each name that looks like one of theKNOWNnames of step 7, and which one. Use the sameKNOWNlist and the same cutoff. - Returns the exit code 1 when anything is bad or looks like a copy, and 0 when all is clean.
Then answer from your own results.
Check yourself
Why is "pip install requests" in a build script a risk, even if "requests" is a good package?
It installs whatever version is newest at that moment, together with the newest versions of its dependencies. A bad release of any of them reaches you with no review. Pin the versions, and add hashes.
You pinned idna==3.20 with a hash. Someone replaces the file on the index. What does pip do?
It refuses to install, because the hash of the new file does not match. That is the point of --require-hashes.
Why does --require-hashes refuse a line that says only "idna"?
A hash belongs to one exact file, so the version must be pinned with ==. A name with no pin could mean any file, and no hash could cover it.
A colleague asks you to run "pip install reqeusts". What do you do?
Stop and compare the name letter by letter. It swaps two letters of requests. Check the package page for its age, its releases and its maintainers before anything runs.
Field notes
- A bad package is a software supply-chain failure: the OWASP Top 10 2025 lists "Software Supply Chain Failures" as category A03. A name that copies a real one is called typosquatting.
- Installing a source package (an sdist) can run code before you import anything: a build script runs at install time. Use
--only-binary=:all:when you can, and for the rest, inspect first. A wheel runs no build code at install time, but it can place a.pthfile that runs at every start, and code that runs on import. - Pin and hash the whole tree, in CI as well as on servers, and review the changes in the lock file as you review code.
pip-auditreports pinned packages with known vulnerabilities, from a vulnerability database. - A hash from the same server as the file proves only that the file did not change in transit. It does not prove that the file is good. Take the hash from a different channel, or from a file that you checked and then pinned.
- A new name with one release and few downloads deserves doubt. Check the home page, the maintainers, and whether the release matches a tag in the public repository.
namecheck.pyknows ten names. A real check uses a list of the top few thousand packages and also looks at the age and the maintainers. A near match is a reason to look, not proof. - A private package name that also exists on the public index is the dependency confusion attack. Pip prefers the highest version across all indexes it can see. Use one trusted index (or an explicit mirror), and never
--extra-index-urlfor private names.