SQL Injection (SQLi)
SQL Injection is an attack technique that exploits vulnerabilities in a web application's input fields (like login forms or search boxes) to send malicious SQL commands to the backend database.
This attack severely compromises the integrity and confidentiality between the web application and the database.
1. How the Attack Works: Confusing Input and Code
SQL Injection occurs when user-supplied input is incorrectly treated as part of the executable SQL code by the server.
① Vulnerable Code Example (PHP/Python)
A query constructed by directly concatenating a user's input (user_id) without validation.
// "user_id" is the user input
query = "SELECT * FROM users WHERE id = '" + user_id + "';"
② Attack Scenario (Login Bypass)
The attacker enters the following string into the ID input field:
Input: admin' OR '1'='1
The resulting SQL query executed on the server becomes:
SELECT * FROM users WHERE id = 'admin' OR '1'='1';
- Interpretation: The condition
'1'='1'is always true. Because of theOR, the entireWHEREclause becomes true for the first record found. - Result: The attacker successfully logs in as the admin without knowing the password.
2. Risks of SQLi Attacks
- Authentication Bypass: Bypassing login mechanisms (as shown above).
- Data Exfiltration: Using the
UNIONclause to extract all data from other tables (e.g., personal information, encrypted passwords) and send it to the attacker. - Data Corruption/Deletion: Injecting
UPDATEorDROP TABLEcommands to modify or destroy database content.
3. SQLi Defense Strategies (Developer Perspective)
The core defense against SQL Injection is to completely separate user input from the executable SQL code.
- Prepared Statements or Parameterized Queries:
- The most effective defense. This instructs the DBMS to treat the user input strictly as data and never as part of the executable SQL command structure. The query structure is fixed and prepared beforehand.
- Input Validation:
- Strictly checking the input data to ensure it only contains allowed characters and adheres to expected format/length (e.g., ensuring a username doesn't contain quotation marks).
- Principle of Least Privilege:
- Ensuring the web application's database account has only the minimum necessary permissions (e.g., only allow
SELECTand prohibitDROP TABLE).
- Ensuring the web application's database account has only the minimum necessary permissions (e.g., only allow