liveBook · Manning

Cross-site scripting attack

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Cross-site scripting is a web security attack in which injected script content executes in another user's browser.

A blog post may look like plain text to the person submitting it but contain JavaScript that runs when someone else opens the page. This is a cross-site scripting (XSS) attack: injected script is stored as user content, then executed in another user’s browser. section 11.10

A comment with a hidden script

A user enters ordinary text around `<script>malicious_function()</script>`. If the application saves that text and displays it in a post without preventing the script from running, a later visitor’s browser may execute it. section 11.10

Treat user-entered post and comment text differently from values supplied by the application. In a Jinja2 template, `| safe` prevents Jinja2 from translating potentially dangerous symbols. It is used for an application-supplied JSON value in a JavaScript block; applying the same treatment to user-supplied data could expose an XSS risk. section 6.4.4

For user-entered content, sanitize it before saving it. A form filter calls `bleach.clean()` on non-`None` input; fields such as a post’s `PageDownField` run that filter when the form is submitted, before the application reads the field data. The practical distinction is where the value came from: application-generated data in a template is not the same as text a visitor can submit. section 11.10 section 6.4.4

content = PageDownField(
    "Content",
    validators=[DataRequired()],
    filters=(remove_html_and_script_tags,),
    render_kw={"placeholder": " ", "tabindex": 2}
)

The post content field attaches the sanitizing function through its `filters` parameter, keeping the check on the form-input path. section 11.10

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Defines the attack through a stored-script scenario and shows a form-filter defense, without detailing browser execution internals.
Examples
Uses a blog post containing an embedded script and a post-content field configured with a sanitizing filter.
What it assumes
Assumes familiarity with Flask templates and form fields while defining the XSS risk through a concrete blog scenario.
What you can do after
Apply it via Bleach by filtering user-entered form text before it is saved.
How it connects
Connects user input, JavaScript, Jinja2 templates, form filters, and input sanitization.

Also explained in

Compare how 3 books explain cross-site scripting attack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.