Question

I have an idea to put the templates in the database, and offer the possibility for the designer to edit the templates direct from CMS panel. But what is haunted me is the security question. How could it be any secure if we have ability to put python commands directly in the templates. If I have something like this in a mako template:

<%!
import os

os.system('rm /var/www/env/harmless.txt')
%>

it will performed successful and harmless.txt will be removed. Should I find for another template engine except Mako or could I somehow configure Mako to prevent harmful code injection? On the other hand, some python commands incredibly helpful used in templates, inline if statement for example.

Was it helpful?

Solution

If they have their own separated instance of a CMS it doesn't matter like Loic points out. But if they are in some shared environment it is best to use another template engine. The question Untrusted templates in Python - what is a safe library to use? recommends Django templates and Jinja2.

OTHER TIPS

There is still a possibility to do what you want. The mako engine lets you add a preprocessor to the template. I can't say for sure as I can test at the moment, but you could have something like this:

Here: http://docs.makotemplates.org/en/latest/usage.html#mako.template.Template.params.preprocessor

def removeImports(source):
    # remove whatever you don't want inside the template
    return new_source

tpl = Template(...., preprocessor=removeImports)

If you're using a framework like pyramid you can make it a new renderer to do that for you on all templates.

As a security concern, if you want to got that way as Mako is a terribly good engine in my own opinion. You should do a good set of test case on your preprocessor. I'm pretty sure that imports can be achieved inside inline python <% %>. Actually imports can be achieved almost anywhere inside the template as you can use inline python almost everywhere.

So if you're conerned about running python in a template, you can consider other templates such as Chameleon, Jinja2 ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top