What is SQL Injection?
SQL Injection is a type of attack that exploits vulnerabilities in web applications that use SQL (Structured Query Language) to access databases. This attack allows attackers to inject malicious SQL code into queries executed by the application.
How SQL Injection Works
Here’s a simple example:
- A web application asks for user input, e.g., username and password.
- An attacker inputs malicious SQL code, like
admin' OR '1'='1, into the username field. - The application includes this input in the SQL query:
SQL
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'password'; - The database executes the query, and since
OR '1'='1'is always true, the attacker can log in without knowing the actual password.
Example
Suppose we have a simple web application using SQL for login:
PHP
$username = $_POST['username']; $password = $_POST['password']; $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'"; $result = mysql_query($query); If an attacker inputs admin' OR '1'='1 as the username and password as the password, the executed query is:
SQL
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'password'; Prevention
To prevent SQL Injection:
- Use Prepared Statements (PS) or Parameterized Queries
- Escape user input
- Validate user input
- Use an ORM (Object-Relational Mapping)
Hope this helps you understand the basics of SQL Injection!