Cookies are vulnerable to various security attacks. Understanding these attack methods and protection measures is crucial for building secure web applications.
Common Cookie attack methods
- XSS (Cross-Site Scripting) stealing Cookies
- Attackers read document.cookie through injected malicious scripts
- Protection: Use HttpOnly flag
javascript// Insecure: can be stolen by XSS document.cookie = "token=abc123"; // Secure: HttpOnly prevents JavaScript access Set-Cookie: token=abc123; HttpOnly
- CSRF (Cross-Site Request Forgery)
- Attackers induce users to send cross-site requests, browser automatically carries Cookies
- Protection: Use SameSite attribute, CSRF Token
javascript// Protection example Set-Cookie: token=abc123; SameSite=Strict
- Man-in-the-middle attack
- Intercept Cookies in unencrypted connections
- Protection: Use Secure flag, enforce HTTPS
javascriptSet-Cookie: token=abc123; Secure
- Cookie injection
- Attackers forge or tamper with Cookie values
- Protection: Sign or encrypt Cookie values
Cookie security best practices
- Set security flags
javascript// Complete secure Cookie example Set-Cookie: sessionId=xyz123; HttpOnly; Secure; SameSite=Strict; Path=/; Domain=.example.com; Max-Age=3600
- Sensitive data handling
- Don't store plaintext passwords in Cookies
- Use encryption or signing to verify Cookie integrity
- Regularly rotate Session IDs
- Expiration time management
- Set reasonable expiration times
- Invalidate Cookies immediately after sensitive operations
- Use persistent Cookies when implementing "remember me" functionality
- Server-side validation
- Verify Cookie source and integrity
- Check for IP and User-Agent changes
- Implement rate limiting to prevent brute force attacks
Code example: secure Cookie setting
javascript// Node.js Express example res.cookie('token', encryptedToken, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', maxAge: 3600000, // 1 hour domain: '.example.com' });
GDPR and privacy compliance
- Obtain user consent before setting Cookies
- Provide clear Cookie policy explanations
- Implement Cookie consent banners