Back to Blog
Web Security12 min14,337 views

Cross-Site Scripting (XSS): Attack Techniques and Prevention

?

Cross-Site Scripting (XSS) Attacks

XSS is a client-side code injection attack where attackers inject malicious scripts into web pages viewed by other users.

Types of XSS

1. Reflected XSS

The malicious script comes from the current HTTP request.


Search results for:

2. Stored XSS

The malicious script is permanently stored on the target server.

// Comment saved to database containing:

3. DOM-based XSS

The vulnerability exists in client-side JavaScript.

// Vulnerable code
document.getElementById('output').innerHTML = location.hash.substring(1);
// URL: http://site.com/#

XSS Payloads














Finding XSS

  • Test all input fields

  • Check URL parameters

  • Look at reflected content

  • Test with special characters: <>"'/

Prevention

1. Output Encoding


function htmlEncode(str) {
    return str.replace(/&/g, '&')
              .replace(//g, '>')
              .replace(/"/g, '"');
}

2. Content Security Policy (CSP)


Content-Security-Policy: default-src 'self'; script-src 'self'

3. HttpOnly Cookies


Set-Cookie: session=abc123; HttpOnly; Secure

4. Input Validation

Conclusion

XSS is everywhere. Always encode output and never trust user input!