SecLab
Injection & Output EncodingwalkthroughDifficulty 3/526 min

Encoding for the output context

Objective: After this lesson you can say, for any insertion point in HTML, which encoding is needed and why.

V1CWE-79A05:2025xss
Step 1 of 5 · read6 min

One value, five contexts, five encodings

XSS was merged into A05 because it is injection — the same mechanism as SQL injection with a different interpreter. But one thing makes it harder than SQL injection in practice, and that is this lesson's subject: HTML is not one interpreter, it is five nested interpreters.

The same string, placed in five different spots on a page, needs five different treatments:

ContextExampleNeeds
Element body<div>HERE</div>HTML entity encoding
Attribute value<div title="HERE">HTML entity encoding and always quoted
Inside <script>var x = "HERE";JavaScript string encoding — HTML encoding here is wrong
URL value<a href="/go?u=HERE">URL encoding, plus a scheme check
Inside <style>color: HERE;CSS encoding

The most important point, and where a framework cannot save you: encoding for the wrong context both fails to protect and corrupts the data. HTML-encoding a string then placing it inside <script> yields &quot; sitting in JavaScript code — it does not stop </script> and it renders the string wrongly.

Two contexts deserve their own note, because they are the source of nearly all remaining XSS in modern applications:

(1) href and src. Encoding is not enough, because javascript:alert(1) contains no character that needs encoding. This context needs a scheme check: allow http, https, and perhaps mailto. This is the most common XSS in React — href={userUrl} is not protected by React.

(2) DOM sinks. innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, setTimeout with a string, and dangerouslySetInnerHTML/v-html. There is no correct encoding here — the data enters a fresh HTML parser, so it needs sanitising (DOMPurify) or a different approach.

View path

Comments

Join the discussion
Sign up to comment

Commenting needs an account with at least one completed lesson. That condition is what keeps this thread worth reading: every point belongs to someone who can be asked back, and reputation accrues over time.

Sign upSign in

You can still read every comment below without an account. Signing in brings you back to this exact spot, not to the top of the page.

Loading comments…