문자열을 이어 붙여 쿼리를 짜던 프로젝트 코드는 SQL Injection에 무방비였다. 이걸 psycopg2 파라미터 바인딩으로 고치면서 정수형과 null 처리에서 헷갈렸던 부분까지 같이 정리했다.

따옴표 하나로 쿼리가 바뀐다

POST 인자로 { testKey : "testValue" }가 오면 쿼리는 select * from testTable where key = 'testValue'가 된다. 여기에 "testValue' and '해킹'='해킹"처럼 따옴표를 끼워 보내면 쿼리가 select * from testTable where key = 'testValue' and '해킹'='해킹'으로 변한다. 입력값의 첫 따옴표가 문자열을 닫아 버리고 뒷부분이 SQL로 실행되는 것이다.

실무에서 쓰던 코드가 딱 이렇게 취약했다.

import psycopg2
from psycopg2.extras import RealDictCursor

# DB 연결 준비
conn = psycopg2.connect("dbname={} user={} host={} password={}".format(db_name, db_user, db_host, db_pass))

# DB 호출함수 선언
def fetch(conn, query):
    result = []
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    cursor.execute(query) # SQL 실행

    # DB조회 결과값 담기
    raw = cursor.fetchall()
    for line in raw:
        result.append(line)

    return result

# SQL 쿼리 선언
# ❌ 입력값(pjt_no, item_type)이 그대로 쿼리 문자열이 된다
query = "select pjt_no, item_type from testTable "
query += "where pjt_no = '" + pjt_no + "' "
query += "and item_type = '" + item_type + "'"

# DB 호출함수 실행
result = fetch(conn=conn, query=query)

쿼리와 값을 따로 넘긴다

쿼리에는 자리표시만 두고, 실제 값은 cursor.execute()의 두 번째 인자로 따로 넘기면 된다. psycopg2가 값을 SQL 리터럴로 바꾸면서 따옴표를 이스케이프해 주므로 직접 치환할 필요가 없다.

먼저 fetch 함수가 값을 받도록 인자를 하나 추가했다.

# DB 호출함수 선언
def fetch(conn, query, sql_arg):
    result = []
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    cursor.execute(query, sql_arg) # ✓ 쿼리와 값을 분리해서 넘긴다

    # DB조회 결과값 담기
    raw = cursor.fetchall()
    for line in raw:
        result.append(line)

    return result

값을 넘기는 방식은 두 가지다. 자리표시를 %(이름)s로 쓰고 딕셔너리를 넘기거나, %s로 쓰고 순서에 맞춘 튜플을 넘긴다.

# SQL 쿼리 선언 (딕셔너리 방식)
query = "select pjt_no, item_type from testTable "
query += "where pjt_no = %(pjt_no)s "
query += "and item_type = %(item_type)s"
sql_arg = {
  'pjt_no' : pjt_no,
  'item_type' : item_type,
}

# DB 호출함수 실행
result = fetch(conn=conn, query=query, sql_arg=sql_arg)
# SQL 쿼리 선언 (튜플 방식)
query = "select pjt_no, item_type from testTable "
query += "where pjt_no = %s "
query += "and item_type = %s"
sql_arg = (pjt_no, item_type)

# DB 호출함수 실행
result = fetch(conn=conn, query=query, sql_arg=sql_arg)

튜플은 짧지만 조건이 늘어나면 순서를 맞추다 실수하기 좋다. 같은 값을 두 번 쓰거나 조건이 많으면 딕셔너리 쪽이 편하다. (%s에 작은따옴표를 붙이면 psycopg2가 넣는 따옴표와 겹치고, 줄 끝에 공백을 빼먹으면 %(pjt_no)sand처럼 붙어 버리니 주의해야 함.)

정수와 null을 넘길 때

파이썬 문자열 포맷팅에 익숙해서 DB 컬럼이 int면 %d를 써야 하는지 헷갈렸다. 당시엔 아예 str()로 감싸서 넘겼다.

test = 1 # 인자값

query = 'select * from testTable where key = %(str_test)s'
query_paramDict = { 'str_test' : str(test) }

cursor.execute(query, query_paramDict)

하지만 psycopg2의 %s는 파이썬 포맷 문자가 아니라 드라이버 자리표시다. 공식 문서에도 정수에 %d, 실수에 %f를 쓰지 말라고 적혀 있다. 타입과 무관하게 항상 %s를 쓰고 정수도 그냥 넘기면 된다.

# 형변환 없이 넘겨도 된다
query_paramDict = { 'str_test' : test }

빈 문자열('')을 받아 null을 넣어야 할 때도 당시엔 쿼리 문자열을 직접 고쳤다.

# 'test'라는 변수에 전달받은 인자값이 공백일 경우

query = 'select * from testTable where key = %(str_test)s'
query_paramDict = { 'str_test' : str(test) }

if test is '': query = query.replace('%(str_test)s', 'null')

cursor.execute(query, query_paramDict)

동작은 하지만 지금 보면 고칠 데가 셋이나 보인다. (돌아가긴 했으니 다행이라 해야 하나.)

  • 쿼리 치환 대신 None을 넘기면 psycopg2가 SQL NULL로 바꿔 주므로 replace 불필요. (str(None)은 문자열 'None'이 되니 주의.)

  • is '' 대신 == '' 사용. is는 객체 동일성 비교라 보장되지 않으며 Python 3.8부터는 SyntaxWarning 발생.

  • set key = null이나 values (null)은 되지만, 조회할 때 where key = null은 아무 행도 못 찾으므로 is null 사용.

# ✓ 빈 문자열이면 None을 넘긴다. 쿼리 문자열은 그대로 둔다
query_paramDict = { 'str_test' : test if test != '' else None }

cursor.execute(query, query_paramDict)