~ubuntu-branches/debian/sid/bandit/sid

« back to all changes in this revision

Viewing changes to docs/jinja2.md

  • Committer: Package Import Robot
  • Author(s): Dave Walker (Daviey)
  • Date: 2015-07-22 09:01:39 UTC
  • Revision ID: package-import@ubuntu.com-20150722090139-fl0nluy0x8m9ctx4
Tags: upstream-0.12.0
ImportĀ upstreamĀ versionĀ 0.12.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
jinja2 templates
 
2
=====================
 
3
From the doc page, 'Jinja2 is a modern and designer-friendly templating language
 
4
for Python." Jinja2 is the templating engine used in the common web framework
 
5
Flask.
 
6
 
 
7
The [Jinja2 docs](http://jinja.pocoo.org/docs/dev/api/#autoescaping) on
 
8
autoescaping indirectly state that the default behavior is autoescape=False:
 
9
    "As of Jinja 2.4 the preferred way to do autoescaping is to **enable** the
 
10
    Autoescape Extension and to configure a sensible default for autoescaping."
 
11
 
 
12
### Incorrect
 
13
With autoescape=False, the default behavior, we can see XSS is trivial if a user
 
14
controlled value is ever rendered in a jinja2 template:
 
15
```shell
 
16
>>> from jinja2 import Template
 
17
>>> t = Template("Hello darkness, my old {{ friend }}")
 
18
>>> t.render(friend="friend")
 
19
    u'Hello darkness, my old friend'
 
20
>>> t.render(friend="<h1>enemy</h1>")
 
21
    u'Hello darkness, my old <h1>enemy</h1>'
 
22
```
 
23
 
 
24
### Correct
 
25
The correct solution is to use autoescape=True, as we can see below:
 
26
```shell
 
27
>>> from jinja2 import Template
 
28
>>> t = Template("Hello darkness, my old {{ friend }}", autoescape=True)
 
29
>>> t.render(friend="friend")
 
30
    u'Hello darkness, my old friend'
 
31
>>> t.render(friend="<h1>enemy</h1>")
 
32
    u'Hello darkness, my old &lt;h1&gt;enemy&lt;/h1&gt;'
 
33
>>>
 
34
```
 
35
 
 
36
## Consequences
 
37
* HTML/Javascript injection, known as XSS attacks.
 
38
 
 
39
## References
 
40
* https://realpython.com/blog/python/primer-on-jinja-templating/
 
41
* http://jinja.pocoo.org/docs/dev/api/#autoescaping