Contextual Encoding
The other common mitigation technique is to consider all user given data as textual data and not HTML content, even if it is an HTML content. This can be done performing HTML entity encoding on user data. Encoding <h1>test</h1> may get converted to <pre><test> test </></pre> The browser will then parse this correctly and render <h1>test</h1> as text instead of rendering it as h1 HTML tag.
Advantages:
If done correctly, contextual encoding eliminates XSS risk completely.
Disadvantages:
It treats all user data as unsafe. Thus, irrespective of the user data being safe or unsafe, all HTML content will be encoded and will be rendered as plain text.
Cross Site Scripting (XSS) Prevention Techniques
XSS or Cross-Site Scripting is a web application vulnerability that allows an attacker to inject vulnerable JavaScript content into a website. An attacker exploits this by injecting on websites that doesn’t or poorly sanitizes user-controlled content. By injecting vulnerable content a user can perform (but not limited to),
- Cookie Stealing.
- Defacing a website.
- Bypassing CSRF Protection etc.,
There are multiple ways by which a web application can protect itself from Cross-Site Scripting issues. Some of them include,
- Blacklist filtering.
- Whitelist filtering.
- Contextual Encoding.
- Input Validation.
- Content Security Policy.