Middle+
What is an SQL injection? Provide an example of a vulnerable query and methods of protection.
sobes.tech AI
Answer from AI
SQL injection is a vulnerability where an attacker can inject malicious SQL code into a database query through user input. This can lead to unauthorized access, modification, or deletion of data.
Example of a vulnerable query in Go:
username := r.FormValue("username")
query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s'", username)
rows, err := db.Query(query)
If the user enters username as ' OR '1'='1, the query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1'
which returns all records.
Protection methods:
- Using prepared statements with parameterization:
stmt, err := db.Prepare("SELECT * FROM users WHERE username = ?")
rows, err := stmt.Query(username)
- Validation and escaping of user input.
- Using ORMs that automatically protect against injections.
- Limiting database access rights.
Thus, the main protection is query parameterization, which separates SQL code from data.