Get a Pentest and security assessment of your IT network.

Cyber Security

Reflected XSS Prevention

TL;DR

Reflected Cross-Site Scripting (XSS) happens when malicious scripts are injected into a website through user input and immediately reflected back to the user. This guide shows how to block it on common web servers using input validation, output encoding, and HTTP security headers.

1. Understand Reflected XSS

Reflected XSS is often triggered by search boxes or URL parameters. The server takes your input, includes it in the HTML response without proper sanitisation, and sends it back to your browser. Your browser then executes the malicious script.

2. Input Validation

  1. Whitelist Approach: Define what characters are allowed. Reject anything else. This is the most secure method if you know exactly what input is expected.
    if (preg_match('/^[a-zA-Z0-9 ]+$/', $_GET['search'])) {
        $safeSearch = $_GET['search'];
    } else {
        $safeSearch = ''; // Or handle the invalid input appropriately
    }
    
  2. Blacklist Approach (Less Secure): Identify and remove dangerous characters or patterns. This is harder to get right as attackers can bypass filters.

    Avoid relying solely on blacklists.

  3. Length Restrictions: Limit the length of input fields to prevent excessively long scripts from being injected.

3. Output Encoding

Encoding converts potentially dangerous characters into a safe format that browsers will display as text, not execute as code.

  1. HTML Entity Encoding: Encode characters like <, >, ", and &.
    $safeOutput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
    
  2. JavaScript Encoding: Encode characters for safe use within JavaScript code. Use this when outputting data inside into various input fields.
  3. Test different encoding scenarios.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation