Junior — Middle
What methods are used to prevent injection attacks in applications?
sobes.tech AI
Answer from AI
The following methods are used in applications to prevent injection attacks:
- Use of parameterized queries (prepared statements) — instead of string concatenation for SQL queries, parameters are used, which are passed separately from the query code.
- Validation and filtering of input data — checking and restricting the format, length, and data type entered by the user.
- Use of ORM (Object-Relational Mapping) — abstracts database interactions and automatically escapes data.
- Escaping special characters — if parameterized queries are not possible, characters that can alter the query structure are escaped.
- Minimizing access rights — the database and application operate with the minimum necessary permissions.
Example of a parameterized query in Python using the sqlite3 library:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
user_id = 1
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
rows = cursor.fetchall()
This approach prevents the injection of malicious SQL code.