Blog | G5 Cyber Security

SSH Brute Force with Key Pairs

TL;DR

Brute-forcing SSH accounts using key pairs is generally ineffective and slow due to the nature of public/private key cryptography. However, it’s possible if you have a list of potential private keys. This guide outlines how to attempt this (for legitimate penetration testing purposes only) and highlights why it’s usually impractical.

How SSH Key Authentication Works

SSH key authentication relies on cryptographic proof. The server doesn’t ‘guess’ the key; it verifies that you possess the correct private key corresponding to a public key already authorized on the system. This makes traditional brute-forcing (trying many passwords) inapplicable.

Attempting Key Pair Brute Force

  1. Gather Potential Private Keys: This is the hardest part. You need a list of private keys that might be used to access the server. These could come from compromised backups, leaked data, or previous employee accounts. Without this list, brute-forcing is impossible.
  2. Prepare a Key List File: Create a text file (e.g., keys.txt) with one private key per line. Each line should contain the full path to the private key file.
    /home/user/.ssh/id_rsa
    /root/.ssh/another_key
    /opt/backup/.ssh/old_key
    
  3. Use a Brute-Force Tool: Several tools can attempt to connect using the keys in your list. ssh-keyscan and custom scripts are common options.

    Using ssh-keyscan (for authorized_keys): This isn’t direct brute-forcing, but it helps identify if any of your potential public keys *are already* on the server. It won’t test private key validity.

    ssh-keyscan user@target_host > known_hosts
    
  4. Custom Script (Example – Python): A more effective approach involves writing a script to iterate through the keys and attempt connections.
    import subprocess
    
    with open('keys.txt', 'r') as f:
        for key in f:
            key = key.strip()
            try:
                subprocess.run(['ssh', '-i', key, 'user@target_host'], check=True)
                print(f'Success with key: {key}')
                break # Stop on first successful connection
            except subprocess.CalledProcessError as e:
                print(f'Failed with key: {key} - {e}')
    

    Important: Replace user@target_host with the actual username and hostname.

  5. Run the Script: Execute your Python script (or equivalent) to start the brute-force attempt.
    python brute_ssh.py
    
  6. Monitor Results: The script will output success or failure messages for each key it tries.

Why This is Usually Impractical

Ethical Considerations

Attempting to gain unauthorized access to any system is illegal and unethical. This guide is for educational purposes only and should only be used with explicit permission from the system owner as part of a legitimate penetration testing exercise.

Exit mobile version