乐闻世界logo
搜索文章和话题

What are the security risks of Cookies? How to prevent Cookie-related attacks?

3月6日 21:40

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

  1. 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
  1. 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
  1. Man-in-the-middle attack
  • Intercept Cookies in unencrypted connections
  • Protection: Use Secure flag, enforce HTTPS
javascript
Set-Cookie: token=abc123; Secure
  1. Cookie injection
  • Attackers forge or tamper with Cookie values
  • Protection: Sign or encrypt Cookie values

Cookie security best practices

  1. Set security flags
javascript
// Complete secure Cookie example Set-Cookie: sessionId=xyz123; HttpOnly; Secure; SameSite=Strict; Path=/; Domain=.example.com; Max-Age=3600
  1. Sensitive data handling
  • Don't store plaintext passwords in Cookies
  • Use encryption or signing to verify Cookie integrity
  • Regularly rotate Session IDs
  1. Expiration time management
  • Set reasonable expiration times
  • Invalidate Cookies immediately after sensitive operations
  • Use persistent Cookies when implementing "remember me" functionality
  1. 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
标签:Cookie