Start learning free

LESSON 40 OF 76 · SECURITY: INJECTION

New Lines in Headers

Practice

An HTTP answer starts with headers, one per line, and then the body. A download sends Content-Disposition: attachment; filename=… so the browser saves the body as a file with that name. This shop lets the visitor pick the name with ?name=, and the starting code glues it into the header as typed.

The attack: the attacker sends a visitor a link to the shop whose name holds a line break (%0D%0A), or a quote and a ;. The attacker gets to write headers into the shop's answer to that visitor. A line break starts a new header, such as Set-Cookie: session=attacker, which plants the attacker's session so the visitor is signed in as the attacker. A "; filename*=UTF-8''prices.html makes the browser save the price list as prices.html. Werkzeug, under Flask, refuses headers with a line break, so the starting code crashes with 500 there; a crash is not a fix, and the quote goes right through.

The fix is an allowlist: instead of hunting for bad characters, list the ones you allow and refuse everything else, as this coupon check does:

ALLOWED = string.ascii_uppercase + string.digits
for character in coupon:
    if character not in ALLOWED:
        return jsonify({"error": "Coupon codes use A-Z and 0-9"}), 400

In this header, a file name with a space belongs inside double quotes. Once the loop has refused every quote, nobody can close yours early. The price list must answer, with the CSV list as the body of each 200:

GET /price-list  →  200  Content-Disposition: attachment; filename="prices.csv"
GET /price-list?name=May prices.csv  →  200  Content-Disposition: attachment; filename="May prices.csv"
GET /price-list?name=prices.csv%0D%0ASet-Cookie: session=attacker  →  400  {"error": "Use only letters, digits, spaces, - _ and . in the name"}
GET /price-list?name=prices.csv"; filename*=UTF-8''prices.html  →  400  {"error": "Use only letters, digits, spaces, - _ and . in the name"}

Your task: add SAFE_CHARACTERS (letters, digits, space, -, _ and .). Loop over the name and answer 400 with the error above at the first character that isn't on the list. Then put double quotes around the name before it goes into the header.


Assignment
Follow the Coding Tutorial to check the file name against an allowlist, refuse anything else with 400, and quote the name in Content-Disposition.


Hint
string.ascii_letters and string.digits hold every letter and digit, and + joins texts. character not in SAFE_CHARACTERS is True for a line break, a quote or a ;. Add the quotes after the loop.


STEP 1 OF 5
    Ctrl + Enter to check