SQL Injection
SQL Injection
An attack that inserts malicious SQL code. Can lead to data leakage and tampering. Defended with Prepared Statements.
SQL Injection
An attack that inserts malicious SQL code. Can lead to data leakage and tampering. Defended with Prepared Statements.
SQL injection is a web security attack that inserts malicious SQL code through user input. It is a critical vulnerability that has long ranked near the top of the OWASP Top 10, and it can lead to data leakage, tampering, deletion, and even server takeover. Many damage cases are still being reported in 2023.
The attack principle is simple. If user input is concatenated directly into a query string, an attacker can include SQL syntax in the input and change the meaning of the original query. Example: WHERE id = '1' OR '1'='1' is always true, so all data is exposed. An input such as ' DROP TABLE users; -- can also delete a table.
SQL injection types: 1) In-band SQLi - results are displayed directly on screen (Error-based, UNION-based), 2) Blind SQLi - results are not visible and are inferred from true/false responses (Boolean-based, Time-based), 3) Out-of-band SQLi - data is exfiltrated through external channels such as DNS or HTTP requests.
The core defense is the Prepared Statement (Parameterized Query). It separates the SQL structure from the data so that the database driver safely escapes values. In addition, multi-layered defense is needed, including input validation, use of least-privilege DB accounts, a WAF (Web Application Firewall), and hiding error messages.
// SQL 인젝션 취약 코드 vs 안전한 코드
// ❌ 취약한 코드 - 문자열 연결
async function getUser_VULNERABLE(username: string) {
// 공격 예: username = "admin' OR '1'='1' --"
// 결과 쿼리: SELECT * FROM users WHERE username = 'admin' OR '1'='1' --'
const query = `SELECT * FROM users WHERE username = '${username}'`;
return await db.query(query); // 모든 사용자 정보 유출!
}
// ❌ 더 위험한 예 - DROP TABLE
// username = "'; DROP TABLE users; --"
// 결과: SELECT * FROM users WHERE username = ''; DROP TABLE users; --'
// ✅ 안전한 코드 - Prepared Statement (Node.js + PostgreSQL)
async function getUser_SAFE(username: string) {
const query = 'SELECT * FROM users WHERE username = $1';
// $1은 플레이스홀더, username은 별도 전달되어 이스케이프됨
return await db.query(query, [username]);
}
// ✅ TypeORM - Query Builder
async function getUser_TypeORM(username: string) {
return await userRepository
.createQueryBuilder('user')
.where('user.username = :username', { username }) // 파라미터 바인딩
.getOne();
}
// ✅ Prisma - 기본적으로 안전
const user = await prisma.user.findUnique({
where: { username } // Prisma가 자동으로 이스케이프
});
// ⚠️ 주의: Raw Query 사용 시
// Prisma raw query - 안전한 방법
const result = await prisma.$queryRaw`
SELECT * FROM users WHERE username = ${username}
`; // Tagged template literal은 자동 이스케이프
// ❌ Prisma raw query - 위험한 방법
const dangerous = await prisma.$queryRawUnsafe(
`SELECT * FROM users WHERE username = '${username}'`
); // 절대 사용 금지!
// ✅ 동적 컬럼명/테이블명이 필요한 경우 - 화이트리스트
const ALLOWED_COLUMNS = ['id', 'name', 'email', 'created_at'];
function buildQuery(sortColumn: string, sortOrder: string) {
// 입력값 검증 - 화이트리스트에 있는지 확인
if (!ALLOWED_COLUMNS.includes(sortColumn)) {
throw new Error('Invalid column name');
}
if (!['ASC', 'DESC'].includes(sortOrder.toUpperCase())) {
throw new Error('Invalid sort order');
}
// 검증된 값만 쿼리에 포함
return `SELECT * FROM users ORDER BY ${sortColumn} ${sortOrder}`;
}
// ✅ Python + psycopg2
import psycopg2
# 안전한 방법
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
(username, password) # 튜플로 파라미터 전달
)
# ✅ Java + JDBC
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, username); // 인덱스 기반 바인딩
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
In a security audit:
"A SQL injection vulnerability was found in the search feature. User input is being concatenated directly into the query. Even if you use an ORM, any part that uses a raw query must be fixed with parameter binding."
In a technical interview:
"How do we defend against SQL injection?" - "The most important thing is to separate the query from the data with a Prepared Statement. In addition, you need multi-layered defense, such as input validation, the principle of least privilege, hiding error messages, and applying a WAF."
In a code review:
"You're building the query with a template literal here, so please change it to parameter binding. Using an ORM is mostly safe, but dynamically inserting ORDER BY or table names requires whitelist validation."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free