OWASP Top 10 Explained with Practical Examples
You've probably heard of the OWASP Top 10, but do you know how each vulnerability looks in real code? Many developers can list the categories but struggle to spot them in their own projects. This article walks through each OWASP Top 10 item with concrete examples and practical fixes, so you can recognize and prevent these issues in your applications.
1. Broken Access Control
Broken access control occurs when users can act outside their intended permissions. For example, a user might access another user's data by changing an ID in the URL.
// Vulnerable: No check if the requested order belongs to the user
app.get('/orders/:id', (req, res) => {
const order = db.getOrder(req.params.id);
res.json(order);
});
// Fixed: Verify ownership
app.get('/orders/:id', (req, res) => {
const order = db.getOrder(req.params.id);
if (order.userId !== req.user.id) {
return res.status(403).send('Forbidden');
}
res.json(order);
});
Prevention: Enforce access control checks on the server side, deny by default, and use role-based access control (RBAC).
2. Cryptographic Failures
This category includes failures related to protecting sensitive data, such as storing passwords in plaintext or using weak hashing algorithms.
// Vulnerable: Storing passwords with MD5
const hash = crypto.createHash('md5').update(password).digest('hex');
// Fixed: Use bcrypt with a salt
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);
Prevention: Use strong, adaptive hashing algorithms (bcrypt, Argon2) for passwords, encrypt sensitive data at rest and in transit, and avoid deprecated algorithms like MD5 or SHA1.
3. Injection
Injection flaws, such as SQL injection, occur when untrusted data is sent to an interpreter as part of a command or query.
// Vulnerable: String concatenation in SQL query
const query = `SELECT * FROM users WHERE username = '${username}'`;
// Fixed: Use parameterized queries
const query = 'SELECT * FROM users WHERE username = ?';
db.query(query, [username]);
Prevention: Use parameterized queries or prepared statements, validate and sanitize input, and apply the principle of least privilege to database accounts.
4. Insecure Design
Insecure design refers to flaws in the application's architecture and logic, such as missing rate limiting on password reset or lack of account lockout.
// Vulnerable: No rate limiting on login
app.post('/login', (req, res) => {
// authenticate
});
// Fixed: Implement rate limiting
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 });
app.post('/login', limiter, (req, res) => {
// authenticate
});
Prevention: Use threat modeling during design, enforce secure defaults, and implement rate limiting and account lockout mechanisms.
5. Security Misconfiguration
This includes leaving default accounts enabled, exposing stack traces, or misconfiguring cloud permissions.
// Vulnerable: Exposing stack traces in production
app.use((err, req, res, next) => {
res.status(500).send(err.stack);
});
// Fixed: Log the error and send a generic message
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Something went wrong');
});
Prevention: Harden configurations, remove unused features, and ensure error handling does not leak information.
6. Vulnerable and Outdated Components
Using libraries with known vulnerabilities is a common risk. For example, an outdated version of a popular npm package might have a published CVE.
# Check for vulnerabilities
npm audit
# Automatically fix where possible
npm audit fix
Prevention: Regularly update dependencies, use tools like npm audit or OWASP Dependency-Check, and remove unused dependencies.
7. Identification and Authentication Failures
Weak authentication allows attackers to compromise passwords or session tokens. For example, permitting weak passwords or exposing session IDs in URLs.
// Vulnerable: Session ID in URL
app.get('/dashboard', (req, res) => {
const sessionId = req.query.sessionId;
// use sessionId
});
// Fixed: Use secure cookies
app.use(session({
secret: 'strong-secret',
cookie: { secure: true, httpOnly: true }
}));
Prevention: Implement multi-factor authentication, enforce strong password policies, and use secure session management.
8. Software and Data Integrity Failures
This includes using untrusted sources for software updates or deserializing untrusted data without verification.
// Vulnerable: Deserializing untrusted data
const obj = JSON.parse(untrustedInput);
// Fixed: Validate and sanitize before use
const obj = JSON.parse(untrustedInput);
if (typeof obj !== 'object' || obj === null) {
throw new Error('Invalid input');
}
Prevention: Verify the integrity of software and data using digital signatures, and avoid deserializing untrusted data.
9. Security Logging and Monitoring Failures
Without proper logging, breaches go undetected. For example, not logging failed login attempts or not monitoring for suspicious activity.
// Vulnerable: No logging
app.post('/login', (req, res) => {
if (authenticate(req.body)) {
// success
} else {
res.status(401).send('Unauthorized');
}
});
// Fixed: Log failed attempts
app.post('/login', (req, res) => {
if (authenticate(req.body)) {
// success
} else {
logger.warn(`Failed login for ${req.body.username}`);
res.status(401).send('Unauthorized');
}
});
Prevention: Log security-relevant events, monitor logs for anomalies, and establish an incident response plan.
10. Server-Side Request Forgery (SSRF)
SSRF occurs when an attacker can make the server perform requests to internal resources. For example, a vulnerable image fetcher that accepts arbitrary URLs.
// Vulnerable: Fetching any URL
app.get('/fetch-image', async (req, res) => {
const image = await fetch(req.query.url);
res.send(await image.buffer());
});
// Fixed: Validate URL and restrict to allowed domains
app.get('/fetch-image', async (req, res) => {
const url = new URL(req.query.url);
if (!['example.com', 'trusted.com'].includes(url.hostname)) {
return res.status(400).send('Invalid URL');
}
const image = await fetch(url.toString());
res.send(await image.buffer());
});
Prevention: Validate and sanitize URLs, use allowlists, and restrict outbound traffic from your servers.
Comparison Table: OWASP Top 10 at a Glance
| Vulnerability | Example | Prevention |
|---|---|---|
| Broken Access Control | Accessing other users' data via IDOR | Enforce server-side access checks |
| Cryptographic Failures | Storing passwords with MD5 | Use bcrypt/Argon2, encrypt data |
| Injection | SQL injection via string concatenation | Parameterized queries, input validation |
| Insecure Design | No rate limiting on login | Threat modeling, secure defaults |
| Security Misconfiguration | Exposing stack traces | Harden configs, remove defaults |
| Vulnerable Components | Outdated library with CVE | Regular updates, dependency scanning |
| Auth Failures | Weak passwords, session in URL | MFA, secure session management |
| Integrity Failures | Deserializing untrusted data | Verify signatures, validate input |
| Logging Failures | No logging of failed logins | Log security events, monitor |
| SSRF | Fetching internal URLs | URL allowlists, restrict outbound traffic |
FAQ
What is the OWASP Top 10?
The OWASP Top 10 is a regularly updated list of the most critical security risks to web applications, published by the Open Web Application Security Project (OWASP).
How often is the OWASP Top 10 updated?
OWASP updates the list periodically (roughly every 3-4 years) to reflect changes in the threat landscape and technology.
Can I prevent all OWASP Top 10 vulnerabilities?
While no application is completely immune, following secure coding practices, using security tools, and staying informed can significantly reduce the risk.
To further secure your applications, consider using tools like the Nginx Log Analyzer to monitor and detect suspicious activity in your server logs.