Introducing Qwiet AI AutoFix! Reduce the time to secure code by 95% Read More

# Template Injection

In web design, a *template* is an HTML-like file interspersed with programmatic instructions to be interpreted by the
web-server or JavaScript code in the browser at runtime. A template is a *static* file used to generate HTML by
interpolating *dynamic* content retrieved from a database or pulled from HTTP. A **template injection** vulnerability
occurs when the dynamic content is treated by the template engine as code to be executed rather data to be interpolated.
This will allow an attacker to execute malicious code on your server or in a victim’s browser.

=== Template Injection in Angular

Angular apps consist of a hierarchical set of components that encapsulate application logic and state information. Each
component is rendered in the browser using a template that describes the HTML to output for the given state of the
component. Angular templates will safely interpolate state using the `{{` and `}}` delimiters, and allow components
to listen for user interactions using event handlers.

A template is attached to a component using the `@Component` decorator. Templates can be specified with the
`templateUrl` option, which supplies the relative or absolute path of the corresponding template file:

“`typescript@Component({
selector: ‘app-login’,
templateUrl: ‘./login.component.html’,
styleUrls: [‘./login.component.css’]
})
export class LoginComponent {}
“`Templates can also be provided as inline strings using the `template` option:“`typescript
@Component({
selector: ‘app-login’,
template: ‘<form (ngSubmit)=”onSubmit()”>’ +
‘<input type=”text” placeholder=”Username” [(ngModel)]=”username” />’ +
‘<input type=”password” placeholder=”Password” [(ngModel)]=”password” />’ +
‘<button type=”submit”>Login</button>’ +
‘</form>’,
styleUrls: [‘./login.component.css’]
})
export class LoginComponent {}
“`

Template inject vulnerabilities occur in Angular when untrusted input is passed to the `template` option – in
particular, when the template string is generated by string concatenation:

“`typescript
@Component({
selector: ‘app-header’,
template: ‘<h1>’ + (window.location.hash || ‘Home’) + ‘</h1>’
})
export class HeaderComponent {}
“`

Avoid dynamically generated templates in this fashion. Instead, load the state into your component, and use Angular’s
built-in interpolation logic to safely escape any untrusted content:

“`typescript@Component({
selector: ‘app-header’,
template: ‘<h1>{{ title }}</h1>’
})
export class HeaderComponent {
title = ”ngOnInit() {
this.title = window.location.hash || ‘Home’;
}
}
“`

=== Template Injection in React

Most React developers use JSX to make HTML tags native in JavaScript syntax. JSX makes it easy to dynamically render
page elements that correspond to data loaded from the server.

Providing all React components are defined in JSX when the code is transpiled to JavaScript during the build process,
you are generally safe from template injection attacks. However, React components *can* be generated directly from the
low-level APIs at runtime using the `React.createElement(…)` function. If you invoke this method using untrusted
content, you are vulnerable to template injection attacks:

“`jsxconst tagName = ‘div’
const attributes = { class: ‘page-contents’ }
const textContent = ‘Tag contents go here’/**
* Dynamically create a React component, in this case:
*
* <div class=”page-contents”>Tag contents go here</div>
*
* If any of the arguments come from an untrusted source an attacker can inject malicious content.
*/
React.createElement(
tagName,
attributes,
textContent
)
“`

Attackers can also control the attributes and contents of HTML tags if you invoke the `dangerouslySetInnerHTML`
function on a React component:

“`jsx
/**
* React allows you to write raw HTML from a string, but discourages it – hence the function name
* “dangerouslySetInnerHTML(…)”! If the inputs to this function are taken from an untrusted source
* you are vulnerable to template injection.
*/
const html = {
__html: ‘<div class=”page-contents”>Tag contents go here</div>’
}
<div dangerouslySetInnerHTML={html} />
“`

The final source of template injection vulnerabilities in React is `href` attributes. If the `href` attribute of a link
or import statements is dynamically generated from untrusted content, an attacker can inject JavaScript by supplying a
URL with a `javascript:` prefix:

“`jsx/**
* Dynamically setting the `href` of a link can permit cross-site scripting attacks if the
* URL is taken from an untrusted source.
*/
const link = “javascript:alert(‘Oh no’)”// An user clicking on this this component will execute the attacker’s JavaScript.
const button = <a href={link}>Click here</a>
“`

## Mitigation

* Avoid using the `React.createElement(…)` function directly.
* Don’t use the `dangerouslySetInnerHTML` function on React components.
* Don’t dynamically generate `href` attributes from untrusted content.

## CWEs

* [CWE-94](https://cwe.mitre.org/data/definitions/94.html)

About ShiftLeft

ShiftLeft empowers developers and AppSec teams to dramatically reduce risk by quickly finding and fixing the vulnerabilities most likely to reach their applications and ignoring reported vulnerabilities that pose little risk. Industry-leading accuracy allows developers to focus on security fixes that matter and improve code velocity while enabling AppSec engineers to shift security left.

A unified code security platform, ShiftLeft CORE scans for attack context across custom code, APIs, OSS, containers, internal microservices, and first-party business logic by combining results of the company’s and Intelligent Software Composition Analysis (SCA). Using its unique graph database that combines code attributes and analyzes actual attack paths based on real application architecture, ShiftLeft then provides detailed guidance on risk remediation within existing development workflows and tooling. Teams that use ShiftLeft ship more secure code, faster. Backed by SYN Ventures, Bain Capital Ventures, Blackstone, Mayfield, Thomvest Ventures, and SineWave Ventures, ShiftLeft is based in Santa Clara, California. For information, visit: www.shiftleft.io.

Share

See for yourself – run a scan on your code right now