Skip to content

Instantly share code, notes, and snippets.

@chak10
Last active November 10, 2024 13:04
Show Gist options
  • Save chak10/325dc16df4ce8a41020277669998bef8 to your computer and use it in GitHub Desktop.
Save chak10/325dc16df4ce8a41020277669998bef8 to your computer and use it in GitHub Desktop.
This Python script attempts a brute-force attack on a password-protected RAR file by generating all possible password combinations up to a specified length and testing each one using 7-Zip, leveraging multiprocessing for improved performance.

RAR Password Brute-Force

This Python script performs a brute-force attack to find the password of a password-protected RAR file. It generates all possible password combinations up to a specified length and attempts to extract the contents of the RAR file using 7-Zip. The script uses multiprocessing to speed up the process by running multiple password attempts in parallel.

Features

  • Brute-Force Attack: Attempts to crack a password-protected RAR file by testing all possible password combinations up to a specified length.
  • 7-Zip Integration: Uses 7-Zip (7z.exe) to attempt password extraction from the RAR file.
  • Multiprocessing: Utilizes multiple CPU cores to accelerate the brute-force process.
  • Logging: Logs successful and failed attempts, along with errors, into a log file for monitoring progress.
  • Customizable Parameters: Set the maximum password length and the characters used for password generation.

Requirements

  • Python 3.x
  • 7-Zip (7z.exe) installed on your system. Download 7-Zip
  • Windows OS or a system that supports 7-Zip command-line tool.

Install Python Dependencies

Install the required Python libraries with the following command:

pip install -r requirements.txt

The required dependencies are:

  • itertools
  • string
  • subprocess
  • multiprocessing

Setup

  1. Download and Install 7-Zip:
    Download and install 7-Zip if it is not already installed on your system. Make sure the executable 7z.exe is in your system's PATH or provide the absolute path to the 7z.exe file in the script.

  2. Configure the Script:
    Modify the following variables in the script to point to your RAR file and 7-Zip executable:

    rar_file_path = "path/to/your/file.rar"
    seven_zip_path = r"C:\Program Files\7-Zip\7z.exe"
  3. Run the Script:
    Execute the script with the following command:

    python brute_force_rar.py

    The script will start generating and testing password combinations, logging progress and results.

Parameters

  • max_password_length: Set the maximum password length to test.
  • characters: Define the character set to use for generating passwords. The default set includes uppercase and lowercase letters and digits.

Logging

  • Logs are stored in a file named bruteforce_rar.log.
  • The log file records:
    • Successful password attempts.
    • Failed attempts.
    • Any errors that occur during the brute-force process.

Example

$ python brute_force_rar.py
2024-11-09 21:36:07,401 - INFO - Starting brute-force attack on RAR file.
Password found: abc123
2024-11-09 21:36:09,589 - INFO - Correct password found: abc123

Notes

  • Performance: The script uses multiprocessing to utilize multiple CPU cores, speeding up the brute-force process. You can adjust the number of processes used by modifying the script.
  • 7-Zip: The script uses 7-Zip’s command-line tool for extraction. Ensure that 7-Zip is correctly installed and accessible from your system’s PATH.

License

This project is licensed under the MIT License.


This README.md provides an overview of the project, how to set it up, and its usage, along with installation instructions for any dependencies. Feel free to adapt and expand it based on your specific needs.

import subprocess
import itertools
import string
import time
import os
import logging
from multiprocessing import Pool, cpu_count, Manager
# Configurazione dei logger
logger = logging.getLogger()
# Crea handler per la console (mostra solo INFO e superiori)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) # Mostra solo INFO e superiori sulla console
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
# Crea handler per il file di log (mostra solo ERROR e CRITICAL nel file)
file_handler = logging.FileHandler('bruteforce_rar.log')
file_handler.setLevel(logging.ERROR) # Mostra solo ERROR e CRITICAL nel file
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)
# Aggiungi gli handler al logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# Imposta il livello del logger globale
logger.setLevel(logging.INFO)
# Percorso del file RAR e dell'eseguibile 7-Zip
rar_file_path = "rar.rar"
output_folder = "output" # Cartella di destinazione
seven_zip_path = r"C:\Program Files\7-Zip\7z.exe" # Percorso di 7z.exe
# Lunghezza massima della password e set di caratteri
max_password_length = 8
characters = string.ascii_letters + string.digits
# Verifica che il percorso dell'eseguibile e del file RAR esistano
if not os.path.exists(seven_zip_path):
logger.error(f"L'eseguibile 7z.exe non è stato trovato nel percorso specificato: {seven_zip_path}")
raise FileNotFoundError(f"L'eseguibile 7z.exe non è stato trovato nel percorso specificato: {seven_zip_path}")
if not os.path.exists(rar_file_path):
logger.error(f"Il file RAR non è stato trovato: {rar_file_path}")
raise FileNotFoundError(f"Il file RAR non è stato trovato: {rar_file_path}")
def try_password(password):
"""Funzione per tentare di estrarre il file RAR con una password specifica."""
command = [seven_zip_path, 'x', rar_file_path, f'-o{output_folder}', f'-p{password}', '-y']
try:
# Esegui il comando
result = subprocess.run(command, capture_output=True, text=True, timeout=10)
# Controllo dell'output per vedere se la password è corretta
if "Everything is Ok" in result.stdout:
print(f"Password trovata: {password}")
logger.info(f"Password corretta trovata: {password}")
return password
else:
logger.info(f"Tentativo fallito: {password}")
except subprocess.TimeoutExpired:
logger.warning(f"Tentativo con la password {password} scaduto (timeout).")
except subprocess.CalledProcessError as e:
logger.error(f"Errore durante l'esecuzione del comando con password {password}: {e}")
except Exception as e:
logger.error(f"Errore imprevisto con la password {password}: {e}")
return None
def generate_passwords(max_len):
"""Genera tutte le combinazioni di password fino a max_len, una per volta."""
for length in range(1, max_len + 1):
for password_tuple in itertools.product(characters, repeat=length):
yield ''.join(password_tuple)
def chunk_passwords(password_gen, chunk_size):
"""Genera blocchi di password per il multiprocessing."""
chunk = []
for password in password_gen:
chunk.append(password)
if len(chunk) == chunk_size:
yield chunk
chunk = []
if chunk:
yield chunk
def brute_force_rar_multiprocessing(max_len):
# Creazione della cartella di output, se non esiste
os.makedirs(output_folder, exist_ok=True)
try:
# Numero di processi da usare, limitato al numero di CPU disponibili
num_processes = min(cpu_count(), 16) # Usa il massimo numero di processi della tua CPU (16 core)
# Genera le password e dividile in blocchi per i processi
password_gen = generate_passwords(max_len)
password_chunks = chunk_passwords(password_gen, 20000) # 20.000 password per blocco (aumentato)
with Manager() as manager:
# Gestione della coda per passare i batch ai processi
pool = Pool(processes=num_processes)
# Processa ogni blocco di password
for password_chunk in password_chunks:
results = pool.map(try_password, password_chunk)
# Verifica se è stata trovata la password corretta
for result in results:
if result:
pool.terminate() # Ferma il pool se la password è stata trovata
return result
pool.close()
pool.join()
except Exception as e:
logger.critical(f"Errore critico durante il brute-force: {e}")
return None
if __name__ == '__main__':
# Se il programma viene eseguito come script principale, avvia il brute-force
start_time = time.time()
logger.info("Inizio dell'attacco brute-force al file RAR")
password = brute_force_rar_multiprocessing(max_password_length)
if password:
print(f"Password corretta trovata: {password}")
logger.info(f"Password corretta trovata: {password}")
else:
print("Password non trovata.")
logger.info("Password non trovata.")
elapsed_time = time.time() - start_time
print(f"Tempo impiegato: {elapsed_time:.2f} secondi")
logger.info(f"Tempo totale impiegato: {elapsed_time:.2f} secondi")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment