[파이썬] SQL 삽입 공격

SQL injection attack is a common vulnerability that occurs when an attacker can manipulate a SQL query by inserting malicious SQL code into an input field. This can lead to unauthorized access to the database, data leakage, or even complete control over the targeted system.

In this blog post, we will explore how to prevent SQL injection attacks in Python using parameterized queries and input validation.

1. Parameterized Queries

Parameterized queries, also known as prepared statements, are a powerful defense mechanism against SQL injection attacks. Instead of concatenating user inputs directly into the SQL query, we use placeholders that are filled in with the input values at runtime, ensuring that the input is properly escaped.

Example:

import sqlite3

def get_user(username):
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()

    # Using parameterized query
    query = "SELECT * FROM users WHERE username = ?"
    cursor.execute(query, (username,))

    user = cursor.fetchone()

    conn.close()

    return user

In the example above, the username parameter is passed as a placeholder in the SQL query. This way, even if the username contains malicious SQL code, it will be treated as a literal value rather than executable code.

2. Input Validation and Sanitization

While parameterized queries provide a strong defense against SQL injection attacks, it’s still important to validate and sanitize user input to prevent other types of vulnerabilities.

Example:

import re

def is_valid_username(username):
    # Validate username format
    if re.match("^[a-zA-Z0-9_-]{3,20}$", username):
        return True
    else:
        return False

In the example above, we use regular expressions to validate the username format. By enforcing specific rules for the input, we can reduce the risk of SQL injection attacks and other security vulnerabilities.

Conclusion

SQL injection attacks can have devastating consequences, but by following the best practices such as using parameterized queries and input validation, we can mitigate the risks significantly. Remember to always validate and sanitize user input before using it in SQL queries to ensure the security of your application.

Stay safe and happy coding!

Reference: