SY0-701Chapter 94 of 212Objective 2.3

Injection Attacks Overview

This chapter covers injection attacks, a critical threat category where attackers insert malicious code into an application's input to manipulate backend systems. Injection attacks consistently rank among the most dangerous web application vulnerabilities, and the SY0-701 exam tests your ability to identify, prevent, and mitigate them. This chapter maps to Objective 2.3 (Threats, Vulnerabilities, and Mitigations) and covers SQL injection, command injection, LDAP injection, XML injection, and NoSQL injection, along with their countermeasures.

25 min read
Intermediate
Updated May 31, 2026

The Trusted Waiter Injection Trick

Imagine a busy restaurant kitchen where waiters submit orders on slips of paper to the chef. The chef trusts that every order slip contains only food items, so he reads each slip and cooks whatever is written. A malicious customer realizes this trust and writes a note on the slip: 'Steak, and also add poison to the next customer's drink.' The waiter hands the slip to the chef, who sees 'Steak' and then reads the extra command as if it were a legitimate instruction. The chef, trained to follow all instructions on the slip, adds poison to the next drink. In this analogy, the waiter is the application, the chef is the database or interpreter, the order slip is the input form, and the malicious extra command is the injection payload. The key mechanic is that the system fails to distinguish between data (the steak) and code (the poison instruction). A secure restaurant would have the chef ignore anything on the slip that isn't a standard menu item, or require separate slips for special requests. Similarly, in injection attacks, the application does not properly separate untrusted user input from commands, allowing the attacker to execute arbitrary code. The defense is to treat all user input as data, not executable code, and to use parameterized queries or input validation to enforce this separation.

How It Actually Works

What Are Injection Attacks?

Injection attacks occur when an application passes untrusted user input to an interpreter (such as a SQL database, operating system shell, LDAP directory, or XML parser) without proper sanitization or validation. The attacker crafts input that contains both data and executable code, and the interpreter executes the code as if it were a legitimate command. The core vulnerability is the failure to separate data from code.

How Injection Attacks Work Mechanically

Injection exploits the fact that many interpreters use special characters to delimit commands or query structures. For example, in SQL, the single quote (') marks the start or end of a string literal. If an application constructs a SQL query by concatenating user input directly, an attacker can inject a single quote to break out of the intended string and then append malicious SQL commands.

Example of vulnerable code (SQL injection):

# Vulnerable Python code
username = request.GET['username']
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)

If an attacker enters ' OR '1'='1, the query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1'

This returns all rows because '1'='1' is always true.

Key Components and Variants

SQL Injection (SQLi): Targets SQL databases. Common payloads include ' OR 1=1 --, ' UNION SELECT ..., and '; DROP TABLE users --. The double dash -- comments out the rest of the query.

Command Injection: Targets operating system commands. Attackers inject shell metacharacters like ;, |, &, $(), or backticks to execute arbitrary commands. For example, input 127.0.0.1; ls -la could cause the application to ping an IP and then list files.

LDAP Injection: Targets LDAP directories. Attackers inject LDAP filter syntax, such as * or )(&), to bypass authentication or extract information.

XML Injection: Targets XML parsers. Attackers inject XML tags or special characters like <, >, & to alter the structure of XML documents, potentially leading to XXE (XML External Entity) attacks.

NoSQL Injection: Targets NoSQL databases like MongoDB. Attackers inject operators like $ne (not equal) or $gt (greater than) to manipulate queries. Example: {"username": {"$ne": ""}, "password": {"$ne": ""}} might bypass authentication.

How Attackers Exploit Injection

1.

Identify vulnerable input fields: Attackers test every input (URL parameters, form fields, HTTP headers, cookies) by submitting unexpected characters like single quotes, semicolons, or angle brackets.

2.

Detect error messages: If the application returns a database error (e.g., "You have an error in your SQL syntax"), the attacker knows the input is being processed unsafely.

3.

Craft payloads: Based on the error, attackers refine their payload to achieve their goal: data extraction, authentication bypass, privilege escalation, or remote code execution.

4.

Execute and escalate: Attackers use UNION-based SQLi to extract data from other tables, or they use stacked queries to run multiple commands (if supported).

Real-world example (CVE-2021-41773): A path traversal vulnerability in Apache HTTP Server 2.4.49 allowed attackers to map URLs to files outside the document root. While not classic injection, it shares the concept of insufficient input validation leading to unintended execution.

Defenses: How to Prevent Injection

