Back
+20 XP
Concept

Injection Armor: Parameterized Queries & Shell Safety

String formatting SQL or shell commands merges executable code with untrusted data. Parameterized queries enforce strict compile-time AST separation so attacker inputs are parsed purely as literal values. Similarly, passing list arguments with `shell=False` neuters shell injection 🛡️🛑.

python
import sqlite3
import subprocess

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE accounts (id INT, balance INT)")

# Attacker payload:
malicious_id = "100 OR 1=1"

# SECURE: Database engine treats input purely as literal parameter:
cursor = conn.execute("SELECT * FROM accounts WHERE id = ?", (malicious_id,))
print(f"Results returned: {cursor.fetchall()} (Attack neutered!) 🛡️")

# SECURE Subprocess: List of args with shell=False
# subprocess.run(["ping", "-c", "1", user_ip], shell=False)

# 72. Injection Armor: Parameterized Queries & Shell Safety The most infamous vulnerability in computing history (OWASP Top 10 #1) is injection. Concatenating user inputs into strings with `f"SELECT * FROM users WHERE name = '{name}'"` or `f"system('cat {filename}')"` invites attackers to execute arbitrary system code 🛑. ```python # The Vulnerability: Merging Code and Data # Attacker supplies: "admin' OR '1'='1" # SQL Query becomes: SELECT * FROM users WHERE name = 'admin' OR '1'='1' # Result: Attacker logs in without password! ``` ### The Architectural Armor 1. **Parameterized Queries**: Never use f-strings or `.format()` to construct SQL queries. Parameter placeholders (`?` or `%s`) send the query template to the database engine first. The engine compiles the execution plan, then binds user inputs as pure scalar values without re-parsing syntax 🛡️. 2. **Never Use `shell=True`**: In `subprocess.run()`, setting `shell=True` invokes `/bin/sh -c`, allowing attackers to append command separators (`; rm -rf /`). Always pass an explicit list `["cmd", "arg1", "arg2"]` with `shell=False`. 3. **`shlex.quote()`**: If you legitimately require shell string construction, always sanitize variables using `shlex.quote(var)` to escape meta-characters safely 🚀. --- ### Interactive Pop-Quiz 🧠 #### Why does parameterized SQL querying (cursor.execute(sql, params)) completely prevent SQL injection attacks? - [ ] The database compiles the query syntax tree before binding parameters, treating inputs strictly as literal data values 🛡️ - [ ] It converts all database strings into uppercase SHA-256 hashes - [ ] It runs the SQL statement inside an encrypted TLS socket - [ ] Because SQLite automatically strips quotation marks from all queries --- ### Practical Challenge 🎯 Using an in-memory SQLite database, create table `secrets (key TEXT, val TEXT)`. Insert `('admin_token', 'SECRET123')`. Use a parameterized query `SELECT val FROM secrets WHERE key = ?` with parameter `('admin_token',)` to extract the value. Verify the result equals `'SECRET123'`, and print `'PARAM_QUERY_OK'`. <details> <summary>Solution</summary> ```python import sqlite3 conn = sqlite3.connect(":memory:") conn.execute("CREATE TABLE secrets (key TEXT, val TEXT)") conn.execute("INSERT INTO secrets VALUES (?, ?)", ("admin_token", "SECRET123")) cursor = conn.execute("SELECT val FROM secrets WHERE key = ?", ("admin_token",)) res = cursor.fetchone() assert res[0] == "SECRET123" print("PARAM_QUERY_OK") ``` </details>

Checkpoint

Why does parameterized SQL querying (`cursor.execute(sql, params)`) completely prevent SQL injection attacks? 🧠

Practice

Using an in-memory SQLite database, create table `secrets (key TEXT, val TEXT)`. Insert `('admin_token', 'SECRET123')`. Use a parameterized query `SELECT val FROM secrets WHERE key = ?` with parameter `('admin_token',)` to extract the value. Verify the result equals `'SECRET123'`, and print `'PARAM_QUERY_OK'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks