Start learning free

LESSON 25 OF 56 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

Download Links That Expire in Python

Practice

Customers get an emailed link to their invoice, like /files/invoice-1.txt?exp=1800000600&sig=…. Right now download sends whatever file the path names and ignores the rest of the link. The attack: a visitor holding Ana's link changes invoice-1.txt to invoice-2.txt and reads Ben Ortiz's invoice, with his name, date and total. They can also keep an old link working forever by typing a bigger exp.

A signed link: exp is the second (in Unix time) when the link stops working, ten minutes after it was made. sig is an HMAC of the name and the expiry, made with LINK_KEY, a key only the server has. The starting code already has sign and make_link. Change one character of what was signed and the signature comes out completely different. Without the key, nobody can work out the new one:

sign("report.pdf", 1800003600)   # signs the text "report.pdf:1800003600"
sign("salary.pdf", 1800003600)   # a completely different signature

To check a link, sign the name and exp from the request again and compare the result with sig using hmac.compare_digest. Only once they match can you trust exp and compare it with the clock. To read a number from the query, pass type=int. For /orders?page=2, request.args.get("page", 1, type=int) gives the number 2, and it gives 1 when page is missing or isn't a number.

The check sets the server's clock for each request, and now() reads it. Ana's link is made at 1800000000. The requests run at 1800000300 unless marked:

GET /files/invoice-1.txt?exp=1800000600&sig=<sig>   →  200  Invoice for order 1 …
GET /files/invoice-2.txt?exp=1800000600&sig=<sig>   →  403  {"error": "Bad link"}
GET /files/invoice-1.txt?exp=1900000000&sig=<sig>   →  403  {"error": "Bad link"}
GET /files/invoice-2.txt                            →  403  {"error": "Bad link"}
at 1800000600:
GET /files/invoice-1.txt?exp=1800000600&sig=<sig>   →  403  {"error": "Link expired"}
at 1800000599, Ben's own link:
GET /files/invoice-2.txt?exp=1800000600&sig=<sig2>  →  200  Invoice for order 2 …

Your task: in download, read exp from the query as a whole number (0 when it's missing) and sig ("" when it's missing). Answer 403 with {"error": "Bad link"} when sig isn't the signature sign makes for name and exp. Then answer 403 with {"error": "Link expired"} once now() has reached exp. Otherwise the file is sent as before.


Assignment
Follow the Coding Tutorial to check a download link's signature and expiry before download sends the invoice.


Hint
Compare with hmac.compare_digest, not ==, and check the signature first: until it matches, exp is just a number the visitor typed. Use >= so the link stops working at the second exp itself.


STEP 1 OF 6
    Ctrl + Enter to check

    Secx Signed Urls in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free