SQL Injection and Command Injection
Learn how attackers craft injection payloads that manipulate database queries or OS commands, and how parameterized queries and input validation prevent them.
SQL Injection and Command Injection is a free Cloud & IT Cert Prep lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cloud & IT Cert Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is SQL Injection?
SQL injection (SQLi) occurs when an attacker inserts or 'injects' malicious SQL code into an input field that is later passed to a database query. Because the application concatenates user input directly into a SQL statement, the database cannot distinguish between legitimate data and attacker-supplied commands. SQLi consistently ranks as one of the most dangerous web vulnerabilities on the OWASP Top 10.
Classic SQLi Payload Example
A vulnerable login query might look like: SELECT * FROM users WHERE username='INPUT' AND password='INPUT'. An attacker supplying ' OR '1'='1 as the username transforms the query so the WHERE clause is always true, bypassing authentication entirely. This is the classic tautology-based injection.
-- Vulnerable query (DO NOT use in production)
SELECT * FROM users
WHERE username = '' OR '1'='1'
AND password = 'anything';
-- Returns ALL rows — auth bypassedTypes of SQL Injection
SQL injection attacks come in several forms: In-band SQLi returns results directly in the HTTP response (error-based or union-based). Blind SQLi infers data through Boolean true/false responses or deliberate time delays (SLEEP(5)). Out-of-band SQLi uses secondary channels like DNS lookups to exfiltrate data when responses are not visible.
-- Time-based blind SQLi example
SELECT * FROM users
WHERE id = '1' AND SLEEP(5)--';
-- If response is delayed 5s, injection succeededPreventing SQLi: Parameterized Queries
The primary defense against SQL injection is parameterized queries (also called prepared statements). In a parameterized query, the SQL structure is compiled first, and user input is passed as a separate parameter — it can never alter the query structure. This approach is language-agnostic and far more reliable than input sanitization alone.
# Python example — parameterized query (safe)
import sqlite3
conn = sqlite3.connect('app.db')
cursor = conn.cursor()
username = 'admin'
password = 'secret'
cursor.execute(
'SELECT * FROM users WHERE username=? AND password=?',
(username, password) # parameters, never concatenated
)Input Validation as Defense in Depth
While parameterized queries are the primary defense, input validation provides an important secondary layer. Allowlist validation accepts only expected characters (e.g., alphanumeric only for a username field) and rejects everything else. Denylist validation blocks known bad characters, but attackers often encode or obfuscate payloads to bypass denylists — making allowlists far stronger.
What Is Command Injection?
Command injection (OS command injection) occurs when an application passes unsanitized user input to a system shell. Unlike SQL injection that targets databases, command injection targets the operating system itself — giving attackers the ability to run arbitrary commands with the privileges of the web server process. It is rated critical severity and often leads to full system compromise.
Command Injection Example
A web app that pings a user-supplied IP address might use: ping -c 1 INPUT. If an attacker supplies 8.8.8.8; cat /etc/passwd, the shell interprets ; as a command separator and runs both commands. Common injection operators include ;, &&, ||, |, and backtick command substitution.
# Vulnerable Python (subprocess with shell=True)
import subprocess
user_ip = '8.8.8.8; cat /etc/passwd' # attacker input
subprocess.run('ping -c 1 ' + user_ip, shell=True)
# Safe alternative — avoid shell=True, pass args as list
subprocess.run(['ping', '-c', '1', '8.8.8.8'])Preventing Command Injection
The safest defense against command injection is to avoid calling OS commands from user input entirely — use library functions that accomplish the same goal. When shell calls are unavoidable, pass arguments as a list (never as a concatenated string), disable shell interpretation, validate input against a strict allowlist, and run processes with the least-privileged user account possible.
OWASP Context: Injection in the Top 10
The OWASP Top 10 lists Injection (which encompasses SQL, NoSQL, OS, and LDAP injection) as one of the most critical application security risks. OWASP recommends a defense-in-depth approach: use safe APIs that avoid the interpreter, perform positive (allowlist) server-side input validation, escape special characters using the syntax specific to that interpreter, and use SQL controls like LIMIT to prevent mass disclosure.
Detection: WAFs and Logging
A Web Application Firewall (WAF) can detect and block common injection payloads by inspecting HTTP requests against signature patterns. However, WAFs can be bypassed through encoding tricks and are not a substitute for secure coding. Proper application logging — recording query parameters, response codes, and error messages — enables security teams to identify injection attempts during incident review.
Real-World Impact of Injection Attacks
Injection attacks have caused some of the largest data breaches in history. The 2017 Equifax breach exposed 147 million records via a web application flaw. SQL injection against Sony PlayStation Network compromised 77 million accounts in 2011. These incidents illustrate that injection flaws carry extreme business impact: data theft, regulatory fines, reputational damage, and legal liability all follow a successful injection attack.
Quick Check
Test your understanding of CompTIA Security+ (SY0-701) concepts from this lesson.
Lesson Recap
In this lesson you learned: SQL injection exploits unsanitized input concatenated into database queries, command injection passes malicious input to the OS shell via operators like ; and |, and parameterized queries and avoiding shell=True are the primary defenses. Next up we explore Cross-Site Scripting (XSS) and CSRF attacks.
Frequently asked questions
Is the “SQL Injection and Command Injection” lesson free?
Yes — the full text of “SQL Injection and Command Injection” is free to read here on the web, and the Cloud & IT Cert Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cloud & IT Cert Prep course, upgrade to CoddyKit PRO.
What will I learn in “SQL Injection and Command Injection”?
Learn how attackers craft injection payloads that manipulate database queries or OS commands, and how parameterized queries and input validation prevent them. You practise Cloud & IT Cert Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Cloud & IT Cert Prep?
No prior experience is required. Cloud & IT Cert Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “SQL Injection and Command Injection” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Cloud & IT Cert Prep lesson?
Yes. Every Cloud & IT Cert Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SQL Injection and Command Injection
- Cross-Site Scripting (XSS) and CSRF
- Broken Authentication and Insecure Deserialization
- Secure SDLC, SAST, and DAST Tools