Prévenir XSS (Cross-Site Scripting) attacks
XSS injects malicious scripts en web pages. Apprendre entrée sanitization, sortie codage, et Content Sécurité Policy en prevent XSS.
- 1
XSS occurs when user input is rendered in HTML without escaping. Types: stored (persistent in database), reflected (in URL, immediate), DOM-based (client-side). Prevention: (1) Output encoding — escape <, >, &, ", ' based on context (HTML, attribute, JavaScript, URL). (2) Input validation/sanitization. (3) Content Security Policy. (4) HttpOnly cookies. Never insert untrusted data in dangerous locations (script, event handler, innerHTML).
- 2 Échappement HTML →
Échapper HTML special characters: < → <, > → >, & → &, " → ", ' → '. This prevents script injection in HTML body and attribute contexts. Use context-appropriate encoding: HTML-escape for body, attribute-escape for attributes, JavaScript-escape for script blocks, URL-encode for URLs.
- 3 Encodeur d'entités HTML →
Coder all characters as HTML entities for maximum safety. This is more aggressive than escaping only special characters — every character becomes &#xNN;. Use this for highly untrusted input or when you need to display code samples safely.
- 4
Defense in depth: (1) Output encoding (primary defense). (2) CSP: Content-Security-Policy: default-src 'self' — blocks inline scripts. (3) HttpOnly + Secure + SameSite cookies — prevents cookie theft via XSS. (4) Trusted Types (Chrome) — enforces type-safe DOM manipulation. (5) X-XSS-Protection: 0 (modern browsers rely on CSP, this header can introduce vulnerabilities).
Questions fréquentes
- What is the difference between escaping and sanitization?
- Escaping encodes special characters so they are displayed literally, not interpreted as markup (< → <). Sanitization removes or neutralizes dangerous content (strips <script> tags). Escaping is preferred — it preserves the content while making it safe. Sanitization (e.g., DOMPurify) is needed when you must allow some HTML (rich text editors).
- Is innerHTML ever safe?
- Only with fully sanitized input. innerHTML parses the string as HTML, executing any <script> tags. Use textContent (no HTML parsing) for plain text, or DOMPurify.sanitize() for rich text. Never use innerHTML with user input — even escaped input can be unsafe in certain contexts (e.g., in an attribute or event handler).