Skip to main content
Create your own
Lesson illustration

Python Exploit Scripting for Web Vulnerabilities

Hello! Welcome to your lesson on scripting exploits.

In our previous lessons, we've explored a range of advanced web vulnerabilities, from exploiting GraphQL APIs to bypassing security controls. Finding these vulnerabilities is a critical skill, but to truly demonstrate their impact and operate efficiently as a professional, you need to be able to automate their exploitation. This is where your computer science background and Python skills become a significant advantage.

Today's lesson is dedicated to bridging the gap between manual discovery and automated exploitation. We will focus on the learning outcome: Use Python to script a proof-of-concept (PoC) exploit for a discovered web vulnerability. You will learn how to take a vulnerability you've identified and write a Python script to reliably and repeatably trigger it, creating a tangible PoC that is essential for penetration testing reports and bug bounty submissions.

1. From Manual Discovery to an Exploit Script

As a professional, you'll often need to provide a PoC script to development or security teams who may not be familiar with tools like Burp Suite. A standalone script is an unambiguous way to demonstrate a vulnerability's impact. A common and highly effective workflow is to translate a request from your testing tool into code.

Writing API exploits in Python

To understand this professional workflow, let's start with the article 'Writing API exploits in Python' from Dana Epp's blog. It perfectly explains the rationale and the process.

Please read the following sections: 'Our vuln found in Burp Suite': This sets the context. 'Extract Burp request to cURL command': This shows the first crucial step of getting the request out of Burp Suite. 'Convert cURL command to Python': This introduces curlconverter, a powerful tool that automates the translation from a cURL command into Python code using the requests library. Focus on the workflow: Burp Suite → cURL command → curlconverter → Python script. This is a massive time-saver in practice.

This workflow gives you a fantastic starting point for any exploit script. The curlconverter tool handles the tedious work of structuring the headers, parameters, and data, leaving you to focus on the exploit logic itself.

2. Case Study: Scripting a Command Injection Vulnerability

Let's apply this to a classic vulnerability: OS command injection. Imagine you are testing a web application with a ping utility, like the one in Damn Vulnerable Web Application (DVWA).

DVWA Command Execution Vulnerability Demonstration
A typical web form that executes a system command. Such inputs are prime candidates for command injection.

Manually, you might test a payload like 127.0.0.1 | whoami to see if you can chain a command. If it works, the next step is to script it. This involves three main steps:

  1. Handling authentication to access the vulnerable page.
  2. Sending the malicious payload to the correct endpoint and parameter.
  3. Analyzing the response to confirm the exploit's success.

The requests library in Python is the standard for this. A key feature for exploit scripting is the requests.Session object, which automatically handles cookies and allows you to maintain a logged-in state across multiple requests.

How to Exploit Command Injection Vulnerabilities in Python

The article 'How to Exploit Command Injection Vulnerabilities in Python' provides a complete walkthrough of scripting an exploit for this exact DVWA scenario.

Read the sections that cover the Python implementation: Start from where the Python code begins, after the manual exploitation part. Observe how requests.Session() is used to log in and maintain the session. Analyze the check_command_injection function. See how it constructs the POST request with the payload in the form_data dictionary. Finally, review the section on automating with multiple payloads using a for loop. This demonstrates how to turn a simple PoC into a more versatile scanner.

Test your understanding!

You've discovered a blind SQL injection vulnerability on a page that requires authentication. The exploit requires sending a POST request to /api/search with a JSON body. The malicious payload needs to be in the query field of the JSON object. You have already logged in and have a valid requests.Session object named s.

How would you use the session object to send the payload ' OR 1=1--?

Show answer

You would use the s.post() method, specifying the endpoint and using the json parameter to automatically format the dictionary and set the Content-Type header to application/json.

import requests

# Assume 's' is an existing, authenticated requests.Session object
# s = requests.Session()
# s.post(login_url, data=login_credentials) 

target_url = "https://vulnerable.site/api/search"
payload = {"query": "' OR 1=1--"}

response = s.post(target_url, json=payload)

# You would then analyze the response to see if the injection was successful
print(response.status_code)
print(response.text)

Using the json parameter is the correct way to send JSON data, as opposed to the data parameter which is used for form-data.

3. Advanced Case Studies: RCE and Multi-Step API Exploits

While command injection is a great starting point, real-world exploits can be more complex. They might involve multiple steps, specific header requirements, and different data formats. Let's look at two video walkthroughs that demonstrate scripting more advanced Remote Code Execution (RCE) vulnerabilities.

