๐Ÿ”’Security

SQL Injection

SQL Injection

An attack that manipulates a database by inserting malicious SQL code. It can lead to data leakage, deletion, authentication bypass, and even server takeover, and is defended against with Prepared Statements (parameterized queries).

๐Ÿ“– Detailed Explanation

SQL Injection (SQLi) is a security vulnerability that occurs when a web application inserts user input directly into an SQL query. Attackers inject malicious SQL code into input fields (login forms, search boxes, etc.) to cause unintended queries to be executed. Since it was first reported in 1998, it has remained one of the most dangerous web vulnerabilities, consistently ranking near the top of the OWASP Top 10.

The main types of SQL Injection are In-band SQLi, Blind SQLi, and Out-of-band SQLi. In-band SQLi is the most basic form, in which the results are displayed directly on the screen. Union-based extracts additional data using the UNION operator, and Error-based extracts information from error messages. In Blind SQLi, the results are not visible, but data is inferred from differences in true/false responses (Boolean-based) or from response time (Time-based).

If an attack succeeds, the damage is severe. An attacker can access an administrator account by bypassing authentication, or extract the entire contents of the database (Data Exfiltration). They can also delete data with DROP TABLE, or take over the server by executing operating system commands through features such as xp_cmdshell (MS SQL). In the 2017 Equifax hack, the personal information of 140 million people was leaked through SQL Injection.

The core of the defense is the Prepared Statement (Parameterized Query). By separating the SQL query structure from the data, user input is not interpreted as SQL syntax and is processed purely as data. Using an ORM (Object-Relational Mapping), the principle of least privilege (restricting DB account permissions), input validation (whitelisting), and applying a WAF (Web Application Firewall) are also important layers of defense.

๐Ÿ’ป Code Example

# โŒ SQL Injection ์ทจ์•ฝํ•œ ์ฝ”๋“œ ์˜ˆ์‹œ

# ===== Python (์ทจ์•ฝ) =====
import sqlite3

