LearnThatStack Ace your next interview
Security · Free

OWASP Top 10 Security Cheat Sheet (2021).

Quick reference for OWASP Top 10 Security Cheat Sheet (2021) - sectioned for fast scanning. Skim the part you're shaky on, walk in confident.

Security 15-section reference ~9 min read

Summary

Master the OWASP Top 10 critical web application security risks for technical interviews. This comprehensive guide covers each vulnerability with practical examples, detection methods, and prevention strategies. Essential knowledge for application security engineers, penetration testers, and developers, providing code samples and best practices for identifying and mitigating the most common security threats in modern web applications.

Overview

The OWASP Top 10 is the industry-standard awareness document for web application security risks. Updated every 3-4 years based on global security data. Interview Essential: Be able to name all 10, explain each, and provide prevention strategies for the top 5.


A01:2021 – Broken Access Control

What is it?

Failures in enforcing restrictions on what authenticated users can do. Users can act outside their intended permissions.

Common Vulnerabilities

  • Vertical privilege escalation (accessing admin functions as regular user)
  • Horizontal privilege escalation (accessing other users' data)
  • Missing function level access control
  • Insecure direct object references (IDOR)

Example Attack

// Vulnerable: No authorization check
app.get('/api/user/:id', (req, res) => {
  const user = db.getUser(req.params.id);
  res.json(user);
});

// Secure: Proper authorization
app.get('/api/user/:id', authenticate, (req, res) => {
  if (req.user.id !== req.params.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  const user = db.getUser(req.params.id);
  res.json(user);
});

Prevention

  • Deny by default - except for public resources
  • Implement access control mechanisms once and reuse
  • Log access control failures
  • Rate limit API access
  • Invalidate JWT tokens on logout

Interview Key Points

  • Always check user permissions before granting access
  • Use role-based access control (RBAC) or attribute-based access control (ABAC)
  • Never rely on client-side access controls alone

A02:2021 – Cryptographic Failures

What is it?

Failures related to cryptography that lead to exposure of sensitive data. Previously called "Sensitive Data Exposure."

Common Issues

  • Data transmitted in clear text (HTTP, SMTP, FTP)
  • Weak/old cryptographic algorithms (MD5, SHA1, DES)
  • Weak key generation
  • Missing encryption at rest
  • Improper key storage

Example Vulnerabilities

# Vulnerable: Weak hashing
import hashlib
password_hash = hashlib.md5(password.encode()).hexdigest()

# Secure: Strong hashing with salt
import bcrypt
password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

Prevention

  • Classify data and apply protection accordingly
  • Don't store sensitive data unnecessarily
  • Encrypt data at rest and in transit
  • Use strong, updated algorithms (AES-256, RSA-2048+, SHA-256+)
  • Use proper key management
  • Enforce HTTPS with HSTS

Interview Key Points

  • Never roll your own crypto
  • Understand the difference between encoding, encryption, and hashing
  • Know when to use symmetric vs asymmetric encryption
  • Salt and pepper passwords before hashing

A03:2021 – Injection

What is it?

Untrusted data is sent to an interpreter as part of a command or query, allowing attackers to execute unintended commands.

Types of Injection

  • SQL Injection
  • NoSQL Injection
  • OS Command Injection
  • LDAP Injection
  • XPath Injection

SQL Injection Example

// Vulnerable: String concatenation
String query = "SELECT * FROM users WHERE name = '" + userName + "'";

// Secure: Parameterized query
String query = "SELECT * FROM users WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, userName);

Command Injection Example

# Vulnerable
os.system(f"ping {user_input}")

# Secure
subprocess.run(["ping", "-c", "4", user_input], check=True)

Prevention

  • Use parameterized queries/prepared statements
  • Use stored procedures (carefully)
  • Validate input using allowlists
  • Escape special characters
  • Use LIMIT in SQL queries
  • Apply least privilege to database accounts

Interview Key Points

  • Parameterized queries are the primary defense
  • Input validation is defense in depth, not primary defense
  • Understand blind SQL injection
  • Know about ORM injection risks

A04:2021 – Insecure Design

What is it?

Missing or ineffective security controls due to flawed design. Cannot be fixed by perfect implementation.

Examples

  • Missing rate limiting on password reset
  • No segregation between tenants in multi-tenant apps
  • Lack of business logic validation
  • Trust boundaries not properly defined

Design Flaws vs Implementation Bugs

# Design flaw: Anyone can transfer any amount
def transfer_money(from_account, to_account, amount):
    # No business logic checks!
    from_account.balance -= amount
    to_account.balance += amount

# Secure design: Business logic included
def transfer_money(from_account, to_account, amount, user):
    if not user.owns_account(from_account):
        raise PermissionError()
    if amount > from_account.daily_limit:
        raise LimitExceededError()
    if amount > from_account.balance:
        raise InsufficientFundsError()
    # ... perform transfer

Prevention

  • Threat modeling during design phase
  • Secure design patterns and reference architectures
  • Security requirements in user stories
  • Principle of least privilege in design
  • Defense in depth

Interview Key Points

  • Security must be built in, not bolted on
  • Understand threat modeling basics (STRIDE, DREAD)
  • Know secure design principles (least privilege, defense in depth, fail secure)

A05:2021 – Security Misconfiguration

What is it?

Missing appropriate security hardening or improperly configured permissions on cloud services.

Common Misconfigurations

  • Default credentials unchanged
  • Unnecessary features enabled (ports, services, accounts)
  • Error messages revealing sensitive info
  • Missing security headers
  • Outdated software
  • Permissive CORS policy

Examples

// Vulnerable: Detailed errors in production
app.use((err, req, res, next) => {
  res.status(500).json({
    error: err.message,
    stack: err.stack,  // Exposes internal details!
    sql: err.sql       // Exposes queries!
  });
});

// Secure: Generic errors in production
app.use((err, req, res, next) => {
  console.error(err); // Log internally
  res.status(500).json({
    error: 'Internal server error'
  });
});

Security Headers Example

// Implement security headers
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"]
    }
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true
  }
}));

