Python, Jinja2 nl2br and security
Question: I'm using the [snippet from
Jinja2](http://jinja.pocoo.org/docs/dev/api/#custom-filters) for showing
multiline texts in html and I'm facing an issue :

If the user enters

    
    
    "Hello\nMy name is Jon"
    

the `nl2br` tag will render it as

    
    
    "Hello<br />My name is Jon"
    

with the br correctly interpreted (a break line).

Now this is good, but if the user enters

    
    
    "Hello<script>alert('hacked');</script>"
    

since I have to interpret the html to show the breaklines correctly, the
`<script>` will also be executed...

How can I avoid that?


Answer: The example code you've linked to _already_ escapes the input prior to
replacing newlines. Subsequently, the text is marked safe, because at that
point it is. The relevant code is:

    
    
    from jinja import escape, Markup
    value = escape(value)
    return Markup(value)
    

For the input `"Hello<script>alert('hacked');</script>"`, this results in
`"Hello &lt;script&gt;alert(&#39;hacked&#39;);&lt;/script&gt;"`. Notice that
the problematic syntax has been replaced with escape characters. When rendered
in the HTML document, there will be no script execution, just text.