def login_vulnerable(username, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()

    # ์œ„ํ—˜: ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ๋กœ ์ฟผ๋ฆฌ ์ƒ์„ฑ
    query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
    cursor.execute(query)
    return cursor.fetchone()

# ๊ณต๊ฒฉ ์˜ˆ์‹œ 1: ์ธ์ฆ ์šฐํšŒ
# username: admin' --
# password: (์•„๋ฌด๊ฑฐ๋‚˜)
# ๊ฒฐ๊ณผ ์ฟผ๋ฆฌ: SELECT * FROM users WHERE username = 'admin' --' AND password = 'xxx'
# -- ์ดํ›„๋Š” ์ฃผ์„ ์ฒ˜๋ฆฌ๋จ โ†’ ๋น„๋ฐ€๋ฒˆํ˜ธ ๊ฒ€์ฆ ์šฐํšŒ!

# ๊ณต๊ฒฉ ์˜ˆ์‹œ 2: ํ•ญ์ƒ ์ฐธ์ธ ์กฐ๊ฑด
# username: ' OR '1'='1
# password: ' OR '1'='1
# ๊ฒฐ๊ณผ ์ฟผ๋ฆฌ: SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '' OR '1'='1'
# โ†’ ๋ชจ๋“  ์‚ฌ์šฉ์ž ๋ฐ˜ํ™˜!


# ===== Node.js (์ทจ์•ฝ) =====
# const query = `SELECT * FROM users WHERE id = ${req.params.id}`;
# connection.query(query);  // ์œ„ํ—˜!

# ๊ณต๊ฒฉ: /user/1; DROP TABLE users; --
# ๊ฒฐ๊ณผ: ์ „์ฒด ํ…Œ์ด๋ธ” ์‚ญ์ œ!


# ===== PHP (์ทจ์•ฝ) =====
# $query = "SELECT * FROM products WHERE id = " . $_GET['id'];
# mysql_query($query);  // ์œ„ํ—˜!


# ===== SQL Injection ๊ณต๊ฒฉ ํŽ˜์ด๋กœ๋“œ ์˜ˆ์‹œ =====
# (๊ต์œก ๋ชฉ์ , ์‹ค์ œ ๊ณต๊ฒฉ ๊ธˆ์ง€)

# ์ธ์ฆ ์šฐํšŒ
# ' OR '1'='1' --
# admin'--
# ' OR 1=1#

# Union ๊ธฐ๋ฐ˜ ๋ฐ์ดํ„ฐ ์ถ”์ถœ
# ' UNION SELECT username, password FROM users --
# ' UNION SELECT NULL, table_name FROM information_schema.tables --

# Time-based Blind SQLi
# ' OR IF(1=1, SLEEP(5), 0) --
# ' OR (SELECT SLEEP(5) FROM users WHERE username='admin') --

# Error-based (์ •๋ณด ์ถ”์ถœ)
# ' AND 1=CONVERT(int, (SELECT TOP 1 table_name FROM information_schema.tables)) --

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฒ„์ „ ํ™•์ธ
# ' UNION SELECT @@version --       (MySQL/MSSQL)
# ' UNION SELECT version() --       (PostgreSQL)
# โœ… SQL Injection ๋ฐฉ์–ด - Prepared Statement

# ===== Python (sqlite3) =====
import sqlite3

def login_secure(username, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()

    # ์•ˆ์ „: ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฐ”์ธ๋”ฉ (? ํ”Œ๋ ˆ์ด์Šคํ™€๋”)
    query = "SELECT * FROM users WHERE username = ? AND password = ?"
    cursor.execute(query, (username, password))
    return cursor.fetchone()

# ' OR '1'='1 ์ž…๋ ฅํ•ด๋„ ๋ฌธ์ž์—ด๋กœ ์ฒ˜๋ฆฌ๋จ
# ์ฟผ๋ฆฌ ๊ตฌ์กฐ์™€ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ถ„๋ฆฌ๋˜์–ด SQL๋กœ ํ•ด์„๋˜์ง€ ์•Š์Œ


# ===== Python (psycopg2 - PostgreSQL) =====
import psycopg2

def get_user_secure(user_id):
    conn = psycopg2.connect(database="mydb")
    cursor = conn.cursor()

    # %s ํ”Œ๋ ˆ์ด์Šคํ™€๋” ์‚ฌ์šฉ
    cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
    return cursor.fetchone()


# ===== Python (mysql-connector) =====
import mysql.connector

def search_products_secure(keyword):
    conn = mysql.connector.connect(host='localhost', database='shop')
    cursor = conn.cursor(prepared=True)

    # ์ด๋ฆ„ ์žˆ๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ
    query = "SELECT * FROM products WHERE name LIKE %(keyword)s"
    cursor.execute(query, {'keyword': f'%{keyword}%'})
    return cursor.fetchall()


# ===== Node.js (mysql2) =====
# const mysql = require('mysql2/promise');
#
# async function getUser(userId) {
#     const connection = await mysql.createConnection({...});
#
#     // ํŒŒ๋ผ๋ฏธํ„ฐํ™”๋œ ์ฟผ๋ฆฌ
#     const [rows] = await connection.execute(
#         'SELECT * FROM users WHERE id = ?',
#         [userId]
#     );
#     return rows[0];
# }


# ===== Java (JDBC) =====
# String query = "SELECT * FROM users WHERE username = ? AND password = ?";
# PreparedStatement pstmt = connection.prepareStatement(query);
# pstmt.setString(1, username);
# pstmt.setString(2, password);
# ResultSet rs = pstmt.executeQuery();


# ===== ์ถ”๊ฐ€ ๋ฐฉ์–ด ๊ณ„์ธต =====

# 1. ์ž…๋ ฅ ๊ฒ€์ฆ (ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ)
def validate_order_column(column):
    allowed = ['id', 'name', 'created_at', 'price']
    if column not in allowed:
        raise ValueError(f"Invalid column: {column}")
    return column

# 2. ์ตœ์†Œ ๊ถŒํ•œ ์›์น™
# - ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ DB ๊ณ„์ •์— SELECT, INSERT, UPDATE๋งŒ ๋ถ€์—ฌ
# - DROP, ALTER, CREATE ๊ถŒํ•œ ์ œ๊ฑฐ
# - ๋ฏผ๊ฐํ•œ ํ…Œ์ด๋ธ”์— ๋Œ€ํ•œ ์ ‘๊ทผ ์ œํ•œ

# 3. ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ˆจ๊ธฐ๊ธฐ
# - ํ”„๋กœ๋•์…˜์—์„œ ์ƒ์„ธ SQL ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ˆจ๊น€
# - ๋กœ๊ทธ์—๋งŒ ๊ธฐ๋ก, ์‚ฌ์šฉ์ž์—๊ฒŒ๋Š” ์ผ๋ฐ˜ ์—๋Ÿฌ ํ‘œ์‹œ
# โœ… ORM ์‚ฌ์šฉ - SQL Injection ์ž๋™ ๋ฐฉ์–ด

# ===== Python (SQLAlchemy) =====
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))
    password = Column(String(255))

# DB ์—ฐ๊ฒฐ
engine = create_engine('postgresql://user:pass@localhost/mydb')
Session = sessionmaker(bind=engine)
session = Session()

