Start learning free

LESSON 37 OF 76 · SECURITY: INJECTION

Command Injection: No Shell

Practice

POST /thumbnail makes a small copy of a photo by running an image tool, mogrify, on the name the visitor sends. The first version built one string with the name in it and ran it through a shell, the program that reads what you type in a terminal:

command = "mogrify -path thumbs -thumbnail 100x100 photos/" + name
result = subprocess.run(command, shell=True, capture_output=True, text=True)

The attack: to a shell, ; means "now run the next command" and $( ) means "run this first and paste in what it prints". A visitor sends the name a.png; cat secrets.txt, and the shell runs cat right after mogrify. The attacker gets every secret in secrets.txt printed into the answer, and can run any other command on your server the same way.

The fix: leave the shell out. Give subprocess.run a list, the program and then each argument as its own string, and no shell=True. Python starts the program itself and hands it each item as exactly one argument, so a ; or a space in a name is just part of the name. For example, zipping one day's orders:

command = ["zip", "-j", "backup.zip", "orders/" + day + ".csv"]
result = subprocess.run(command, capture_output=True, text=True)

The name is still part of a path, though: ../secrets.txt would point the tool at a file outside photos/. So also let a name through only if it is one of the files in os.listdir("photos"). In this lesson a stand-in mogrify prints each argument it gets in [ ], so you can see exactly what reached it:

POST /thumbnail  {"name": "mug.png"}                 →  200  {"log": "mogrify [-path] [thumbs] [-thumbnail] [100x100] [photos/mug.png]\n", "thumbnail": "thumbs/mug.png"}
POST /thumbnail  {"name": "beach day.png"}           →  200  {"log": "mogrify … [100x100] [photos/beach day.png]\n", "thumbnail": "thumbs/beach day.png"}
POST /thumbnail  {"name": "a.png; cat secrets.txt"}  →  404  {"error": "No photo named a.png; cat secrets.txt"}
POST /thumbnail  {"name": "$(cat secrets.txt).png"}  →  404  {"error": "No photo named $(cat secrets.txt).png"}
POST /thumbnail  {"name": "../secrets.txt"}          →  404  {"error": "No photo named ../secrets.txt"}

Your task: the starting code has no command yet, so every request answers 500. Below the name line, set command to a list and run it with subprocess.run, without shell=True, keeping its output as text in result. Then, above command, answer 404 with "No photo named " plus the name when name is not one of the files in photos.


Assignment
Follow the Coding Tutorial to run mogrify from a list instead of a shell, and to let only real photos through.


Hint
Each item of the list reaches the program as one argument: "mogrify", "-path", "thumbs", "-thumbnail", "100x100", then the photo's path. not in works on the list that os.listdir gives back.


STEP 1 OF 4
    Ctrl + Enter to check