Flake8 plugin to check for unsafe MarkupSafe usage in your code to prevent XSS vulnerabilities.
$ pip3 install https://github.com/vmagamedov/flake8-markupsafe/archive/master.zip
$ flake8 --show-source ./examples
./examples/view.py:14:12: MS001 Markup is used in a dangerous way
return Markup("<script>{}</script>".format(value))
^
./examples/view.py:18:12: MS001 Markup is used in a dangerous way
return Markup(gettext("<script>{}</script>".format(value)))
^
This plugin also checks for webhelpers.html.literal()
usages. But there is
a known issue that SQLAlchemy has it's own sqlalchemy.literal()
, this may
cause false positives.
This plugin has an exception for a functions called _
and *gettext
. You
can pass result of these functions to the Markup
, but their arguments should
be also safe.
Markup(_("<script>{}</script>")).format(code)
Note: Mako should be installed to use this feature.
$ python -m flake8_markupsafe.mako --show-source ./examples
examples/view.mako:3
unsafe = Markup('<script>{}</script>'.format(value))
examples/view.mako:8
<div class="unsafe">${Markup('<script>{}</script>'.format(value))}</div>
Found 2 errors in 1 file
Here is how to ignore errors in a Python code:
title = Markup(page.title) # noqa: MS001
Here is how to ignore errors in a Mako templates:
<%
title = Markup(page.title) # noqa
%>
<script type="text/javascript">
${Markup(application_js)} <%doc>noqa</%doc>
</script>
But it is better to pass into templates already wrapped into Markup
objects.