# ์•ˆ์ „ํ•œ ์ฟผ๋ฆฌ - ORM์ด ์ž๋™์œผ๋กœ ํŒŒ๋ผ๋ฏธํ„ฐํ™”
def login_with_orm(username, password):
    # filter()๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ Prepared Statement ์‚ฌ์šฉ
    user = session.query(User).filter(
        User.username == username,
        User.password == password
    ).first()
    return user

# LIKE ๊ฒ€์ƒ‰๋„ ์•ˆ์ „
def search_users(keyword):
    return session.query(User).filter(
        User.username.like(f'%{keyword}%')
    ).all()


# ===== Python (Django ORM) =====
# from myapp.models import User
#
# # ์ž๋™์œผ๋กœ ์•ˆ์ „ํ•œ ์ฟผ๋ฆฌ ์ƒ์„ฑ
# user = User.objects.filter(username=username, password=password).first()
#
# # Raw SQL ์‚ฌ์šฉ ์‹œ์—๋„ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฐ”์ธ๋”ฉ
# User.objects.raw('SELECT * FROM users WHERE id = %s', [user_id])


# ===== Node.js (Prisma) =====
# const user = await prisma.user.findFirst({
#     where: {
#         username: username,
#         password: password
#     }
# });


# ===== Node.js (Sequelize) =====
# const user = await User.findOne({
#     where: {
#         username: username,
#         password: password
#     }
# });


# ===== ์ฃผ์˜: Raw Query ์‚ฌ์šฉ ์‹œ =====

# SQLAlchemy raw query (์•ˆ์ „)
from sqlalchemy import text

result = session.execute(
    text("SELECT * FROM users WHERE id = :user_id"),
    {"user_id": user_id}
)

# Django raw query (์•ˆ์ „)
# User.objects.raw('SELECT * FROM users WHERE id = %s', [user_id])

# โŒ ์œ„ํ—˜ํ•œ ์‚ฌ์šฉ (๋ฌธ์ž์—ด ํฌ๋งทํŒ…)
# session.execute(f"SELECT * FROM users WHERE id = {user_id}")  # ์ ˆ๋Œ€ ๊ธˆ์ง€!


# ===== ์ •๋ ฌ/์ปฌ๋Ÿผ๋ช…์€ ํŒŒ๋ผ๋ฏธํ„ฐํ™” ๋ถˆ๊ฐ€ =====

# ๋™์  ORDER BY๋Š” ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋กœ ๊ฒ€์ฆ
ALLOWED_SORT_COLUMNS = ['id', 'name', 'created_at']

def get_sorted_users(sort_column, sort_order):
    if sort_column not in ALLOWED_SORT_COLUMNS:
        sort_column = 'id'
    if sort_order not in ['asc', 'desc']:
        sort_order = 'asc'

    # ๊ฒ€์ฆ๋œ ๊ฐ’๋งŒ ์‚ฌ์šฉ
    from sqlalchemy import asc, desc
    order_func = asc if sort_order == 'asc' else desc
    column = getattr(User, sort_column)

    return session.query(User).order_by(order_func(column)).all()

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a code review
"This part builds the SQL query with string formatting. That's an SQL Injection vulnerability. Please change it to a Prepared Statement. With parameter binding, user input is processed as pure data rather than as SQL syntax."
๐Ÿ’ฌ In response to a security audit
"After reviewing all database queries, we found dynamic query construction in 3 places. We fixed all of them to use an ORM or Prepared Statements, and reset the DB account permissions according to the principle of least privilege. In addition, we enabled SQL Injection detection rules in the WAF."
๐Ÿ’ฌ In an Interview
"The core of SQL Injection defense is separating the query structure from the data. A Prepared Statement compiles the query first and binds the data afterward, so even malicious input is not interpreted as SQL syntax. Using an ORM applies this approach by default."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions & Best Practices

โŒ
Building queries with string concatenation/formatting

f"SELECT * FROM users WHERE id = {user_id}" is the root cause of SQL Injection. Never use it. Use only Prepared Statements.

โŒ
Defending with input validation only

Blacklist filtering (such as removing quotation marks) can be bypassed. Input validation is a supplementary measure, and the Prepared Statement is the core defense.

โŒ
Excessive DB account privileges

Granting DBA privileges to the application's DB account maximizes the damage when SQLi succeeds. Grant only SELECT, INSERT, and UPDATE, and remove DROP and ALTER.

โœ…
SQL Injection Defense Best Practices

Prepared Statements are mandatory, ORM use is recommended, principle of least privilege, hide error messages, apply a WAF, regular code scanning (SAST), and whitelist validation for dynamic column/table names.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More