Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Typosquatting: one letter out

After this lesson: I can spot a package name that imitates a real one.

50 min lesson13 commandsDevSecOps lab: build a security pipeline and a gate

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

One letter too many

You type pip install with a name you know well, and one finger slips. You press Enter before you notice.

If nobody owns the misspelt name, pip just fails. If an attacker registered it last week, it installs their code, and it may work so well you never notice.

By the end of this lesson

Note

I can spot a package name that imitates a real one.

Key words

WordWhat it meansExample
Typosquattingregistering a misspelling of a popular name
Lookalikea name made to be mistaken for anothershopkitt
Normalised namea name after case and - _ . are made the same
Edit distancehow many letters change one name into another
Allow-listthe packages you have approved, and no others

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The rule for this lesson

Warning

You will publish lookalike packages, in your own lab copy only. Every name here is made up and both indexes are inside the lab. Never upload a lookalike to a real index. Putting code on someone else's systems without permission is a crime under the Computer Misuse Act 1990.

A popular name and its lookalikes

On the public index, shopkit is a popular made-up library. The shop approved it and copied it to its private index.

An attacker registers lookalike names: shopkitt, with one letter too many, and shop-kit, with a hyphen. Write the package builder if lesson 4 did not, then publish all of them.

Write the package builder (part 1)

Command
docker exec -i ci sh -c "cat > pkg.py" <<'EOF'
"""Puts a made-up package in one of the lab's package indexes:
python3 pkg.py private|public NAME VERSION WORDS
Importing it prints WORDS and does nothing else."""
import hashlib
import os
import re
import sys
import zipfile

index, name, version, words = sys.argv[1:5]
module = re.sub(r"[-_.]+", "_", name).lower()
info = module + "-" + version + ".dist-info/"
files = {
    module + "/__init__.py": "print(" + repr(words) + ")\n",
    info + "METADATA": "Metadata-Version: 2.1\nName: " + name + "\nVersion: " + version + "\n",
    info + "WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
}
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the package builder (part 2)

Command
docker exec -i ci sh -c "cat >> pkg.py" <<'EOF'
files[info + "RECORD"] = "".join(path + ",,\n" for path in [*files, info + "RECORD"])
folder = "/tmp/pkg/" + index + "/simple/" + module.replace("_", "-")
os.makedirs(folder, exist_ok=True)
out = folder + "/" + module + "-" + version + "-py3-none-any.whl"
with zipfile.ZipFile(out, "w") as wheel:
    for path, text in files.items():
        wheel.writestr(zipfile.ZipInfo(path, (2026, 1, 1, 0, 0, 0)), text)
print(index, out.split("/")[-1], hashlib.sha256(open(out, "rb").read()).hexdigest())
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Publish the real library, and the approved copy

Command
docker exec ci python3 pkg.py public shopkit 2.4.0 "shopkit 2.4.0, the real one" && docker exec ci python3 pkg.py private shopkit 2.4.0 "shopkit 2.4.0, the real one"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Publish two lookalikes

Command
docker exec ci python3 pkg.py public shopkitt 2.4.0 "shopkitt, not shopkit: this could have been any code" && docker exec ci python3 pkg.py public shop-kit 1.0.0 "shop-kit, not shopkit: this could have been any code"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Start the two indexes

Command
docker exec -d ci python3 -m http.server 8100 --bind 127.0.0.1 -d /tmp/pkg

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make the typo

Command
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ shopkitt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Install it and import it

Command
docker exec ci pip install --no-cache-dir -q --user --index-url http://127.0.0.1:8100/public/simple/ shopkitt && docker exec ci python3 -c "import shopkitt"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Some differences do not count

An index normalises names: it ignores case and treats -, _ and . as the same. So Shop_Kit and shop.kit are one name, shop-kit.

But shopkit and shop-kit are two different names, which is exactly the gap an attacker uses.

Try it: normalise some names

Code: python
import re

def normalise(name):
    return re.sub(r"[-_.]+", "-", name).lower()

for typed in ["Shop_Kit", "shop.kit", "SHOPKIT", "shopkit"]:
    print(typed, "->", normalise(typed))

# Add "shop--kit" to the list and press Run. Which name does it become?

Make a free account to save your work and track your progress.

Ask for Shop_Kit

Command
docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/public/simple/ Shop_Kit

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a typo simply fails to install. It fails only while nobody owns the name. Attackers register common misspellings in advance, and a good lookalike also works, so the mistake is never noticed.

Check every new name against a list

A pipeline can compare each wanted name with the allow-list. A name on the list passes. A name a letter or two from an approved one is suspect. Anything else needs a person to review it.

The edit distance counts the letters to change, add or remove.

Write the name checker (part 1)

Command
docker exec -i ci sh -c "cat > namecheck.py" <<'EOF'
# Checks wanted names against an approved list: python3 namecheck.py approved.txt wanted.txt
import re
import sys

def norm(name):
    return re.sub(r"[-_.]+", "-", name).lower()

def distance(a, b):
    row = list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        prev, row[0] = row[0], i
        for j, y in enumerate(b, 1):
            prev, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, prev + (not x == y))
    return row[-1]
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the name checker (part 2)

Command
docker exec -i ci sh -c "cat >> namecheck.py" <<'EOF'

approved = [norm(line.strip()) for line in open(sys.argv[1]) if line.strip()]
for line in open(sys.argv[2]):
    name = norm(re.split(r"[=<>~ ]", line.strip())[0])
    near = [one for one in approved if 0 < distance(name, one) <= 2]
    if name in approved:
        print("OK     ", name)
    elif near:
        print("SUSPECT", name, "looks like", near[0])
    elif name:
        print("NEW    ", name, "needs a review")
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the approved and wanted lists

Command
docker exec ci sh -c "printf 'shopkit\nrequests\njinja2\npyyaml\n' > approved.txt && printf 'shopkitt==2.4.0\nRequests==2.33.0\njinja2==3.1.6\npyyam1==6.0.2\nflask==3.1.2\n' > wanted.txt"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the wanted names

Command
docker exec ci python3 namecheck.py approved.txt wanted.txt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

The fix: install from the approved index only

Command
docker exec ci pip uninstall -q -y shopkitt && docker exec ci pip install --no-cache-dir --dry-run --index-url http://127.0.0.1:8100/private/simple/ shopkitt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: catch a lookalike name

Write three functions that check a package name against an approved list.

normalise(name) lowers a name and turns every run of -, _ and . into one -. distance(a, b) returns the edit distance between two strings: the fewest single letters added, removed or changed to turn one into the other. classify(name, approved) normalises name and every approved name, then returns ("approved", name) when it is on the list, ("lookalike", closest) when an approved name is 1 or 2 edits away (the closest, and the first in alphabetical order on a tie), and ("unknown", None) otherwise.

Code: python
def normalise(name):
    return name


def distance(a, b):
    return 0


def classify(name, approved):
    return ("unknown", None)

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.