© Bohua Xu

Web Security

Feb 7, 2023 · 10min

Introduction

Web security is a critical aspect of modern web development. This guide covers the most common types of web attacks and provides detailed insights into protection mechanisms. We’ll explore various attack vectors including XSS, CSRF, SQL Injection, and DoS attacks.

Cross-Site Scripting (XSS)

Understanding XSS

Cross-Site Scripting (XSS) is one of the most prevalent web security vulnerabilities. It occurs when attackers inject malicious scripts into web pages viewed by other users. The fundamental issue stems from:

  • Blind trust in user-submitted content
  • Direct conversion of user input into DOM elements
  • Unsafe handling of dynamic content in server-side rendering

Types of XSS Attacks

1. Stored XSS

  • Most dangerous form of XSS
  • Malicious script is permanently stored on target servers
  • Affects any user accessing the infected page
  • Common targets: comment systems, user profiles, message boards
// Vulnerable code example
async function saveComment(content) {
    await db.comments.save({
        content: content  // Unsafe: No sanitization
    });
}

async function displayComment(comment) {
    element.innerHTML = comment;  // Unsafe: Direct DOM manipulation
}
// Vulnerable code example
async function saveComment(content) {
    await db.comments.save({
        content: content  // Unsafe: No sanitization
    });
}

async function displayComment(comment) {
    element.innerHTML = comment;  // Unsafe: Direct DOM manipulation
}

2. Reflected XSS

  • Non-persistent attack vector
  • Malicious script is reflected off web server
  • Usually delivered via URLs
  • Requires user interaction (clicking malicious link)

3. DOM-based XSS

  • Occurs entirely in the browser
  • No server-side involvement
  • Exploits client-side JavaScript vulnerabilities
  • Common sources: URL fragments, localStorage data
// Vulnerable DOM manipulation
const userInput = document.location.hash.substring(1);
document.getElementById("output").innerHTML = userInput; // Unsafe
// Vulnerable DOM manipulation
const userInput = document.location.hash.substring(1);
document.getElementById("output").innerHTML = userInput; // Unsafe

4. Mutation-based XSS

  • Exploits browser-specific DOM parsing behaviors
  • Leverages browser rendering optimizations
  • Varies across different browser engines
  • Particularly difficult to detect and prevent

XSS Prevention Strategies

  1. Input Validation

    • Validate all user input
    • Use allowlist approach
    • Implement strict type checking
  2. Output Encoding

    • HTML encode dynamic content
    • Context-specific encoding
    • Use modern framework escape mechanisms
  3. Content Security Policy (CSP)

    • Implement strict CSP headers
    • Disable inline scripts
    • Control resource loading

Cross-Site Request Forgery (CSRF)

Understanding CSRF

CSRF attacks exploit the trust that websites have in authenticated user browsers. These attacks:

  • Execute unauthorized actions
  • Leverage existing user authentication
  • Often target state-changing requests

CSRF Attack Vectors

  1. GET-based Attacks
<img src="http://bank.com/transfer?amount=1000&to=attacker" />
<img src="http://bank.com/transfer?amount=1000&to=attacker" />
  1. POST-based Attacks
<form id="csrf-form" action="http://bank.com/transfer" method="POST">
    <input type="hidden" name="amount" value="1000" />
    <input type="hidden" name="to" value="attacker" />
</form>
<script>document.getElementById("csrf-form").submit();</script>
<form id="csrf-form" action="http://bank.com/transfer" method="POST">
    <input type="hidden" name="amount" value="1000" />
    <input type="hidden" name="to" value="attacker" />
</form>
<script>document.getElementById("csrf-form").submit();</script>

CSRF Prevention

  1. CSRF Tokens

    • Implement unique tokens per session
    • Include tokens in forms and headers
    • Validate tokens server-side
  2. SameSite Cookies

    • Set appropriate SameSite attributes
    • Use Strict mode for sensitive operations
    • Implement Lax mode as fallback

SQL Injection

Understanding SQL Injection

SQL injection attacks occur when untrusted data is used to construct SQL queries. These attacks can:

  • Bypass authentication
  • Read sensitive data
  • Modify database content
  • Execute admin operations

Example Attack Vectors

-- Original query
SELECT * FROM users WHERE username = '$username' AND password = '$password'

-- Attack input
username: admin' --
password: anything

-- Resulting query
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'
-- Original query
SELECT * FROM users WHERE username = '$username' AND password = '$password'

-- Attack input
username: admin' --
password: anything

-- Resulting query
SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything'

Prevention Strategies

  1. Prepared Statements
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.execute(query, [username, password]);
const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
db.execute(query, [username, password]);
  1. ORM Usage
const user = await User.findOne({
    where: { username, password }
});
const user = await User.findOne({
    where: { username, password }
});

Denial of Service (DoS)

Types of DoS Attacks

1. Application-level DoS

  • Regular expression DoS (ReDoS)
  • Long-running queries
  • Resource exhaustion

2. Distributed DoS (DDoS)

  • Network bandwidth consumption
  • Service infrastructure overload
  • TCP/IP stack exploitation

Prevention Mechanisms

  1. Rate Limiting
const rateLimit = require('express-rate-limit');

app.use(rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
}));
const rateLimit = require('express-rate-limit');

app.use(rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
}));
  1. Resource Monitoring
  • Implement request timeouts
  • Monitor system resources
  • Set up alerting mechanisms

Man-in-the-Middle (MITM) Attacks

Understanding MITM

MITM attacks occur when attackers position themselves between client and server communications. These attacks can:

  • Intercept sensitive data
  • Modify transmitted information
  • Hijack sessions

Prevention Strategies

  1. SSL/TLS Implementation
  • Use strong SSL/TLS certificates
  • Implement HSTS
  • Enable secure cookie attributes
  1. Certificate Pinning
  • Implement public key pinning
  • Validate certificate chains
  • Monitor for certificate changes

Best Practices Summary

  1. Input Validation

    • Validate all user inputs
    • Use strong typing
    • Implement allowlists
  2. Output Encoding

    • Context-specific encoding
    • Framework security features
    • Content Security Policy
  3. Authentication & Authorization

    • Implement strong session management
    • Use secure password storage
    • Regular security audits
  4. Infrastructure Security

    • Keep systems updated
    • Regular security patches
    • Monitoring and logging

Conclusion

Web security is an ongoing process that requires constant vigilance and updates. By understanding these common attack vectors and implementing appropriate protection mechanisms, developers can significantly improve their applications’ security posture.

References

  1. OWASP Top 10
  2. Web Security Standards
  3. Modern Security Best Practices
CC BY-NC-SA 4.0 2021-PRESENT © Bohua Xu