Web Application Security ยท 3.2

๐Ÿ’‰ Injection & SQL Injection

When user input becomes an unintended commandโฑ ~3 min

๐Ÿ“Injection is smuggling instructions into a form

Imagine a form that asks for your name, and a clerk reads whatever you write and does it. You write: 'John. Also, give me the contents of the safe.' A careless clerk reads it all as instructions. Injection attacks work the same way โ€” the app can't tell your data (a name) from a command, so a crafted input hijacks it.

SQL Injection โ€” The Classic Example

Many apps store data in SQL databases and build database queries using user input. If the input isn't handled safely, an attacker can inject their own database commands. This is one of the oldest and most damaging web vulnerabilities โ€” and still common today.

Why It Happens (Conceptually)

The root cause is mixing untrusted user input directly into a command. When a login form builds a query by gluing the username straight into the SQL text, a specially-crafted username can change what the query actually does โ€” for example, tricking it into approving a login that should have failed.

The Fix โ€” Never Mix Data and Commands

python
# UNSAFE โ€” user input glued directly into the query (vulnerable to injection)
query = "SELECT * FROM users WHERE name = '" + user_input + "'"
# SAFE โ€” parameterized query: the database keeps data and commands separate
cursor.execute("SELECT * FROM users WHERE name = ?", (user_input,))
# The '?' placeholder means the input is ALWAYS treated as data,
# never as a command โ€” this single habit stops SQL injection.
๐Ÿ”’ SecurityThe defense against injection is a well-understood habit: never build commands by concatenating untrusted input. Use parameterized queries (also called prepared statements) so the system always treats user input as data. This is a solved problem โ€” the danger is developers not applying the fix consistently.

Cross-Site Scripting (XSS) โ€” Injection Into the Browser

XSS is injection's cousin: instead of injecting database commands, an attacker injects malicious scripts that run in other users' browsers. If a site displays user input without sanitizing it, an attacker's script can run for every visitor โ€” stealing sessions or defacing pages. The fix is similar: treat all user input as untrusted, and properly encode it before displaying it.

๐Ÿ’ก TipPortSwigger's Web Security Academy has excellent free, legal, hands-on labs for both SQL injection and XSS. Reading about injection is useful; safely doing it in a lab is where it truly clicks.
๐Ÿง Quick Checkfirst try = +5 XP

The root cause of injection vulnerabilities isโ€ฆ

โญ 0 XP๐Ÿ”ฅ 0 days