> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/sqli.md).

# SQLi

SQL Injection (SQLi) is a type of injection attack where an attacker manipulates a database by injecting malicious SQL queries through application inputs such as forms, headers, or URL parameters. This vulnerability can allow attackers to bypass authentication and retrieve, modify, or delete database data.

***

#### Types of SQL Injection

* In-band SQLi
  * Error-based SQLi: Exploits database error messages to extract information.
  * Union-based SQLi: Uses the UNION operator to combine results of multiple SELECT queries into a single response.
  * Double query: Uses stacked queries (if supported) to execute multiple queries.
* Blind SQLi (no direct output)
  * Boolean-based: Observes differences in application responses based on true/false conditions.
  * Time-based: Uses delays (e.g., SLEEP()) to infer data based on response time.
* Out-of-band SQLi
  * Data is exfiltrated through a different channel (e.g., DNS, HTTP requests to an attacker-controlled server).
* Second-Order SQLi
  * A malicious payload is stored in the database and executed later when reused in another query.

***

### Impact

* **Sensitive data disclosure:** Access confidential information stored in the database.
* **Privilege escalation:** Gain access to higher-privileged accounts or functions.
* **Remote code execution**: Execute operating system commands in vulnerable configurations.
* **Authentication bypass:** Log in without valid credentials.
* **File read and write:** Read sensitive files and write files to the server, potentially enabling further compromise.

***

### Recommendations

* **Use parameterised queries:** Prevent SQL injection by separating SQL code from user input.
* **Use prepared statements:** Ensure user input is treated as data, not executable SQL.
* **Validate user input:** Accept only expected input formats and reject invalid data.
* **Use stored procedures securely:** Ensure stored procedures do not concatenate untrusted input.
* **Hide database errors:** Prevent detailed SQL errors from being displayed to users.
* **Apply least privilege:** Grant the database account only the permissions it requires.
* **Use a Web Application Firewall (WAF):** Detect and block common SQL injection attempts.
