# SQL Injection

SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries an application makes to its database. It typically involves injecting malicious SQL code into a query, which can manipulate the database to execute unintended commands.

**How an Attacker Can Exploit SQL Injection:**

1. **Injection via Input Fields:** Attackers insert malicious SQL code into input fields (e.g., login forms, search boxes) that are concatenated into SQL queries.
2. **URL Manipulation:** Attackers modify query parameters in the URL to include SQL code.
3. **Cookies:** Malicious SQL code can be inserted into cookies that are used in SQL queries.
4. **HTTP Headers:** SQL code can be injected through HTTP headers such as User-Agent.

**Potential Damage:**

1. **Data Theft:** Unauthorized access to sensitive data (e.g., user credentials, personal information).
2. **Data Manipulation:** Modification or deletion of data.
3. **Authentication Bypass:** Gaining unauthorized access by bypassing login mechanisms.
4. **Database Corruption:** Destroying or corrupting database data.
5. **Escalation of Privileges:** Gaining administrative access to the database server.
6. **Remote Code Execution:** In some cases, executing commands on the server hosting the database.

**Brief Use Cases:**

1. **Extracting User Data:** Accessing usernames and passwords stored in the database.
2. **Dumping Database:** Retrieving the entire contents of a database.
3. **Administrative Operations:** Performing administrative operations like adding or deleting users.
4. **Compromising Systems:** Escalating privileges to control the database server and potentially the underlying operating system.

**Protection Measures and Implementation:**

1. **Parameterized Queries (Prepared Statements):**
   * **Description:** Ensures that SQL code is defined separately from the data.
   * **Implementation:**

     ```python
     # Example in Python using SQLite
     import sqlite3

     conn = sqlite3.connect('example.db')
     cursor = conn.cursor()
     cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
     ```
   * **Requirements:** Database and application support for parameterized queries.
2. **Stored Procedures:**
   * **Description:** Encapsulates SQL queries within the database, reducing direct SQL manipulation.
   * **Implementation:**

     ```sql
     -- Example in SQL Server
     CREATE PROCEDURE AuthenticateUser
     @username NVARCHAR(50),
     @password NVARCHAR(50)
     AS
     BEGIN
         SELECT * FROM users WHERE username = @username AND password = @password
     END
     ```
   * **Requirements:** Database support for stored procedures.
3. **Input Validation:**
   * **Description:** Validates and sanitizes user input to ensure it adheres to expected formats.
   * **Implementation:**

     ```python
     # Example in Python
     import re

     def validate_input(user_input):
         if re.match("^[a-zA-Z0-9_]+$", user_input):
             return True
         else:
             return False
     ```
   * **Requirements:** Implementation of robust input validation functions.
4. **Escaping Inputs:**
   * **Description:** Escapes special characters in user inputs to neutralize any SQL code.
   * **Implementation:**

     ```php
     // Example in PHP
     $username = mysqli_real_escape_string($conn, $_POST['username']);
     $password = mysqli_real_escape_string($conn, $_POST['password']);
     ```
   * **Requirements:** Functions or libraries for escaping inputs.
5. **Web Application Firewalls (WAF):**
   * **Description:** Inspects and filters traffic to block malicious SQL injection attempts.
   * **Implementation:** Configure a WAF like ModSecurity with rules to detect and prevent SQLi.
   * **Requirements:** Deployment and configuration of a WAF.
6. **Least Privilege Principle:**
   * **Description:** Restrict database user permissions to the minimum necessary for the application to function.
   * **Implementation:**

     ```sql
     -- Example in MySQL
     CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'password';
     GRANT SELECT, INSERT, UPDATE ON database.* TO 'appuser'@'localhost';
     ```
   * **Requirements:** Proper database user role configuration.

By implementing these protective measures, you can significantly reduce the risk of SQL Injection attacks on your web applications.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hackerspot.net/web-security/web-vulnerabilities/sql-injection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