Example 1: RCE via Command Injection

This first video shows how to script an exploit for a known Webmin vulnerability. It's a great example of handling authentication and correctly encoding a payload to achieve a reverse shell.

Stop Being a Skid ! Can You Hack a WebApp With an Exploit You Made ? 💬 PoC Scripting - RCE | THM

Watch this video 'Stop Being a Skid ! Can You Hack a WebApp With an Exploit You Made ?' by Hox Framework. It's a concise walkthrough of scripting an RCE exploit.

Pay close attention to these key steps: (00:26 - 00:58): Understanding the vulnerability (a pipe character | allows command injection). (03:03 - 03:46): Using requests.Session() to handle login and maintain the session, which simplifies cookie management. (04:17 - 05:14): Constructing the payload and, crucially, using urllib.parse.quote to URL-encode it. This ensures special characters in your reverse shell payload are correctly interpreted by the server. (05:06 - 05:30): Running the script and catching the reverse shell.

Example 2: RCE via a Multi-Step API Exploit

This second example from John Hammond is more intricate. It involves chaining a path traversal vulnerability with a file upload vulnerability to achieve RCE. Scripting is almost essential here to perform the multiple steps in sequence.

How To Hack APIs with Python

Now, let's watch 'How To Hack APIs with Python' by John Hammond. This demonstrates a more complex, real-world scenario of scripting a multi-step API exploit.

This video details the entire process from research to exploitation. Focus on the Python scripting parts: (02:49 - 09:23): First, understand the vulnerability: a path traversal flaw allows creating a .ssh directory, and a weak regex in the file upload allows placing an authorized_keys file inside it. (09:38 - 14:10): See how the script handles login. Note that instead of form data, it parses a JSON response to get session tokens and then adds them to the session's cookie jar. (14:10 - 16:41): Watch the scripting of the first part of the chain: creating the .ssh directory using the path traversal vulnerability. This part also shows how to add custom headers (X-Token, X-CID) required by the API. (16:41 - 19:39): Observe the scripting of the second part: uploading your public SSH key. This uses the files parameter in requests, which is specifically designed for multipart/form-data file uploads. (19:39 - 21:15): The final step: using the uploaded key to gain SSH access and achieve RCE.

4. Professionalizing Your Scripts with Argument Parsing

The scripts generated by curlconverter are functional, but for professional use, you should make them more flexible. Hardcoding target URLs or user credentials is bad practice. The argparse module in Python is the standard way to create command-line interfaces for your scripts, allowing you or another user to easily change targets or parameters without editing the code.

This aligns with your goal of thinking like a software architect—building tools that are reusable and well-structured.

Writing API exploits in Python

Let's revisit Dana Epp's blog post to see how to improve the generated code.

Read the section 'Clean up the code'. It shows how to refactor the simple script to use argparse, allowing the target IP and vulnerable ID to be passed as command-line arguments. Also, notice the use of an f-string to construct the URL dynamically.

By parameterizing your scripts, you create a robust PoC that can be easily used by a client to verify the vulnerability in their own environment.

Conclusion

You've now learned the end-to-end process of turning a discovered vulnerability into a powerful, reusable proof-of-concept script. This skill separates you from beginners and is fundamental to being an effective penetration tester and bug bounty hunter. It not only proves impact but also enables you to automate testing and build a personal arsenal of security tools.

Key Takeaways:

  • Standard Workflow: A highly efficient way to start is Burp Suite → Copy as cURL → curlconverter → Python.
  • Handle State with Sessions: Use requests.Session() to manage authentication and cookies across the multiple requests often needed for an exploit.
  • Master the requests Library: Understand the difference between the data (for forms), json (for JSON APIs), and files (for uploads) parameters.
  • Encode Your Payloads: Use libraries like urllib.parse to properly encode payloads to prevent misinterpretation by the web server or application.
  • Write Professional Code: Use argparse to make your scripts flexible and reusable, avoiding hardcoded values.

Next Lesson Preview:

In our next lesson, we will tackle one of the most creative and impactful topics in offensive security: vulnerability chaining. You'll learn how to combine multiple, separate vulnerabilities—like an SSRF and a command injection—into a sequence that achieves a much higher impact than any single flaw. The scripting skills you've honed today will be directly applicable, as automating these complex chains is often the only way to execute them effectively.

Can't find a good explanation? Sign up and we'll make it for you

Sign up