Files
vault/Career/Security/Output Encoding.md
Zaine 5d3ed14275
Some checks failed
Build Quartz Notes / build (push) Failing after 2m40s
updates
2026-06-04 14:47:44 +01:00

2.7 KiB
Executable File
Raw Blame History

note type, date, done, link
note type date done link
security
theory
2026-06-03 true https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

In order for an XSS attack to be successful, an attacker must be able to insert and execute malicious content in a webpage. Thus, all variables in a web application needs to be protected. Ensuring that all variables go through validation and are then escaped or sanitized is known as perfect injection resistance. Any variable that does not go through this process is a potential weakness. Frameworks make it easy to ensure variables are correctly validated and escaped or sanitised.

However, no framework is perfect and security gaps still exist in popular frameworks like React and Angular. Output encoding and HTML sanitization help address those gaps.

Output encoding

When you want data to be safely displayed, just as a user types it in, output encoding is recommended. Variables should not be interpreted as code instead of text. There are different types of output encoding mechanisms used.

Output Encoding for HTML Contexts.

“HTML Context” refers to inserting a variable between two basic HTML tags like a <div> or <b>. For example:

<div> $varUnsafe </div>

An attacker could modify data that is rendered as $varUnsafe. This could lead to an attack being added to a webpage. For example:

<div> <script>alert`1`</script> </div> // Example Attack

Output Encoding for “JavaScript Contexts”

“JavaScript Contexts” refers to the situation where variables are placed into inline JavaScript and then embedded in an HTML document. This situation commonly occurs in programs that heavily use custom JavaScript that is embedded in their web pages.

However, the only safe location for placing variables in JavaScript is inside a “quoted data value”. All other contexts are unsafe and you should not place variable data in them.

Examples of “Quoted Data Values”

<script>alert('$varUnsafe)</script> <script>x=$varUnsafe</script> <div onmouseover="'$varUnsafe'"</div>

Encode all characters using the \xHH format. Encoding libraries often have a EncodeForJavaScript or similar to support this function.

Please look at the OWASP Java Encoder JavaScript encoding examples for examples of proper JavaScript use that requires minimal encoding.

For JSON, verify that the Content-Type header is application/json and not text/html to prevent XSS.

Example

!Pasted image 20260603202316.png