Denizhalil

Detecting SQL Injection Vulnerabilities with Python

Introduction:

SQL injection is a common type of security vulnerability encountered in web applications. Malicious users can gain access to or manipulate databases by injecting harmful code into database queries. This article will discuss developing a simple tool using Python to detect SQL injection vulnerabilities.

The Importance of Python and SQL Injection:

Python is a popular language due to its strong library support and easy-to-read syntax. SQL injection typically arises when developers directly add user inputs to database queries. Detecting this vulnerability is critical to enhancing the security of the application.

Development Process:

  1. Required Libraries: Firstly, we will use the requests library to send HTTP requests to the target web application. This library is commonly used for interacting with web-based applications in Python.
  2. SQL Injection Testing: We will prepare a set of typical SQL injection “payloads”. These payloads, when added to query parameters, help us check for the presence of a security vulnerability.
  3. Detection of the Vulnerability: For each payload, an HTTP POST request will be sent with modified query parameters. If the server’s response indicates a potential security vulnerability, this will be detected and reported.

Example Flask Application

First, we will create a simple web application using Flask and SQLite. This application will have a simple login page with username and password fields. However, this application is deliberately left vulnerable to SQL injection:

from flask import Flask, request, render_template_string
import sqlite3

app = Flask(__name__)

# A simple HTML form
HTML = '''
    <html>
        <head>
            <title>Login</title>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { width: 300px; margin: auto; margin-top: 50px; }
                input { margin-bottom: 10px; width: 100%; padding: 10px; }
                button { width: 100%; padding: 10px; }
            </style>
        </head>
        <body>
            <div class="container">
                <h2>Login</h2>
                <form method="post" action="/login">
                    <input type="text" name="username" placeholder="Username">
                    <input type="password" name="password" placeholder="Password">
                    <button type="submit">Login</button>
                </form>
            </div>
        </body>
    </html>'''

@app.route('/')
def home():
    return HTML

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

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

    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute(query)
    result = cursor.fetchone()
    conn.close()

    if result:
        return "Welcome, {}!".format(username)
    else:
        return "Login failed!"

if __name__ == '__main__':
    app.run(debug=True)

Our Website is ready!

Detecting SQL Injection Vulnerabilities with Python
Writing Our SQL Detection Tool:

Next, using Python and the requests library, we develop a tool to detect injection vulnerabilities in sites like the application we created above:

  1. Importing Library: The requests library is imported. This library is used for making HTTP requests in Python.
  2. SQL Injection Test Function: A function named test_sql_injection is defined. This function is used to detect SQL injection vulnerabilities at a given URL.
  3. SQL Injection Payloads: Typical injection payloads are added to a list. These payloads are designed to manipulate database queries.
  4. Testing Payloads: Each payload is tested in a for loop. The payloads are sent to the server as username and password parameters in an HTTP POST request.
  5. Checking Server Response: The server’s response is examined. If the response contains phrases like “Hoş geldiniz” or “Welcome”, this indicates successful detection of an injection vulnerability.
  6. Printing Results: If a vulnerability is detected, this is printed to the console. If not, the message “No Injection vulnerability detected.” is displayed.
  7. Test URL: A sample test URL is determined. Users can replace this URL with the one they want to test.
import requests

def test_sql_injection(url):
    # Typical payloads for SQL injection testing
    payloads = ["' OR '1'='1", "' OR '1'='1' --", "' OR 1=1--"]
    vulnerable = False

    for payload in payloads:
        # Add the payload to query parameters
        # In this example, 'username' and 'password' are the default parameters
        params = {'username': payload, 'password':

 'random'}
        response = requests.post(url, data=params)

        # If the payload is successful, we usually get an unexpected response
        if "Hoş geldiniz" in response.text or "Welcome" in response.text:
            print(f"SQL Injection vulnerability detected with payload: {payload}")
            vulnerable = True
        else:
            pass

    if not vulnerable:
        print("No SQL Injection vulnerability detected.")

# Test URL
test_url = "http://127.0.0.1:5000/login"  # Replace this URL with the one you want to test
test_sql_injection(test_url)

These steps provide a simple and effective method for detecting SQL injection vulnerabilities in web applications. In particular, the automatic detection of such security vulnerabilities and the identification of potential weaknesses are important steps in enhancing the security of web applications.

Detecting SQL Injection Vulnerabilities with Python

Conclusion

This tool is useful for detecting basic SQL injection vulnerabilities. However, for a more comprehensive security analysis, professional security tools and methodologies should be used. Developers should prefer practices such as parameterized queries or ORM libraries to prevent security vulnerabilities.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.