Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django / Python: Convert Markdown to Secure HTML

I'm accepting Markdown and need to convert it to HTML to render securely in Django. Right now I'm accepting the form.cleaned_data and converting it to HTML with:

import markdown
html_body = markdown.markdown(body_markdown, safe_mode=True)
html_body = html_body.replace('[HTML_REMOVED]', '')
return html_body

In the template, I'm rendering it as :

{{ object.content|safe|capfirst }}

However if you post:

0;url=javascript:alert('hi');" http-equiv="refresh

The JS will render so XSS is possible.

like image 617
user1846171 Avatar asked Nov 22 '12 22:11

user1846171


1 Answers

django's built in safe template tag means that you are marking that variable as ok to output, i.e. you know that it's contents are safe:

safe: Marks a string as not requiring further HTML escaping prior to output.

Django by default escapes your template variables:

By default in Django, every template automatically escapes the output of every variable tag. Specifically, these five characters are escaped ...

but it won't strip the javascript away for you (it will just render it unusable), you need to do that manually with a template tag:

Strip javascript code before rendering in django templates

On the other hand, safe_mode on markdown strips any HTML in the text with [HTML REMOVED] as you've seen.

So removing safe should be enough to make it safe,

like image 68
Timmy O'Mahony Avatar answered Oct 18 '22 20:10

Timmy O'Mahony