Sobes.tech
Junior — Middle

Can you explain what SQL injection is and what is the danger of this vulnerability?

sobes.tech AI

Answer from AI

SQL injection is a type of vulnerability where an attacker can inject malicious SQL code into a database query through user input. This occurs when an application constructs SQL queries by directly inserting user data without proper validation and escaping.

The danger of SQL injection is that an attacker can:

  • Gain unauthorized access to data (e.g., read, modify, or delete information).
  • Bypass authentication mechanisms.
  • Perform administrative operations on the database.
  • In some cases, gain access to the server or execute arbitrary code.

An example of vulnerable Python code using the sqlite3 library:

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

user_input = "' OR '1'='1"
query = f"SELECT * FROM users WHERE username = '{user_input}'"
cursor.execute(query)
results = cursor.fetchall()

In this example, if user_input contains malicious code, the query will return all records, bypassing the username check.

To prevent SQL injections, parameterized queries or ORM should be used, which automatically escape data:

cursor.execute("SELECT * FROM users WHERE username = ?", (user_input,))

Thus, SQL injection is a serious security threat that must be prevented by proper handling of user input.