Start learning free

LESSON 37 OF 56 · SECURITY: SECURE THE WEB APP

Data in a <script> Tag in Python

Practice

A page often hands data to its JavaScript as JSON inside a <script> tag. This product page does it with json.dumps. The catch: before any JavaScript runs, the browser's HTML reader cuts the script out of the page. It ends the script at the first </script> it meets, even one inside a JSON string.

Here is the same trap on another page, a note handed to a script:

note = {"text": "I love </script> tags"}
page = "<script>const note = " + json.dumps(note) + ";</script>"
# <script>const note = {"text": "I love </script> tags"};</script>
# the HTML reader ends the script at the first </script>, in the middle of the string

So a product named </script><script>alert(document.cookie)</script> ends the shop's script and starts a new one. The attacker's script then runs on the product page in every visitor's browser, where it can read the visitor's cookies and act as them. html.escape is no help here: inside a script, &lt; is never turned back into <, so JavaScript would get the wrong name.

The fix uses JSON's own escapes. In a JSON or JavaScript string, \u003c means <, \u003e means > and \u0026 means &. JavaScript reads the very same characters, but the HTML reader sees no <, so it finds no tag. Python's replace swaps every copy of one piece of text for another: "a-b-c".replace("-", "+") gives "a+b+c".

GET /products/1  →  200  <h1>Mug</h1><script>const product = {"id": 1, "name": "Mug", "price": 12};</script>
POST /products  {"name": "Salt & Pepper <Set>", "price": 14}  →  201  {"id": 9, "name": "Salt & Pepper <Set>", "price": 14}
GET /products/9  →  200  <h1>Salt &amp; Pepper &lt;Set&gt;</h1><script>const product = {"id": 9, "name": "Salt \u0026 Pepper \u003cSet\u003e", "price": 14};</script>
POST /products  {"name": "</script><script>alert(document.cookie)</script>", "price": 5}  →  201  {"id": 10, …}
GET /products/10  →  200  <h1>&lt;/script&gt;…</h1><script>const product = {"id": 10, "name": "\u003c/script\u003e\u003cscript\u003ealert(document.cookie)\u003c/script\u003e", "price": 5};</script>
GET /products/99  →  404  Product not found

Your task: in script_json, below the json.dumps line, replace every <, > and & in text with \u003c, \u003e and \u0026, one line for each.


Assignment
Follow the Coding Tutorial to escape <, > and & in the JSON before it goes into the script.


Hint
In a Python string, write the backslash twice: "\\u003c" is the six characters \u003c.


STEP 1 OF 3
    Ctrl + Enter to check

    Secx Json In Script 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