Sobes.tech
Junior — Middle

How can you identify a SQL injection vulnerability in this code?

sobes.tech AI

Answer from AI

SQL injection occurs when user input is directly inserted into an SQL query without proper handling. To identify a vulnerability in Python code, check whether the SQL query is constructed using string concatenation or formatting involving user data.

For example, vulnerable code:

user_id = input("Enter user ID: ")
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)

Here, if the user enters something like 1 OR 1=1, the query will be modified and return all records.

A safe approach is to use parameterized queries:

user_id = input("Enter user ID: ")
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))

Thus, to identify a vulnerability, look for places where user input is inserted directly into the SQL query without parameterization or escaping.