Prevention

  • Repeatable hardening process
  • Minimal platform without unnecessary features
  • Regular patching
  • Security configuration review
  • Automated configuration verification

Interview Key Points

  • Know important security headers (CSP, HSTS, X-Frame-Options)
  • Understand the principle of least functionality
  • Be familiar with cloud security misconfigurations (S3 buckets, IAM)

A06:2021 – Vulnerable and Outdated Components

What is it?

Using components with known vulnerabilities or running outdated/unsupported software versions.

Risk Factors

  • Not knowing component versions
  • Using vulnerable, outdated, or unsupported software
  • Not scanning for vulnerabilities regularly
  • Not patching in timely fashion
  • Developers not testing compatibility of updated libraries

Example

// package.json with vulnerable dependencies
{
  "dependencies": {
    "express": "3.0.0",  // Old version with known vulnerabilities
    "lodash": "4.17.4"   // CVE-2019-10744 prototype pollution
  }
}

// Use npm audit to check
// npm audit
// npm audit fix

Prevention

  • Remove unused dependencies
  • Inventory versions of all components
  • Monitor CVE databases
  • Use dependency checking tools (OWASP Dependency Check, npm audit)
  • Obtain components from official sources
  • Monitor unmaintained libraries

Interview Key Points

  • Understand supply chain attacks
  • Know about dependency management tools
  • Familiar with CVE/NVD databases
  • Understand the importance of Software Bill of Materials (SBOM)

A07:2021 – Identification and Authentication Failures

What is it?

Functions related to authentication and session management implemented incorrectly, allowing attackers to compromise passwords, keys, or session tokens.

Common Weaknesses

  • Permits brute force attacks
  • Permits default/weak passwords
  • Weak password recovery
  • Plain text password storage
  • Missing/ineffective 2FA
  • Session ID exposed in URL
  • Session fixation