Parameterized Queries (Prepared Statements): The most effective defense against SQL injection. User input is passed as parameters, not concatenated into the query string. The database treats the input as data only.

Example (safe code):

cursor.execute("SELECT * FROM users WHERE username = %s", (username,))

Stored Procedures: Precompiled SQL code that can also use parameters, but they are not foolproof if dynamic SQL is used inside the procedure.

Input Validation and Whitelisting: Validate input against a whitelist of allowed characters. For example, a username should only contain alphanumeric characters and underscores.

Output Encoding: Encode data before sending it to an interpreter. For example, HTML encode special characters before rendering in a browser.

Least Privilege: Use database accounts with minimal privileges. If an injection occurs, the attacker's actions are limited.

Web Application Firewalls (WAF): Can detect and block common injection patterns, but they are not a substitute for secure coding.

Escaping: Use escape functions for specific interpreters (e.g., mysql_real_escape_string), but this is less reliable than parameterized queries.

Standards and References

OWASP Top 10: Injection is consistently ranked as a top vulnerability (e.g., A03:2021 – Injection).

CWE-89: SQL Injection.

CWE-77: Command Injection.

CWE-90: LDAP Injection.

CWE-91: XML Injection.

NIST SP 800-53: Provides guidance on input validation (SI-10).

Exam-Relevant Details

The SY0-701 exam expects you to recognize injection attack indicators and choose appropriate mitigations.

Know the difference between SQL injection and command injection: SQLi targets databases, command injection targets the OS.

Understand that parameterized queries prevent SQL injection because they separate SQL logic from data.

Remember that input validation should be done on both client-side and server-side, but only server-side validation is trusted.

Be aware that NoSQL databases also have injection vulnerabilities, often through JSON payloads.

Walk-Through

1

Identify Vulnerable Input Points

The attacker begins by mapping the application's attack surface. They submit input to every form field, URL parameter, cookie, and HTTP header. They look for error messages or unexpected behavior when they enter special characters like a single quote ('), semicolon (;), or angle brackets (<>). For example, if a search box returns a database error after entering a single quote, the application likely has a SQL injection vulnerability. Tools like Burp Suite or OWASP ZAP automate this process. The attacker notes all endpoints that show signs of injection.

2

Break Out of Intended Context

Once a vulnerable input is found, the attacker crafts input to break out of the intended data context. In SQL injection, they insert a single quote to close the current string literal. For example, if the original query is `SELECT * FROM products WHERE name = 'user_input'`, entering `' OR '1'='1` results in `SELECT * FROM products WHERE name = '' OR '1'='1'`. The single quote closes the string, and the `OR '1'='1'` becomes part of the SQL logic. For command injection, they use shell metacharacters like `;` to end a command and start a new one.

3

Craft Malicious Payload

The attacker now crafts a payload to achieve a specific goal. For data exfiltration, they might use a UNION SELECT to retrieve data from other tables. For example: `' UNION SELECT username, password FROM users --`. For authentication bypass, they might use `' OR '1'='1' --`. For command injection, they might use `; ls -la /etc`. The payload is tailored to the backend interpreter. The attacker tests the payload incrementally, often using tools like sqlmap for automation.

4

Execute and Observe Results

