Users Online

· Guests Online: 151

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Python SQL Injection

Python SQL Injection

 

 

Python SQL Injection

Introduction to Python SQL Injection

Python SQL injection is a vulnerability and security which was legendary for a webcomic. It is a typical task to create and execute SQL queries. However, when it comes to constructing SQL statements, businesses all around the world frequently make terrible blunders. Although the ORM layer normally generates SQL queries, we may need to write our own occasionally. When we run queries straight into a database, there’s a danger.

What is Python SQL Injection?

  • SQL injection is nothing but the multiple commands which was embedded in a URL string or data structure to extract the desired response from databases connected to web applications. This kind of attack is most common on PHP or ASP.NET-based websites.
  • A common example of an SQL injection attack is changing the content of the database to run multiple queries from the application end.
  • This attack occurs when an application fails to validate inputs properly before delivering them to a SQL statement. Normally, injections are placed in search areas or data fields.

How to Build Python SQL Injection?

  • Using the “‘” character in a string and seeing if we get an error is the quickest way to see if a web application is vulnerable to a SQL injection attack.
  • SQLi is the most common and harmful code insertion technique in general. The most typical attack target is mass knowledge extraction. Attackers can dump database tables containing tens of thousands of client records. Depending on the environment, SQL injection can also swap or remove data.
  • SQL injection is carried by user input; we will extract the forms using a method described below. Then we’ll see if a web page has any SQL issues, which will come in handy when testing for SQL injection attacks, and we’ll put it to the test on HTML forms.

Below steps shows how to build python SQL injection as follows:

1. In the first step, we import the module names as requests and sys. This module is used to build the python SQL injection.

Python SQL Injection 1

2. After importing the module, in this step, we are initializing the http session and setting up the latest agent for our browser.

We initialize the http module with Mozilla and Chrome browsers in the below step.

Code:

s = requests.Session ()
s.headers ["User-Agent"] = "Mozilla/5.0 (Win64; x64) AppleWebKit/537.36 Chrome/87.0.4280.88"

Output:

Python SQL Injection 2

3. After initializing the http session and setting up the agent in this step, we extract the web forms. For extracting the web forms first, we are writing the function giving the URL and making the request to the page which was extracting the html from the tags. After this, tags will be returned as a list. We can be using this tag as a list afterward.

Code:

def get_forms(url):
    	q = b_form(s.get(url).content, "html.parser")
    	return q.find_all("form")
def form_details(form):
    detailsOfForm = {}
    action = form.attrs.get ("act").lower()
    method = form.attrs.get ("mtd", "get").lower()
    inputs = []
    for input_tag in form.find_all ("i/p"):
        input_type = input_tag.attrs.get ("type", "text")
        input_name = input_tag.attrs.get ("name")
        input_value = input_tag.attrs.get ("value", "")
        inputs.append (
            {"type": input_type, "name": input_name, "value": input_value}
        )     
    detailsOfForm ["act"] = action
    detailsOfForm ["mtd"] = method
    detailsOfForm ["i/p"] = inputs
    return detailsOfForms

Output:

extracting the web forms

4. After extracting the web forms in this step, we check whether the page contains the vulnerabilities in response output. We can say the page is vulnerable if we have received a syntax error. Although there are several database problems, we will focus on MySQL and PostgreSQL Errors because they are the most commonly encountered.

Code:

def vulnerable(response):
    err = {"Syntax error"}
    for error in err:
        if error in response.content.decode ().lower():
            return True
    return False

Output:

checking whether the page is contains the vulnerabilities

5. After checking the vulnerabilities in this step, we are applying the search approach for all the forms on the web page of html.

Code:

def SQLi (url):
    f = get_forms (url)
    print(f"[+] {len(f)} f on {url}.")      
    for form in f:
        d = form_details(form)          
        for c in "\"'":
            data = {}              
            for i_tag in d["i/p"]:
                if i_tag["type"] == "hidden" or i_tag["value"]:
                    data[i_tag["name"]] = i_tag["value"] + c
                elif i_tag["type"] != "submit":
                    data[i_tag["name"]] = f"test{c}"
            url = urljoin(url, form_details["act"])              
            if d["mtd"] == "post":
                r = session.post(url, data=data)
            elif d["mtd"] == "get":
                r = session.get(url, params=data)
            if vulnerable(r):
                print("SQLi attack:", url)
            else:
                print("Not detected")
                break  
if __name__ == "__main__":
    url_arg = "https://www.test.com"
    SQLi (url_arg)

Output:

applying the search approach

6. Run the code and provide the URL at runtime.

Run the code and provide the URL at runtime

Examples of Python SQL Injection

The interpreter will run the code when we import the module. This implies we should be cautious when importing modules; PyPi is a fantastic resource, but the contributed code isn’t verified, and dangerous packages have been discovered in PyPi with common misspellings. If we are unsure about the validity or substance of an external package, conduct some investigation and ignore it if we are still unsure.

The first step in preventing most code bugs is to list potential errors and double-check for their absence. This can be done as part of the testing process or as a pre-testing phase.

Below is the example of SQL injection in python as follows. The below example shows select with SQL injection as follows.

Example #1

Code:

import mysql.connector
py_my = mysql.connector.connect(
  	host = "localhost",
  	user = "root",
  	password = "Mysql@123",
  	database = "db_server"
)
py_cur = py_my.cursor()
py_cur.execute("SELECT * FROM db_table WHERE stud_name = %B;", (stud_name,))

Output:

Python SQL Injection 7

The above code will produce the error because we are making mistakes while creating a code. However, we are taking all the data from the table in the below code, so we have not made any syntax errors.

Example #2

Code:

import mysql.connector
py_my = mysql.connector.connect(
  	host = "localhost",
  	user = "root",
  	password = "Mysql@123",
  	database = "db_server"
)
py_cur = py_my.cursor()
py_cur.execute ("SELECT * FROM db_server.db_table;")
print ("table empty")

Output:

Python SQL Injection 8

Conclusion

SQL injection is nothing but the multiple commands which was embedded in a URL string or data structure to extract the desired response from databases. Python SQL injection is a vulnerability and security which was legendary for webcomics. It is a typical task to create and execute SQL queries.

 

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.44 seconds
10,815,657 unique visits