OWASP Top 10
The OWASP Top 10 is a document summarizing the most critical security risks in web applications. It is regularly updated by the Open Web Application Security Project (OWASP) and serves as a guideline for developers and security professionals to understand threats that should be addressed with priority.
OWASP Top 10 (2021 Edition)
1. A01:2021 - Broken Access Control
Overview Vulnerabilities where users can act beyond their authorized permissions.
Risk Examples
- Accessing other users' data by directly manipulating URLs
- Privilege escalation attacks
- Improper access control of APIs
Countermeasures
- Implement access control for all resources
- Adopt the principle of deny by default
- Proper implementation of session management
- Server-side permission checks
// Good Example: Server-side permission check
app.get('/api/users/:id/profile', async (req, res) => {
const requestedUserId = req.params.id;
const currentUserId = req.user.id;
// Accessible only by own profile or administrator
if (currentUserId !== requestedUserId && !req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied' });
}
const profile = await getUserProfile(requestedUserId);
res.json(profile);
});
2. A02:2021 - Cryptographic Failures
Overview A state where sensitive data encryption is insufficient or encryption is not properly implemented.
Risk Examples
- Storing passwords in plain text
- Using weak encryption algorithms
- Transmitting sensitive data over HTTP
- Improper key management
Countermeasures
- Encrypt all sensitive data
- Use strong encryption algorithms (e.g., AES-256)
- Enforce HTTPS/TLS
- Use secure hash functions (bcrypt, Argon2, etc.)
// Good Example: Password hashing
using BCrypt.Net;
public class UserService
{
public void CreateUser(string username, string password)
{
// Hash password and save
string hashedPassword = BCrypt.HashPassword(password, BCrypt.GenerateSalt(12));
// Save to database
SaveToDatabase(username, hashedPassword);
}
public bool VerifyPassword(string username, string password)
{
var user = GetUserFromDatabase(username);
return BCrypt.Verify(password, user.HashedPassword);
}
}
3. A03:2021 - Injection
Overview Vulnerabilities where untrusted data is sent as part of a command or query, causing unintended behavior.
Risk Examples
- SQL Injection
- NoSQL Injection
- OS Command Injection
- LDAP Injection
Countermeasures
- Use parameterized queries (prepared statements)
- Proper use of ORM
- Input validation and sanitization
- Principle of least privilege
// Bad Example: SQL Injection vulnerability
string query = "SELECT * FROM Users WHERE Username = '" + username + "'";
// Good Example: Parameterized query
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @Username", connection))
{
cmd.Parameters.AddWithValue("@Username", username);
SqlDataReader reader = cmd.ExecuteReader();
}
// Example using Entity Framework Core
var user = await dbContext.Users
.Where(u => u.Username == username)
.FirstOrDefaultAsync();
4. A04:2021 - Insecure Design
Overview Vulnerabilities due to lack of security requirements or improper risk analysis during the design phase.
Risk Examples
- Lack of threat modeling
- Non-use of security patterns
- Flaws in business logic
Countermeasures
- Adopt Secure Development Lifecycle (SDLC)
- Conduct threat modeling
- Clarify security requirements
- Conduct security reviews
5. A05:2021 - Security Misconfiguration
Overview A state where settings of applications, frameworks, databases, servers, etc., are inappropriate.
Risk Examples
- Using default credentials
- Enabling unnecessary services
- Displaying detailed error messages
- Not applying the latest security patches
Countermeasures
- Deploy with minimal configuration
- Change default settings
- Regular security updates
- Automated configuration management
// Good Example: Proper configuration in production environment
{
"production": {
"debug": false,
"detailedErrors": false,
"cors": {
"origins": ["https://yourdomain.com"],
"credentials": true
},
"headers": {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains"
}
}
}
6. A06:2021 - Vulnerable and Outdated Components
Overview A state of using libraries or frameworks with known vulnerabilities.
Risk Examples
- Using libraries that have reached end of support
- Using versions with known vulnerabilities
- Insufficient dependency management
Countermeasures
- Regular dependency updates
- Use vulnerability scanning tools (npm audit, Dependabot, Snyk, etc.)
- Use only supported versions
- Remove unnecessary dependencies
# Vulnerability check with npm
npm audit
# Auto fix
npm audit fix
# Fixed version specification in package.json
{
"dependencies": {
"express": "4.18.2" # Avoid ~ or ^
}
}
7. A07:2021 - Identification and Authentication Failures
Overview Vulnerabilities where user identification or authentication is not properly implemented.
Risk Examples
- Weak password policies
- Credential stuffing attacks
- Flaws in session management
- Lack of multi-factor authentication
Countermeasures
- Enforce strong password policies
- Implement Multi-Factor Authentication (MFA)
- Account lockout features
- Secure session management
// Good Example: Rate limiting and account lockout
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Max 5 attempts
message: 'Too many login attempts, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
app.post('/api/login', loginLimiter, async (req, res) => {
const { username, password } = req.body;
// Authentication process
const user = await authenticateUser(username, password);
if (!user) {
// Count failed attempts
await incrementFailedLoginAttempts(username);
return res.status(401).json({ error: 'Invalid credentials' });
}
// Request MFA token
if (user.mfaEnabled) {
return res.json({ requiresMFA: true, tempToken: generateTempToken() });
}
res.json({ token: generateToken(user) });
});
8. A08:2021 - Software and Data Integrity Failures
Overview Vulnerabilities where software updates or data processing are performed without integrity verification.
Risk Examples
- Updates without signature verification
- Deserialization from untrusted sources
- Unauthorized access to CI/CD pipelines
Countermeasures
- Verify digital signatures
- Use trusted repositories
- Harden CI/CD pipeline security
- Implement integrity checks
9. A09:2021 - Security Logging and Monitoring Failures
Overview A state where appropriate logging and monitoring are not implemented.
Risk Examples
- Lack or insufficiency of logs
- Lack of anomaly detection
- Delayed incident response
Countermeasures
- Log all security events
- Real-time monitoring and alerting
- Centralized log management
- Regular log reviews
// Good Example: Structured logging and recording security events
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'security.log' })
]
});
// Logging security events
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
const ipAddress = req.ip;
try {
const user = await authenticateUser(username, password);
if (!user) {
logger.warn({
event: 'LOGIN_FAILED',
username,
ipAddress,
timestamp: new Date().toISOString()
});
return res.status(401).json({ error: 'Invalid credentials' });
}
logger.info({
event: 'LOGIN_SUCCESS',
userId: user.id,
username,
ipAddress,
timestamp: new Date().toISOString()
});
res.json({ token: generateToken(user) });
} catch (error) {
logger.error({
event: 'LOGIN_ERROR',
username,
ipAddress,
error: error.message,
timestamp: new Date().toISOString()
});
res.status(500).json({ error: 'Internal server error' });
}
});
10. A10:2021 - Server-Side Request Forgery (SSRF)
Overview Vulnerabilities where a web application fetches remote resources without validating user-specified URLs.
Risk Examples
- Unauthorized access to internal services
- Leakage of cloud metadata
- Port scanning
- Firewall bypass
Countermeasures
- Whitelist URLs
- Segmentation at the network layer
- Restrict URL schemes
- Block internal IP addresses
// Good Example: SSRF countermeasures
import { URL } from 'url';
const ALLOWED_DOMAINS = ['api.example.com', 'cdn.example.com'];
const BLOCKED_IPS = ['127.0.0.1', '0.0.0.0', '::1'];
async function fetchExternalResource(urlString: string) {
try {
const url = new URL(urlString);
// Protocol check
if (url.protocol !== 'https:') {
throw new Error('Only HTTPS is allowed');
}
// Domain whitelist check
if (!ALLOWED_DOMAINS.includes(url.hostname)) {
throw new Error('Domain not allowed');
}
// Block internal IP addresses
if (BLOCKED_IPS.includes(url.hostname) ||
url.hostname.startsWith('192.168.') ||
url.hostname.startsWith('10.') ||
url.hostname.startsWith('172.')) {
throw new Error('Internal IP addresses are not allowed');
}
const response = await fetch(url.toString());
return response;
} catch (error) {
console.error('SSRF attempt blocked:', error);
throw error;
}
}
Summary
The OWASP Top 10 presents the security risks that require the most attention in web application development. It is important to be aware of these threats from the early stages of development and implement appropriate measures.
Recommendations
- Adopt Secure Development Lifecycle: Consider security from the design phase
- Regular Security Reviews: Conduct code reviews and vulnerability assessments
- Education and Training: Improve security awareness across the entire development team
- Leverage Automation Tools: Introduce SAST, DAST, and dependency scanning
- Incident Response Plan: Prepare response procedures for emergencies