The attacker submits the payload and observes the response. If successful, they may see data returned in the application's output, or they may receive a different status code or response length. For blind SQL injection (where no output is shown), the attacker uses boolean-based or time-based techniques. For example, they might use `' AND IF(1=1, SLEEP(5), 0) --` to cause a delay if the condition is true. Tools like sqlmap can automate blind injection. The attacker logs all successful payloads for later use.

5

Escalate and Maintain Access

After initial exploitation, the attacker escalates privileges or gains deeper access. In SQL injection, they might use `xp_cmdshell` (on SQL Server) to execute OS commands, or they might read sensitive files using `LOAD_FILE` (on MySQL). For command injection, they might create a reverse shell or upload a web shell. The attacker then covers their tracks by deleting logs or using obfuscated payloads. Defenders should monitor for anomalous database queries, shell commands, or outbound network connections.

What This Looks Like on the Job

Scenario 1: E-commerce Site Data Breach via SQL Injection

A SOC analyst at a retail company notices unusual database queries in the logs. The logs show a query like SELECT * FROM products WHERE id = 1 UNION SELECT credit_card_number, expiry, cvv FROM payments. The analyst traces the source IP to a user's search request. The application's product search endpoint directly concatenated user input into a SQL query. The attacker had extracted thousands of credit card numbers over several hours. The correct response is to immediately block the IP, take the vulnerable endpoint offline, and conduct a forensic analysis. The analyst should also check for data exfiltration patterns (e.g., large outbound data transfers). A common mistake is to only patch the vulnerability without checking for existing backdoors or compromised accounts.

Scenario 2: Command Injection in a Network Monitoring Tool

An engineer receives an alert from the IDS indicating a suspicious command execution on a network monitoring server. The alert shows a ping command with an appended ; cat /etc/shadow. The monitoring tool had a feature to ping IP addresses entered by users without sanitization. The attacker used this to read the password file. The correct response is to isolate the server, revoke any compromised credentials, and implement input validation (e.g., only allow valid IP addresses). The engineer should also check for other commands executed by the same attacker. A common mistake is to assume the tool is safe because it's internal, but internal tools are often targeted.

Scenario 3: NoSQL Injection in a Web Application

A penetration tester discovers that a login form using MongoDB is vulnerable to NoSQL injection. The tester sends a JSON payload: {"username": {"$ne": ""}, "password": {"$ne": ""}}. This returns the first user document where both fields are not empty, effectively bypassing authentication. The developer had used string interpolation to build the query. The correct remediation is to use parameterized queries (e.g., using MongoDB's $eq operator) or validate input to reject objects. The tester would report this as a critical finding. A common mistake is to think NoSQL databases are immune to injection; they are not.

How SY0-701 Actually Tests This

What SY0-701 Tests on Injection Attacks

The exam expects you to:

Identify injection attacks from scenario descriptions (e.g., SQL injection when a user enters a single quote and gets an error).

Choose the best mitigation (e.g., parameterized queries for SQL injection, input validation for command injection).

Understand that injection attacks exploit the lack of separation between data and code.

Recognize different types of injection: SQL, command, LDAP, XML, NoSQL.

Common Wrong Answers and Why Candidates Choose Them

1.

"Use a firewall to prevent injection" – Candidates think a network firewall can block malicious input, but injection happens at the application layer; a WAF can help but is not a complete solution. The best answer is input validation and parameterized queries.

2.

"Encrypt the database" – Encryption protects data at rest but does not prevent injection; the attacker can still extract encrypted data or bypass authentication.

3.

"Use client-side validation" – Client-side validation is easily bypassed (e.g., by disabling JavaScript). Server-side validation is essential.

4.

"Use stored procedures" – While stored procedures can help, they are not immune if they use dynamic SQL. Parameterized queries are the gold standard.

Specific Terms and Acronyms

SQLi: SQL Injection

Parameterized Query: Also called prepared statement; uses placeholders for user input.

Blind SQL Injection: Injection where no error or data is returned; uses boolean or time-based techniques.

UNION Injection: Using UNION to combine results from multiple SELECT statements.

Stacked Queries: Executing multiple SQL statements separated by semicolons (e.g., ; DROP TABLE users).

Common Trick Questions

Question: "An application allows users to search for products. An attacker enters ' OR '1'='1. What type of attack is this?" – Answer: SQL injection. The trick is that some candidates might think it's command injection because of the OR, but the single quote indicates SQL.

Question: "Which of the following is the most effective defense against SQL injection?" – Options: Firewall, Encryption, Parameterized queries, Stored procedures. The correct answer is parameterized queries.

Question: "A web application executes commands on the server based on user input. What attack is likely?" – Answer: Command injection. The trick is that candidates might choose SQL injection, but the clue is "executes commands on the server."

Decision Rule for Scenario Questions

1.

Identify the interpreter (SQL, OS, LDAP, XML, NoSQL).

2.

Look for special characters in the input (single quote, semicolon, angle brackets).

3.

Determine the goal (data extraction, authentication bypass, command execution).

4.

Choose the mitigation that directly addresses the root cause: separating data from code (parameterized queries, input validation, escaping).

5.

Eliminate answers that are generic (firewall, encryption) or client-side only.

Key Takeaways

Injection attacks exploit the lack of separation between data and code in an interpreter.

SQL injection is the most common type; parameterized queries are the primary defense.

Command injection allows attackers to execute OS commands; avoid using shell commands with user input.

Blind SQL injection uses boolean or time-based techniques to extract data without visible output.

NoSQL databases are also vulnerable to injection via operators like $ne.

Input validation should be server-side and whitelist-based, not blacklist-based.

OWASP Top 10 includes injection as a critical risk; know CWE-89, CWE-77, CWE-90, CWE-91.

Web application firewalls (WAFs) can detect injection but are not a replacement for secure coding.

Easy to Mix Up

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

SQL Injection

Targets SQL databases (MySQL, PostgreSQL, SQL Server, etc.)

Uses single quotes, double dashes, UNION, etc.

Goal: Extract data, bypass authentication, modify database

Mitigation: Parameterized queries, stored procedures

Example: ' OR '1'='1

Command Injection

Targets operating system shell (Linux, Windows)

Uses semicolons, pipes, backticks, $()

Goal: Execute arbitrary commands, gain shell access

Mitigation: Input validation, avoid shell execution, use APIs

Example: ; ls -la

Watch Out for These

Mistake

Only SQL databases are vulnerable to injection attacks.

Correct

Injection attacks can target any interpreter, including OS shells (command injection), LDAP directories (LDAP injection), XML parsers (XML injection), and NoSQL databases (NoSQL injection).

Mistake

Input validation alone is sufficient to prevent all injection attacks.

Correct

Input validation helps but is not foolproof; blacklisting can be bypassed. The most robust defense is to use parameterized queries or prepared statements, which inherently separate data from code.

Mistake

Stored procedures always prevent SQL injection.

Correct

Stored procedures can still be vulnerable if they use dynamic SQL (e.g., EXEC or EXECUTE IMMEDIATE) with concatenated user input. Parameterized queries are safer.

Mistake

Client-side validation is enough to stop injection attacks.

Correct

Client-side validation can be easily bypassed by disabling JavaScript or using tools like Burp Suite. All validation must be performed on the server side.

Mistake

NoSQL databases are immune to injection because they don't use SQL.

Correct

NoSQL databases can be injected using operators like $ne, $gt, or $where. For example, MongoDB queries built from user-supplied JSON objects can be manipulated.

Frequently Asked Questions

What is the difference between SQL injection and command injection?

SQL injection targets SQL databases by injecting malicious SQL statements through user input, aiming to extract or manipulate data. Command injection targets the operating system by injecting shell commands, aiming to execute arbitrary commands on the server. The key difference is the interpreter: SQL databases vs. OS shell. For the exam, remember that SQL injection uses single quotes and SQL keywords, while command injection uses shell metacharacters like semicolons or pipes.

How do parameterized queries prevent SQL injection?

Parameterized queries (prepared statements) separate SQL logic from data by using placeholders for user input. The database engine compiles the SQL query template first, then binds the user input as data only, never as executable code. Even if the input contains malicious SQL syntax, it is treated as a string literal, not as part of the SQL command. This prevents the attacker from altering the query structure.

Can NoSQL databases be injected?

Yes, NoSQL databases like MongoDB are vulnerable to injection if user input is used to build queries without proper sanitization. For example, if a login form passes a JSON object directly to a MongoDB query, an attacker can inject operators like $ne (not equal) to bypass authentication. Mitigations include using parameterized queries (e.g., with MongoDB's $eq operator) and validating input to reject unexpected data types.

What is blind SQL injection?

Blind SQL injection occurs when the application does not display database errors or query results in its output. The attacker must infer information by observing the application's behavior. Boolean-based blind injection sends queries that return true or false (e.g., ' AND 1=1 vs ' AND 1=2) and checks for differences in response. Time-based blind injection uses commands like SLEEP() to cause delays, indicating a true condition. Tools like sqlmap automate blind injection.

What is the best defense against command injection?

The best defense is to avoid executing OS commands with user input altogether. If unavoidable, use APIs or libraries that perform the required operation without invoking a shell. If shell execution is necessary, strictly validate input against a whitelist of allowed characters and escape shell metacharacters. Additionally, run the application with the least privilege possible to limit the impact of a successful injection.

How does input validation help prevent injection attacks?

Input validation ensures that user-supplied data conforms to expected formats and does not contain malicious characters. Whitelist validation (allowing only known good characters) is more secure than blacklist validation (blocking known bad characters). For example, a username field should only accept alphanumeric characters. However, input validation should be used as a defense-in-depth measure, not as the sole protection; parameterized queries are still needed for SQL injection.

What is the role of a WAF in preventing injection attacks?

A Web Application Firewall (WAF) can inspect HTTP requests and block those containing common injection patterns, such as SQL keywords or shell metacharacters. It acts as a filter between the user and the application. However, a WAF is not a complete solution because attackers can obfuscate payloads to evade detection. The primary defense must be secure coding practices like parameterized queries and input validation.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Injection Attacks Overview — now see how well it sticks with free SY0-701 practice questions. Full explanations included, no account needed.

Done with this chapter?