Examples

# Vulnerable: Session in URL
@app.route('/dashboard')
def dashboard():
    session_id = request.args.get('sid')  # Bad!
    user = get_user_by_session(session_id)
    
# Secure: Session in secure cookie
@app.route('/dashboard')
def dashboard():
    user = get_user_by_session(session['id'])  # From secure cookie
// Vulnerable: No rate limiting
app.post('/login', async (req, res) => {
  const user = await authenticate(req.body.username, req.body.password);
  // ...
});

// Secure: With rate limiting
const rateLimit = require('express-rate-limit');
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // 5 attempts
  message: 'Too many login attempts'
});

app.post('/login', loginLimiter, async (req, res) => {
  // ...
});

Prevention

  • Multi-factor authentication (MFA)
  • No default credentials
  • Implement weak password checks
  • Limit failed login attempts
  • Secure session management
  • Use secure password recovery
  • Log authentication failures

Interview Key Points

  • Understand different authentication factors (something you know/have/are)
  • Know session management best practices
  • Familiar with OAuth 2.0 and OpenID Connect basics
  • Understand JWT tokens and their risks

A08:2021 – Software and Data Integrity Failures

What is it?

Code and infrastructure that doesn't protect against integrity violations, including insecure deserialization and CI/CD pipeline compromises.

Common Issues

  • Insecure deserialization
  • Unsigned/unverified software updates
  • Insecure CI/CD pipelines
  • Untrusted sources in build process

Insecure Deserialization Example

// Vulnerable: Deserializing untrusted data
ObjectInputStream ois = new ObjectInputStream(userInputStream);
Object obj = ois.readObject(); // Dangerous!

// Safer: Use JSON instead of Java serialization
String jsonString = getJsonFromUser();
ObjectMapper mapper = new ObjectMapper();
UserData data = mapper.readValue(jsonString, UserData.class);

CI/CD Security Example

# GitHub Actions: Secure practice
name: Build
on:
  pull_request:
    branches: [ main ]
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read  # Minimal permissions
    steps:
      - uses: actions/checkout@v3
      - name: Build
        run: |
          # Pin versions, verify checksums
          npm ci  # Use lockfile
          npm audit
          npm run build

Prevention

  • Digital signatures for software/data
  • Verify dependencies and components
  • Secure CI/CD pipeline
  • Code signing
  • Avoid deserialization of untrusted data
  • Use integrity checks

Interview Key Points

  • Understand risks of deserialization
  • Know about supply chain security
  • Familiar with code signing concepts
  • Understand SBOM (Software Bill of Materials)

A09:2021 – Security Logging and Monitoring Failures

What is it?

Insufficient logging, detection, monitoring, and active response allows attackers to persist, pivot, and destroy data undetected.

Common Failures

  • Login failures not logged
  • Warnings/errors generate unclear log messages
  • Logs only stored locally
  • No monitoring of logs
  • No alerting thresholds
  • No incident response plan

Logging Example

import logging
import json
from datetime import datetime

# Configure structured logging
logger = logging.getLogger(__name__)

def login(username, password, ip_address):
    try:
        user = authenticate(username, password)
        # Log successful login
        logger.info(json.dumps({
            'event': 'login_success',
            'user_id': user.id,
            'username': username,
            'ip': ip_address,
            'timestamp': datetime.utcnow().isoformat()
        }))
        return user
    except AuthenticationError:
        # Log failed login
        logger.warning(json.dumps({
            'event': 'login_failure',
            'username': username,
            'ip': ip_address,
            'timestamp': datetime.utcnow().isoformat()
        }))
        raise

What to Log

  • Authentication events (success/failure)
  • Access control failures
  • Input validation failures
  • Privilege changes
  • High-value transactions

Prevention

  • Log all security events
  • Ensure logs are centralized
  • Establish monitoring and alerting
  • Create incident response plan
  • Protect logs from tampering
  • Retain logs appropriately

