Cross-site scripting (XSS) is a type of attack in which a malicious agent manages to inject client-side JavaScript into your website, so that it runs in the trusted environment of your users' browsers.
The cleanest way to prevent XSS attacks is to escape untrusted data at the point of injection. That means at the point where it's actually being injected into the HTML.
Use <%= %>
to HTML-encode data:
<h3 is="welcome-msg">Hello <%= me.username %>!</h3>
<h4><%= owner.username %>'s projects:</h4>
<ul><% _.each(projects, function (project) { %>
<li>
<a href="/<%= owner.username %>/<%= project.slug %>"><%= project.friendlyName %></a>
</li>
<% }); %></ul>
Use the exposeLocalsToBrowser
partial to safely expose some or all of your view locals to client-side JavaScript:
<%- exposeLocalsToBrowser(); %>
<script>
console.log(window.SAILS_LOCALS);
// {
// me: {
// username: 'eleven',
// memberSince: '1982-08-01T05:00:00.000Z'
// },
// owner: {
// username: 'joyce',
// memberSince: '1987-11-03T05:00:00.000Z'
// },
// projects: [
// {
// slug: 'my-neat-stuff-n-things',
// friendlyName: 'My neat stuff & things',
// description: 'Yet another project.'
// },
// {
// slug: 'kind-of-neat-stuff-but-not-that-great',
// friendlyName: 'Kind of neat stuff, but not that great...',
// description: 'I am so sick and tired of these project. <script>alert(\'attack\');</script>'
// }
// ],
// _csrf: 'oon95Uac-wKfWQKC5pHx1rP3HsiN9tjqGMyE'
// }
</script>
Note that when you use this strategy, the strings in your view locals are no longer HTML unescaped after being exposed to client-side JavaScript. That's because you'll want to escape them again when you stick them in the DOM. If you always escape at the point of injection, this stuff is a lot easier to keep track of. This way, you know you can safely escape any string you inject into the DOM from your client-side JavaScript. (More on that below.)
A lot of XSS prevention is about what you do in your client-side code. Here are a few examples:
Use <%- %>
to HTML-encode data:
<div data-template-id="welcome-box">
<h3 is="welcome-msg">Hello <%- me.username %>!</h3>
</div>
Use something like $(...).text()
to HTML-encode data:
var $welcomeMsg = $('#signup').find('[is="welcome-msg"]');
welcomeMsg.text('Hello, '+window.SAILS_LOCALS.me.username+'!');
// Avoid using `$(...).html()` to inject untrusted data.
// Even if you know an XSS is not possible under particular circumstances,
// accidental escaping issues can cause really, really annoying client-side bugs.
As you've probably figured out, the example above assumes you are using jQuery, but the same concepts apply regardless of what front-end library you are using.
- The examples above assume you are using the default view engine (EJS) and client-side JST/Lodash templates from the default asset pipeline.