Cross-Site Scripting in NodeJS
Prevention
Apply the recommended security controls depending on the framework and template engine of choice.
EJS
EJS is a template engine supported by many NodeJS web frameworks, including Express.js.
It applies the encoding for the HTML context automatically to all of the output sourced from variables, but inserting untrusted input directly into JavaScript context must be avoided.
Context | Code | EJS Encoding mechanisms |
---|---|---|
HTML Code and Attribute | <?= user-controlled-variable ?> |
HTML Escaped Encode data for use in HTML using HTML entity encoding |
JavaScript | <script>var id = "<?= user-controlled-variable ?>";</script> |
HTML Escaped and JavaScript escaped if between quotes Encode data for insertion inside a data value or function argument in JavaScript. |
References
OWASP - Cross-Site Scripting (XSS) OWASP - Code Review Guide OWASP - Cross-Site Scripting Prevention Cheat Sheet EJS