Interview Key Points

  • Know what events should be logged
  • Understand log injection attacks
  • Familiar with SIEM concepts
  • Know about incident response basics

A10:2021 – Server-Side Request Forgery (SSRF)

What is it?

Web application fetches remote resources without validating user-supplied URLs, allowing attackers to make requests to unintended locations.

Attack Scenarios

Vulnerable Example

// Vulnerable: No URL validation
app.get('/fetch-image', async (req, res) => {
  const imageUrl = req.query.url;
  const response = await fetch(imageUrl); // Dangerous!
  const image = await response.buffer();
  res.send(image);
});

// Secure: Validate and restrict URLs
const { URL } = require('url');

app.get('/fetch-image', async (req, res) => {
  try {
    const imageUrl = new URL(req.query.url);
    
    // Whitelist allowed domains
    const allowedHosts = ['example.com', 'cdn.example.com'];
    if (!allowedHosts.includes(imageUrl.hostname)) {
      return res.status(400).send('Invalid domain');
    }
    
    // Ensure HTTPS only
    if (imageUrl.protocol !== 'https:') {
      return res.status(400).send('HTTPS required');
    }
    
    // Block internal IPs
    const ip = await resolveIP(imageUrl.hostname);
    if (isInternalIP(ip)) {
      return res.status(400).send('Internal IPs blocked');
    }
    
    const response = await fetch(imageUrl.toString());
    // ... process response
  } catch (error) {
    res.status(400).send('Invalid URL');
  }
});

Cloud Metadata Example

# AWS metadata endpoint that SSRF can access
# http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Defense: Block metadata endpoints
BLOCKED_IPS = [
    '169.254.169.254',  # AWS
    '169.254.170.2',    # AWS
    'metadata.google.internal',  # GCP
    '168.63.129.16'     # Azure
]

Prevention

  • Input validation with allowlists
  • Disable unnecessary protocols (file://, dict://, ftp://)
  • Use separate network for remote resources
  • Deny by default
  • Don't send raw responses to clients
  • Block metadata endpoints

Interview Key Points

  • Understand cloud metadata endpoints
  • Know about DNS rebinding attacks
  • Familiar with URL parsing bypass techniques
  • Understand impact in cloud environments

Quick Reference Matrix

Vulnerability Primary Defense Secondary Defense
Broken Access Control Deny by default Access control checks
Cryptographic Failures Strong encryption Key management
Injection Parameterized queries Input validation
Insecure Design Threat modeling Secure patterns
Security Misconfiguration Hardening process Regular reviews
Vulnerable Components Patch management Dependency scanning
Auth Failures MFA Session management
Integrity Failures Digital signatures Avoid deserialization
Logging Failures Comprehensive logging SIEM/Monitoring
SSRF URL allowlisting Network segmentation

Interview Tips

Common Questions

  1. "What's the most critical vulnerability?" - Context dependent, but broken access control affects most apps
  2. "How do you prevent SQL injection?" - Parameterized queries first, then input validation
  3. "Explain the difference between authentication and authorization" - AuthN = who you are, AuthZ = what you can do
  4. "What's your approach to secure coding?" - Threat modeling, secure defaults, defense in depth
  5. "How do you keep dependencies secure?" - Regular scanning, automated updates, monitoring CVEs

Key Principles to Remember

  • Defense in Depth - Multiple layers of security
  • Least Privilege - Minimum necessary access
  • Fail Secure - Deny by default
  • Don't Trust User Input - Always validate
  • Security by Design - Built in, not bolted on

Red Flags in Code Review

  • String concatenation in queries
  • Hardcoded credentials
  • Missing authentication/authorization checks
  • Detailed error messages in production
  • Disabled security features
  • Use of dangerous functions (eval, exec, deserialize)

Additional Resources

Found this useful? Pass it on.
Pro · $10/mo

The sheet is free. Pro goes deeper.

Pro opens the full question library behind every sheet, every refresher and a monthly AI allowance. One subscription, all formats.

Full question library All refreshers Cancel anytime