Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

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:

  1. Search box: enter <a href="javascript:alert('Hacked!')">Click me!</a>; the result page shows a link that runs JavaScript.
  2. 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....
  3. 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.
  4. 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#

  1. Use .textContent instead 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;
    
  2. Input sanitization via regex (whitelist the allowed characters):
    // Remove all characters except letters, comma, and space
    let safe = userInput.replace(/[^A-Za-z, ]/g, "");
    
  3. 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()).
  • .textContent escapes all HTML; .innerHTML parses 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-pooper that protects the app against code injection.

Example#

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only