Lesson 09 · 35 minutes
Stop shell injection and mass assignment and test each fix
- Run a program from a server without a shell and allow only a safe name pattern
- Build an object from fields that the server picks, not from the body
- Prove each fix with a test that also checks normal use
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 support tool lists the files of a folder that the user names, and it saves notes. A review asks two questions. Can a folder name run another command? Can a client choose who owns a note? Your task is to build a small server with both flaws, show each one with a test, fix it, and then add a route that is safe from the first line.
Recall
Lesson 4. Where must the owner of a new note come from?
From the key or the session. Never from the body, because the client writes the body.
Lesson 8. Which header does the server compare with a list to refuse a cross-site POST, and who sets it?
Origin. The browser sets it, and a page script cannot change it.
The idea
Two gaps, one fix each.
| Gap | What goes wrong | The fix |
|---|---|---|
| OS command injection | User text becomes part of a shell command | Run no shell, pass arguments as a list, allow only a pattern |
| Mass assignment | Every field of the body is copied into the object | The server picks the fields |
A shell is the program that reads a command line and starts the programs in it. A ; ends one command and starts the next. If a server builds a command line from user text, the user can add commands of their own. This is OS command injection, the same root flaw as SQL injection in lesson 5: text becomes code.
Mass assignment is the same mistake with objects. The server copies every field of the body into a new object, so the client can set fields that it must not set, such as owner.
Worked example
1. Prepare a folder
mkdir makes a folder, and touch creates an empty file. The route will list the folder docs.
cd ~/krlab/web-apis
mkdir -p docs
touch docs/a.txt docs/b.txt2. Write the server that has both flaws
Create inputs.py. It reads the fixed cookie session of lesson 8. Three things are new:
subprocess.runstarts another program. Withshell=Trueit starts a shell and gives it one text.capture_output=True, text=Truecollect the output of the program as text, and.stdoutis what the program prints.lslists the files of a folder.note.update(body)copies every key ofbodyintonote.
The comments mark the flaws.
inputs.py
import json, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
SESSIONS = {"demo-session": "alice"} # a fixed cookie session, for the test only
NOTES = []
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def user(self):
for part in self.headers.get("Cookie", "").split(";"):
name, _, value = part.strip().partition("=")
if name == "sid":
return SESSIONS.get(value)
def do_GET(self):
if self.user() is None:
return self.reply(401, {"error": "not authenticated"})
url = urlsplit(self.path)
if url.path == "/list":
name = parse_qs(url.query).get("dir", ["docs"])[0]
out = subprocess.run("ls " + name, shell=True, capture_output=True, text=True).stdout
return self.reply(200, {"files": out.split()}) # the flaw: the text goes to a shell
self.reply(404, {"error": "not found"})
def do_POST(self):
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path != "/notes":
return self.reply(404, {"error": "not found"})
try:
size = max(0, int(self.headers.get("Content-Length") or 0))
body = json.loads(self.rfile.read(size))
text = body["text"]
except (ValueError, KeyError, TypeError):
return self.reply(400, {"error": "send JSON with a text field"})
note = {"owner": user, "text": text}
note.update(body) # the flaw: the client can set any field
NOTES.append(note)
self.reply(201, note)
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()3. Write the test
Create inputs_test.sh. It has the same two helpers as lesson 8, because each file is printed whole: check compares the status of an answer with the status that you expect, and without fails when a given text appears in the answer.
The new curl option is -G. It puts the data in the address as a query string, as a GET, and --data-urlencode makes the text safe for an address, so a space and a ; arrive whole. Two lines prove normal use, so that a fix cannot pass by refusing everything: a good folder must be listed and a normal note must be saved.
inputs_test.sh
H=http://127.0.0.1:8300
J='Content-Type: application/json'
C='Cookie: sid=demo-session'
check() { # label, expected status, curl arguments
got=$(curl -s -o /dev/null -w '%{http_code}' "${@:3}")
[ "$got" = "$2" ] && echo "PASS $2 $1" || { echo "FAIL $1: wanted $2, got $got"; FAILED=1; }
}
without() { # label, text that must not appear in the headers or the body, curl arguments
out=$(curl -si "${@:3}")
case "$out" in
*"$2"*) echo "FAIL $1: the answer holds $2"; FAILED=1 ;;
HTTP*) echo "PASS $1" ;;
*) echo "FAIL $1: no answer"; FAILED=1 ;;
esac
}
check "no session" 401 $H/list
check "list a good folder" 200 -H "$C" "$H/list?dir=docs"
check "a normal note" 201 -H "$C" -H "$J" -d '{"text":"hi"}' $H/notes
without "owner from the body" '"owner": "bob"' -H "$C" -H "$J" -d '{"text":"hi","owner":"bob"}' $H/notes
without "command in the name" pwned -H "$C" -G --data-urlencode "dir=docs; echo pwned" $H/list
exit ${FAILED:-0}4. Run it against the flawed server
Start the server in one terminal with python3 inputs.py. In a second terminal (type cd ~/krlab/web-apis first), run the test.
bash inputs_test.shPASS 401 no session
PASS 200 list a good folder
PASS 201 a normal note
FAIL owner from the body: the answer holds "owner": "bob"
FAIL command in the name: the answer holds pwnedTwo lines fail: the note went to bob, and the shell ran echo pwned and listed the word as a file. The three PASS lines must stay: a fix must keep normal use working.
5. Fix the command
Stop the server. In do_GET, replace the two lines that start with out = subprocess.run and return self.reply(200 with the four lines below, and add re to the first line of the file (import json, re, subprocess). The pattern allows 1 to 20 lowercase letters. The list goes to ls as arguments, so no shell reads the text, and -- ends the options, so a name that starts with -, such as -la, is read as a folder and not as an option.
if not re.fullmatch(r"[a-z]{1,20}", name):
return self.reply(400, {"error": "bad folder name"})
out = subprocess.run(["ls", "--", name], capture_output=True, text=True).stdout
return self.reply(200, {"files": out.split()})6. Fix the body
In do_POST, delete the line note.update(body) and keep the line before it. The server now builds the note from the two fields that it chooses.
note = {"owner": user, "text": text} # the server picks the fields7. Run the test again
Start python3 inputs.py again and run bash inputs_test.sh.
PASS 401 no session
PASS 200 list a good folder
PASS 201 a normal note
PASS owner from the body
PASS command in the nameAll five lines pass. Stop the server with Ctrl+C.
8. The finished file
The finished file: inputs.py
inputs.py
import json, re, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit
SESSIONS = {"demo-session": "alice"} # a fixed cookie session, for the test only
NOTES = []
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj):
data = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def user(self):
for part in self.headers.get("Cookie", "").split(";"):
name, _, value = part.strip().partition("=")
if name == "sid":
return SESSIONS.get(value)
def do_GET(self):
if self.user() is None:
return self.reply(401, {"error": "not authenticated"})
url = urlsplit(self.path)
if url.path == "/list":
name = parse_qs(url.query).get("dir", ["docs"])[0]
if not re.fullmatch(r"[a-z]{1,20}", name):
return self.reply(400, {"error": "bad folder name"})
out = subprocess.run(["ls", "--", name], capture_output=True, text=True).stdout
return self.reply(200, {"files": out.split()})
self.reply(404, {"error": "not found"})
def do_POST(self):
user = self.user()
if user is None:
return self.reply(401, {"error": "not authenticated"})
if self.path != "/notes":
return self.reply(404, {"error": "not found"})
try:
size = max(0, int(self.headers.get("Content-Length") or 0))
body = json.loads(self.rfile.read(size))
text = body["text"]
except (ValueError, KeyError, TypeError):
return self.reply(400, {"error": "send JSON with a text field"})
note = {"owner": user, "text": text} # the server picks the fields
NOTES.append(note)
self.reply(201, note)
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()Your turn
Add a route to the fixed inputs.py that is safe from the first line. There are no steps here.
POST /profiletakes a JSON body with anameand answers 200 with{"user": ..., "name": ...}. Only these two fields may be in the answer, whatever the body holds. A request with no session gets 401.- Restart the server. Call
/profilewith the cookiesid=demo-sessionand the body{"name":"Ann","role":"admin"}, and count the fields of the answer. - Make the folder
data2with a file in it. Call/listwithdir=docs;ls, and then withdir=data2. Read both statuses and think about what the pattern costs.
Check yourself
Why is `["ls", "--", name]` safer than `"ls " + name`, and why keep the pattern check as well?
The list goes to the program as arguments, so no shell reads ; or |. The pattern is a second layer. The safest fix is to run no program, as os.listdir does.
The pattern refuses the folder data2, which is harmless. Is that a bug?
It is a cost that the owner of the API chooses. An allow list is strict by design: it refuses what nobody planned for. If digits are needed, add 0-9 to the pattern and test again.
Why is it not enough to remove the field `owner` from the body?
Tomorrow a new field such as role or price can appear, and the blacklist misses it. The server should name the fields that it accepts and ignore the rest.
Field notes
- OWASP Top 10 "Injection" includes OS command injection (A05 in the 2025 edition, A03 in 2021). In the OWASP API Security Top 10 2023, API3:2023 "Broken Object Property Level Authorization" joins two 2019 items, "Excessive Data Exposure" and "Mass Assignment".
- Prefer a library call to a program.
os.listdirorpathliblists a folder with no shell and no pattern. Static analysis tools, such as Bandit for Python, flagshell=True. - The same pattern
[a-z]{1,20}also stops../etc. A client that puts..into a file or folder name reads outside the folder you meant: this is path traversal. If you must allow dots, resolve the path and check that it stays inside the base folder. - Use
re.fullmatch: it checks the whole text. A$at the end of a pattern withre.matchstill accepts a trailing newline. - Define the fields of each route by name, in one place: the list answers "what may a client set?" and "what may it see?".
- Tell the owner of a service that a refusal is a design choice, and test the normal use next to the attack, as
inputs_test.shdoes.