> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-11/offline-cracking/archive/trick-0574.md).

# Brute-force Password-Protected Zips

***

Automate the process of cracking multiple password-protected ZIP files using a dictionary list and then extracting their contents. This is particularly useful when a password list is recovered from forensic analysis or during CTF challenges.

A Python script can iterate through all ZIP files in a directory, attempt to crack them with `fcrackzip` using a specified dictionary, extract the contents upon success using `unzip` and the found password, and finally search the extracted files for a specific flag pattern.

The process involves using external command-line tools via Python's `subprocess` module. The primary tools are `fcrackzip` for password cracking and `unzip` for extraction.

```python
import os
import subprocess
import re

def crack_and_extract(zip_file, passwords_file, output_dir):
    """Cracks a single zip file and extracts if successful."""
    try:
        print(f"Attempting to crack {zip_file}...")
        # Use fcrackzip for dictionary attack
        # -v: verbose output
        # -u: try to unzip the file with the found password
        # -D / -p <file>: use a dictionary file
        result = subprocess.run(
            ["fcrackzip", "-v", "-u", "-D", "-p", passwords_file, zip_file],
            capture_output=True,
            text=True,
            errors="ignore" # Handle potential decoding issues in output
        )

        password = None
        # Parse the output to find the password line
        for line in result.stdout.splitlines():
            # Look for the password found line, which typically contains "PASSWORD FOUND"
            if "PASSWORD FOUND" in line:
                # Extract the password after "=="
                password = line.split("==")[-1].strip()
                print(f"Password found for {zip_file}: {password}")
                break

        if password:
            print(f"Extracting {zip_file} to {output_dir}...")
            # Use unzip with the found password
            # -P <password>: use password
            # -d <directory>: extract files into <directory>
            subprocess.run(
                ["unzip", "-P", password, zip_file, "-d", output_dir],
                check=True # Raise error if extraction fails
            )
            print("Extraction successful.")
            return password
        else:
            print(f"Could not crack {zip_file} with the provided dictionary.")

    except subprocess.CalledProcessError as e:
         print(f"Extraction failed for {zip_file}: {e}")
    except FileNotFoundError:
        print("Error: Ensure 'fcrackzip' and 'unzip' are installed and in your PATH.")
    except Exception as e:
        print(f"An unexpected error occurred with {zip_file}: {e}")

    return None

def search_for_flags(search_dir, flag_pattern):
    """Searches extracted files for a flag pattern."""
    flags_found = []
    print(f"Searching for flags matching '{flag_pattern}' in {search_dir}...")
    for root, dirs, files in os.walk(search_dir):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                # Attempt to read the file, ignoring encoding errors
                with open(file_path, "r", errors="ignore") as f:
                    content = f.read()
                    flags = re.findall(flag_pattern, content)
                    if flags:
                        print(f"Found flags in {file_path}")
                        flags_found.extend(flags)
            except Exception as e:
                print(f"Error reading file {file_path}: {e}")
    return flags_found

# --- Example Usage ---
# Define parameters:
# directory = "./" # Directory containing the zip files
# passwords_file = "passwords.txt" # Path to the dictionary file
# extracted_files_dir = "extracted_files" # Directory to extract files into
# flag_pattern = r"Shaastra\{.*?\}" # Regex pattern for flags (e.g., CTF{...}, flag{...})

# Create output directory if it doesn't exist
# os.makedirs(extracted_files_dir, exist_ok=True)

# Process each zip file in the target directory
# for file in os.listdir(directory):
#     if file.endswith(".zip"):
#         zip_file_path = os.path.join(directory, file)
#         crack_and_extract(zip_file_path, passwords_file, extracted_files_dir)

# Search for flags in all extracted content
# found_flags = search_for_flags(extracted_files_dir, flag_pattern)

# Print results
# if found_flags:
#     print("\n--- Flags found ---")
#     for flag in found_flags:
#         print(flag)
# else:
#     print("\nNo flags found.")
```

The `fcrackzip` command is used for the dictionary attack. Common options include:

* `-v`: Enable verbose output, showing progress.
* `-u`, `--unzip`: Attempt to unzip the file with the found password.
* `-D <file>`, `-p <file>`, `--dictionary <file>`, `--password <file>`: Specify the dictionary file containing passwords to try, one per line.

When a password is found, `fcrackzip` typically outputs a line containing "PASSWORD FOUND" followed by the password, often in the format `PASSWORD FOUND: == <password>`. The script parses this output to extract the password.

Once the password is known, the `unzip` command is used to extract the contents. Key options for `unzip` are:

* `-P <password>`: Provide the password for decryption.
* `-d <directory>`: Specify the destination directory where files should be extracted. Without `-d`, files are extracted to the current directory.

The script then iterates through the extracted files and searches for a specific pattern using Python's `re` module, which is useful for finding flags in CTF challenges.

Replace the example usage variables (`directory`, `passwords_file`, `extracted_files_dir`, `flag_pattern`) with the specific paths and patterns relevant to the CTF challenge. The script requires `fcrackzip` and `unzip` to be installed and available in your system's PATH. The `passwords.txt` file should contain one password per line.
