Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Security concerns with Mustache html templating

I have a usecase where the contents of the mustache HTML template could potentially come from the application/end-user (i.e. The content of the script tag in the below code snippet.)

<script id="template" type="x-tmpl-mustache">
  Hello {{ name }}!
</script>

As this could potentially lead to execution of malicious code, I'm doing

  1. Allowing only a subset of HTML tags and attributes to be added in the template (inside the script tag)
  2. Allowing only HTML escaped variables i.e. only {{name}} is allowed and not {{{name}}}.

Is there anything further that needs to be considered for security of the application?

like image 533
Arjun Avatar asked Oct 22 '15 17:10

Arjun


1 Answers

I think it's not a "moustache" problem if we follow the philosophy "small, sharp tools". Then before mapping an unsecure data (third party JSON) to template you are to validate the data with other tools.

The simplest approach to start with is to replace string fields, contaning unsecure data.

function clearJson(userStringData){

  return JSON.parse(userStringData, function(k,v) { 
        // string values containg something like
        // html tags or js block braces will not pass
        return String(v).match('[<>{}]') ? 'UNSAFE' : v;
  });
}

The field of code injection is too wide to have a short answer on your question. You may apply any approach which is advanced enough for your application: define data formats the application expects from user and then in runtime remove incoming suspicious data not matching these formats.

like image 74
diziaq Avatar answered Sep 30 '22 06:09

diziaq