5 Min

Cross Site Scripting

Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious code (usually JavaScript) into web pages that is then executed by other users in the context of that website. XSS becomes possible when a website inserts unsafe user input into the HTML output without sufficient validation or filtering.

How does XSS work?

XSS is based on an application embedding uncontrolled code or malicious scripts in its output. When this malicious code is executed in another user’s browser, it can perform a variety of actions, such as stealing data, reading cookies, or performing other malicious activities in the context of the web page.

Three main types of XSS:

  1. Stored XSS (persistent XSS):
    • The malicious code is stored permanently in the database or backend of the web application (e.g. through a form).
    • When another user visits the page, the malicious code is loaded from the database and executed in the victim’s browser.
    • Example: A user posts a comment on a forum with malicious JavaScript. Other users who read the comment unknowingly execute this script.
  2. Reflected XSS:
    • The malicious code is not saved, but is immediately sent to the server via a crafted link or URL and then sent back to the browser without the server filtering it.
    • The attack is usually carried out via crafted links. When the user clicks this link, the malicious script is executed in their browser.
    • Example: A user clicks a link like http://example.com/search?query=<script>alert('Hacked')</script>.
  3. DOM-based XSS:
    • Here the malicious script is executed directly in the browser without going through the server. This happens when the client-side JavaScript logic interacts with the DOM elements in an unsafe way.
    • Example: When the JavaScript application inserts unsafe user input into the DOM, such as through innerHTML, without properly filtering the input.

Where can XSS cause specific damage?

XSS can cause significant damage in many places in a web application:

  1. Theft of session cookies:
    • An attacker can use an XSS script to steal session cookies from users and thus take over their session.
    • Example: The attacker reads the cookie using JavaScript (document.cookie) and sends it to his own server.
  2. Identity theft and account takeover:
    • XSS allows an attacker to access user data or even take over user accounts by injecting malicious code and reading user data.
  3. Phishing attacks:
    • Attackers can place fake login forms or other phishing pages on legitimate websites to steal usernames, passwords and other sensitive information.
  4. Website content devastation:
    • The attacker can alter the content of a website, display pop-ups, trigger redirects or make the site completely unusable.
  5. Malware distribution:
    • Malicious scripts can be used to trick users into downloading malware by automatically downloading malicious files from third-party servers.
  6. API abuse:
    • If a website uses APIs such as Google Maps, payment gateways or social networks, XSS can manipulate these APIs and perform unauthorized actions on behalf of the user.

How do I protect my users from XSS?

To prevent XSS as a web developer, a variety of security measures are necessary. The most important methods of prevention are:

1. Input validation and filtering

  • Input validation: Make sure that all user input is checked and only the expected values ​​are allowed (e.g. no HTML tags in text fields).
  • Whitelist instead of blacklist: Use a whitelist of allowed inputs instead of trying to block only malicious inputs.
  • Filtering: All user input should be checked for unwanted characters and filtered if necessary. This is especially important for characters like <, >, &, " and ', which have a special meaning in HTML and JavaScript.

2. Escape output (output encoding)

  • When user input is returned on the web page (e.g. in a comment), it should always be “escaped” in a safe form before being inserted into the HTML.
  • For HTML, the special characters &, <, >, ", ' should be replaced with HTML entities:
  • < becomes &lt;
  • > becomes &gt;
  • & becomes &amp;
  • ", ' becomes &quot; or &#039;

  • Example in JavaScript:
function escapeHTML(text) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(text));
  return div.innerHTML;
}

3. Using security headers

  • Content Security Policy (CSP): CSP is a security mechanism that determines which resources (such as scripts, images, stylesheets) can be loaded and executed on a web page.
  • A good CSP prevents inline scripts (e.g. <script> tags or event handlers such as onclick) and unsafe sources such as eval() or data URLs from being executed.
  • Example of a CSP policy:
    Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none';
    

4. Avoiding dangerous functions

  • Do not use unsafe functions such as innerHTML, document.write, or eval() to insert user input into the DOM, as these functions can execute unsafe code directly.
  • Instead, use safe methods such as textContent or setAttribute() that do not interpret the input as HTML.

  • Example of safe DOM manipulation:
    const div = document.getElementById('output');
    div.textContent = 'This is safe text'; // Safe method instead of innerHTML
    

5. Using safe libraries

  • Many modern frameworks and libraries such as React, Vue.js or Angular offer built-in protection mechanisms against XSS attacks. These frameworks automatically “escape” user input, making XSS much harder to implement.

  • Example in React:

    const safeText = "<script>alert('XSS')</script>";
    return <div>{safeText}</div>; // React automatically escapes the script tag
    
  • Use Secure, HttpOnly and SameSite flags for cookies to protect them from XSS:
  • Secure: Cookie is only transmitted over HTTPS.
  • HttpOnly: Cookie cannot be read by JavaScript (protects against theft by XSS).
  • SameSite: Prevents sending the cookie in cross-site requests (protects against CSRF).

7. Regular security testing

  • Use security tools to perform XSS tests. These include tools such as OWASP ZAP or Burp Suite, which can uncover vulnerabilities in web applications.
  • Regular security audits, especially after changes in the frontend code, are essential to identify new attack vectors.

Conclusion

XSS is one of the most common and dangerous security vulnerabilities on the web. As a web developer, it is crucial to carefully validate and escape user input to prevent malicious code from being executed. By using modern web techniques such as content security policies (CSP), secure DOM manipulation functions and frameworks with built-in security mechanisms, the risk of XSS can be significantly minimized.

Updated: