โœ… Secure XSS Examples - Protection Mechanisms

Learn how to properly protect against Cross-Site Scripting attacks

โœ… Security Features Implemented:

๐Ÿ”’ HTML Encoding Protection

Escape dangerous characters to prevent script execution:

// โœ… SECURE: HTML encoding function function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // โœ… SECURE: Use encoding before display const safeContent = escapeHtml(userInput); resultsContent.innerHTML = `

You searched for: ${safeContent}

`;

๐Ÿ›ก๏ธ Content Security Policy (CSP)

This page has CSP enabled to block inline scripts:

Current CSP: script-src 'self'; style-src 'self' 'unsafe-inline';

What this blocks:
  • โŒ Inline <script> tags
  • โŒ JavaScript: URLs
  • โŒ eval() and similar functions
  • โœ… External scripts from same origin

โœ… Input Validation

Validate input using whitelist approach:

// โœ… SECURE: Input validation with whitelist function validateUsername(username) { const allowedPattern = /^[a-zA-Z0-9_]{3,20}$/; return allowedPattern.test(username); } function validateEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }

๐Ÿ›ก๏ธ Safe DOM Manipulation

Use textContent instead of innerHTML for user content:

// โœ… SECURE: Use textContent for user content function displayComment() { const comment = document.getElementById('userComment').value; const contentDiv = document.getElementById('safeCommentContent'); // โœ… SAFE: textContent prevents script execution contentDiv.textContent = comment; // โŒ DANGEROUS: innerHTML would execute scripts // contentDiv.innerHTML = comment; }

๐Ÿงน DOMPurify Sanitization

Advanced HTML sanitization using DOMPurify library:

// โœ… SECURE: DOMPurify sanitization function sanitizeContent() { const dirtyContent = document.getElementById('richText').value; // โœ… SAFE: DOMPurify removes dangerous content const cleanContent = DOMPurify.sanitize(dirtyContent, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'], ALLOWED_ATTR: ['href'] }); document.getElementById('sanitizedContent').innerHTML = cleanContent; }

๐Ÿ“‹ Security Best Practices

โœ… Do's:

  • Always encode user input
  • Use textContent for user data
  • Implement CSP headers
  • Validate input with whitelist
  • Use DOMPurify for rich content
  • Keep libraries updated

โŒ Don'ts:

  • Never use innerHTML with user input
  • Don't trust client-side validation
  • Avoid eval() and similar functions
  • Don't disable CSP for convenience
  • Avoid blacklist approaches
  • Never store sensitive data in localStorage

๐Ÿ” Secure vs Vulnerable Comparison

See the difference between secure and vulnerable implementations:

๐Ÿ›ก๏ธ Implementation Checklist

Ensure these security measures are in place: