Junior — Middle
How is the injection of malicious SQL queries into an application carried out and how do systems protect against this vulnerability?
sobes.tech AI
Answer from AI
The injection of malicious SQL queries (SQL injection) occurs when an attacker inserts or modifies SQL code through user input, which is then directly embedded into a database query without proper validation.
For example, if an application constructs a query like:
query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s'", userInput)
and userInput contains something like admin' OR '1'='1, the resulting query becomes:
SELECT * FROM users WHERE username = 'admin' OR '1'='1'
which returns all records, bypassing authentication.
Protection against SQL injection includes:
- Using parameterized queries (prepared statements), where parameters are passed separately from SQL code.
- Validating and escaping user input.
- Using ORM or specialized libraries that automatically protect against injections.
An example of a safe query in Go using database/sql:
stmt, err := db.Prepare("SELECT * FROM users WHERE username = ?")
if err != nil {
// handle error
}
rows, err := stmt.Query(userInput)
Thus, parameters do not affect the structure of the SQL query, preventing malicious code injection.