Audit: Unsanitized external input passed to a templating engine is prone to vulnerabilitiesJS-A1005
Using unsanitized external inputs with templating engines can lead to Local File Inclusion (LFI) or Remote Code Execution (RCE) attacks.
A specific scenario where such a vulnerability could occur is with the use of ExpressJS in conjunction with Handlebars templating engine.
When an externally supplied object is directly passed to the render
method to define local variables for the view, an attacker can add a property called as layout
to the object, which would allow them to load any local file specified by the layout
property.
A recommended way to avert this potential security risk would be to construct the local variables object for the view at the server side or sanitize the externally supplied value before using it with a templating engine.
Bad Practice
const express = require('express');
const app = express();
app.set('view engine', 'hbs');
app.post('/', (req, res) => {
const options = req.body.params;
res.render('home', options); // options can have the `layout` property
});
Recommended
const express = require('express');
const app = express();
app.set('view engine', 'hbs');
app.post('/', (req, res) => {
const options = req.body.params;
res.render('home', {
name: options.name, // construct the object with only the required properties
title: options.title
});
});