Skip to main content

Lesson 3 of 11

SQL Injection

SQL Injection (SQLi) is one of the oldest and most devastating vulnerabilities. It allows attackers to manipulate database queries to bypass authentication, read sensitive data, modify records, and in some cases, execute operating system commands.

60 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

How SQL Injection Works

How SQL Injection Works
# Vulnerable login query (Python + raw SQL - NEVER DO THIS)
def vulnerable_login(username, password):
    query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
    return db.execute(query)

# Normal call:
vulnerable_login("alice", "password123")
# Query: SELECT * FROM users WHERE username='alice' AND password='password123'

# SQL Injection attack - username: admin'--  password: (anything)
vulnerable_login("admin'--", "anything")
# Query: SELECT * FROM users WHERE username='admin'-- AND password='anything'
# '--' is SQL comment - everything after it is ignored
# Effective query: SELECT * FROM users WHERE username='admin'
# Result: Logged in as admin WITHOUT knowing the password!

# More dangerous - UNION attack to extract data:
# username: ' UNION SELECT username, password, NULL FROM users--
# Query: SELECT * FROM users WHERE username='' UNION SELECT username, password, NULL FROM users--
# Returns all usernames and passwords from the users table

SQLi Attack Types

  • In-band SQLi (Error-based): Application returns database error messages - attacker reads schema info directly from error. Example: username: ' - database shows 'ERROR: unterminated quoted string'
  • In-band SQLi (Union-based): UNION keyword appends results of attacker's query to legitimate results - data exfiltrated directly in HTTP response
  • Blind SQLi (Boolean-based): No visible output, but behavior changes based on query truth. True condition: page loads normally. False condition: page shows different content. Attacker asks binary questions about data character by character
  • Blind SQLi (Time-based): No visible difference, but injection causes delay: ' AND SLEEP(5)--. If response takes 5 extra seconds → vulnerable. SLEEP(5) confirms injection; SLEEP only runs if condition is true
  • Out-of-band SQLi: Data exfiltrated via DNS or HTTP requests from the database server (requires database server internet access)

Parameterized Queries - The Fix

Parameterized Queries - The Fix
# SECURE: Parameterized queries (prepared statements) - the correct solution

# Python with parameterized queries
import sqlite3

def secure_login(username: str, password: str):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    
    # Parameters are NEVER concatenated into SQL - passed separately
    cursor.execute(
        "SELECT * FROM users WHERE username = ? AND password_hash = ?",
        (username, hash_password(password))  # Tuple of parameters
    )
    return cursor.fetchone()

# Attack attempt: username = "admin'--", password = "anything"
# Query remains: SELECT * FROM users WHERE username = ? AND password_hash = ?
# Parameters: ("admin'--", hash("anything"))
# The single quote is ESCAPED by the database driver - treated as literal data
# No SQL injection possible - the database receives the exact string "admin'--"

# Python with SQLAlchemy ORM (always parameterized automatically):
from sqlalchemy import text
result = db.execute(
    text("SELECT * FROM users WHERE username = :username"),
    {"username": username}
)

# ALSO VULNERABLE - even with parameterized queries, identifiers cannot be parameterized:
# column_name = user_input  → still injectable (table/column names)
# Solution: Whitelist allowed column names
ALLOWED_COLUMNS = {"username", "email", "created_at"}
if sort_column not in ALLOWED_COLUMNS:
    raise ValueError("Invalid sort column")

Defense in Depth for SQL Injection

  • Primary defense: Parameterized queries / prepared statements - makes SQLi structurally impossible for the parameterized portions
  • ORM frameworks: SQLAlchemy, Django ORM, Hibernate - use them correctly and they parameterize automatically
  • Input validation: Validate data type, length, format before using (not a substitute for parameterized queries - defense in depth)
  • Principle of least privilege: Application database user should only have SELECT on needed tables; not DROP, not UPDATE on system tables
  • WAF (Web Application Firewall): Detects and blocks common SQLi patterns - not reliable as sole defense but adds a layer
  • Error handling: Never expose database error messages to users - they reveal table names, column names, query structure

Common Mistakes

  • Escaping input instead of parameterizing - escaping functions can be bypassed with multi-byte character sets and encoding tricks. Always use parameterized queries
  • Parameterizing some inputs but not all - one unparameterized query is all it takes for a full database dump
  • Assuming ORMs are always safe - raw queries in ORMs (db.execute(f'...{user_input}')) are just as vulnerable as raw SQL

Tip

Tip

Practice SQL Injection in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Fix A01-A03 to prevent 60%+ of web attacks

Practice Task

Note

Practice Task - (1) Write a working example of SQL Injection from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with SQL Injection is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Key Takeaways

  • SQL Injection (SQLi) is one of the oldest and most devastating vulnerabilities.
  • In-band SQLi (Error-based): Application returns database error messages - attacker reads schema info directly from error. Example: username: ' - database shows 'ERROR: unterminated quoted string'
  • In-band SQLi (Union-based): UNION keyword appends results of attacker's query to legitimate results - data exfiltrated directly in HTTP response
  • Blind SQLi (Boolean-based): No visible output, but behavior changes based on query truth. True condition: page loads normally. False condition: page shows different content. Attacker asks binary questions about data character by character

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done