Code Injection Protection
Also Code Injection · Cross-Site Scripting · XSS
Code injection (cross-site scripting, XSS) is an exploit in which attacker-controlled input is inserted into a web page as HTML/JavaScript and executed in the victim's browser; protection means never inserting untrusted content as HTML, i.e. writing it as text or sanitizing it first.
Know these firstDOM Manipulation
Properties#
Attack vectors#
If user input is inserted via .innerHTML (or jQuery .html()):
// UNSAFE: attacker can inject tags or event handlers
element.innerHTML = userInput;
the input is parsed as HTML. Examples from the lecture and beyond:
- Search box: enter
<a href="javascript:alert('Hacked!')">Click me!</a>; the result page shows a link that runs JavaScript. - Link in a mail:
...index.html?user=guest<script>alert("Ha!")</script>. The<script>part can be made less suspicious by URL-encoding it:...index.html?user=guest%3C%73%63%72%69%70.... - Forum post:
I have a question<script>…sends user info by mail to evil person…</script>. The script does not show on the page but is executed by every client viewing the post; it could, e.g., open a Gmail tab and read private mail. - Event handler:
<img src=x onerror="alert('hacked')">runs its handler as soon as the image fails to load.
It is one of three kinds of web-app vulnerabilities, next to access to private data (HTTP Server) and leaking trusted information to untrusted sites (Same-Origin Policy); overview: the OWASP Top Ten.
Prevention methods#
- Use
.textContentinstead of.innerHTML(jQuery:.text()instead of.html()). The content is treated as plain text:<script>becomes visible text, not executed code.// SAFE document.querySelector("#result").textContent = userInput; - Input sanitization via regex (whitelist the allowed characters):
// Remove all characters except letters, comma, and space let safe = userInput.replace(/[^A-Za-z, ]/g, ""); - General principle: never trust user input; always escape or sanitize before inserting into the DOM; prefer text-only insertion (
.textContent,.text()) over HTML insertion (.innerHTML,.html()).
.textContentescapes all HTML;.innerHTMLparses the string as HTML, so injected markup and event handlers become live.- Server-side templates need the same care: a server that substitutes the raw query into
%QUERY%/%RESULT%(HTML Form > Template variables) injects it into the page. Sheet 10 asks for an option--party-pooperthat protects the app against code injection.
Example#
Sources#
- Slides 10, p. 17 (vulnerabilities, OWASP), pp. 19–20 (code injection)
- DBIS_VL10 > Motivation, DBIS_VL10 > Code injection, DBIS_VL10 > Communicating with other machines via
fetch(theinnerHTMLhole insearch.js) - Sheet 10, Exercise 1.5
- DBIS Exam WS1920 (not published) T3.2