Use John the Ripper to Crack SSH Private Keys

Kali LinuxBeginner
Practice Now

Introduction

SSH (Secure Shell) keys are a secure way to authenticate to remote servers, offering a more robust alternative to password-based logins. For added security, an SSH private key can be encrypted with a passphrase. If an attacker gains access to your private key file, they still need the passphrase to use it.

However, a weak passphrase can be a significant vulnerability. In this lab, you will step into the shoes of a security analyst to understand this risk. You will learn how to use John the Ripper, a powerful open-source password cracking tool, to crack the passphrase of an SSH private key. This exercise is for educational purposes to highlight the importance of using strong passphrases.

Generate a Password-Protected SSH Private Key

In this step, you will generate a new SSH key pair. The private key will be protected with a simple, easy-to-guess passphrase. This key will serve as the target for our cracking exercise in the subsequent steps.

We will use the ssh-keygen command to create the key. We'll specify the key type, bit size, and filename to ensure it's created within our project directory.

Execute the following command to generate an RSA SSH key pair. When prompted for a passphrase, enter labex.

ssh-keygen -t rsa -b 2048 -f ./my_ssh_key -C "labex@labex.io"

You will be prompted to enter and confirm a passphrase. Type labex and press Enter for both prompts.

Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): labex
Enter same passphrase again: labex
Your identification has been saved in ./my_ssh_key
Your public key has been saved in ./my_ssh_key.pub
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx labex@labex.io
The key's randomart image is:
+---[RSA 2048]----+
|        .        |
|       . .       |
|      .   .      |
|     . . . .     |
|    . . S .      |
|   . . . o       |
|  . . . + .      |
| . . . =.o.o     |
|..  .oo*+E+      |
+----[SHA256]-----+

Now, list the files in the current directory to see the newly created key pair: the private key my_ssh_key and the public key my_ssh_key.pub.

ls -l
total 12
-rw------- 1 labex labex 1823 Jan 01 12:00 my_ssh_key
-rw-r--r-- 1 labex labex  401 Jan 01 12:00 my_ssh_key.pub
-rw-r--r-- 1 labex labex   48 Jan 01 12:00 wordlist.txt

You have successfully created a password-protected SSH private key.

Extract Hash from SSH Key using ssh2john

John the Ripper cannot work directly with the SSH key file format. It requires a specific hash format that represents the encrypted passphrase. To get this hash, we will use a utility called ssh2john, which is included with the John the Ripper suite.

In this step, you will run ssh2john on the private key you created (my_ssh_key) and save its output to a new file. This file will contain the hash that john can then attempt to crack.

Run the following command to extract the hash and save it to a file named ssh_hash.txt:

ssh2john my_ssh_key > ssh_hash.txt

This command produces no output in the terminal because we redirected it to the ssh_hash.txt file using the > operator.

To see the content of the generated hash file, use the cat command:

cat ssh_hash.txt

You will see a long string of text, which is the hash representation of your key's passphrase. It will look something like this:

my_ssh_key:$ssh2$0$16$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$1040$xxxxxxxx...

Now you have the hash file ready for the cracking process.

Crack SSH Key Hash with John the Ripper

With the hash extracted, it's time to use John the Ripper to crack it. We will perform a "dictionary attack," where john tries every word from a given list as a potential passphrase. For this lab, we will use the wordlist.txt file that was pre-created in your environment.

In a real-world scenario, attackers use massive wordlists containing millions of common passwords, names, and dictionary words. Our simple wordlist contains the correct passphrase, labex, ensuring the crack will be successful for this demonstration.

Run the john command, specifying the wordlist and the hash file:

john --wordlist=wordlist.txt ssh_hash.txt

John will start the cracking process. Since the passphrase is in our short wordlist, it will be found almost instantly.

Using default input encoding: UTF-8
Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH private keys ssh2john])
Cost 1 (KDF/cipher) is 0 for all loaded hashes
Cost 2 (iteration count) is 16 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
labex            (my_ssh_key)
1g 0:00:00:00 DONE (2023-01-01 12:05) 12.50g/s 12.50p/s 12.50c/s 12.50C/s sunshine..labex
Use the "--show" option to display all of the cracked passwords reliably
Session completed

Success! The output line labex (my_ssh_key) shows that the passphrase labex was successfully recovered for the key my_ssh_key.

John the Ripper saves cracked passwords in a file called a "pot file" (~/.john/john.pot by default). To view the cracked password again without re-running the attack, you can use the --show option:

john --show ssh_hash.txt
my_ssh_key:labex

1 password hash cracked, 0 left

This confirms the cracked passphrase. You have now successfully cracked an SSH key's weak passphrase.

Understand SSH Key Security

This lab demonstrates a critical point: the security of a passphrase-protected SSH key is only as strong as the passphrase itself. Let's break down the components of SSH key security.

  • Key Strength (Cryptography): This refers to the algorithm (e.g., RSA, ECDSA, Ed25519) and the key size (e.g., 2048, 4096 bits) used to generate the key. A larger key size makes it exponentially harder for an attacker to break the underlying cryptography through brute force. This protects against attacks trying to derive the private key from the public key.

  • Passphrase Strength (Encryption): This protects the private key file itself. When you set a passphrase, the private key file is encrypted. If someone steals this file, they cannot use it without decrypting it first. As you've seen, a weak, common, or dictionary-based passphrase can be cracked easily. A strong passphrase should be long, complex, and unique, making a dictionary or brute-force attack computationally infeasible.

  • File Permissions (Access Control): Your operating system's file permissions provide the first line of defense. A private key file should always have permissions that restrict access to only the owner (e.g., 600 or -rw-------). This prevents other users on the same system from reading the key file.

In our lab, the cryptographic strength of the key was irrelevant because the attack vector was not the cryptography itself, but the weak passphrase used to encrypt the file.

Best Practices for SSH Key Management

Understanding the risks is the first step. Applying best practices is how you mitigate them. Here are essential rules for managing your SSH keys securely in a real-world environment.

  • Use Strong, Unique Passphrases:

    • Never use common words, names, or simple patterns.
    • A strong passphrase should be long (15+ characters) and contain a mix of uppercase letters, lowercase letters, numbers, and symbols.
    • Consider using a password manager to generate and store highly complex passphrases.
  • Use Modern Algorithms and Adequate Key Sizes:

    • Prefer modern algorithms like Ed25519 or ECDSA over the older RSA. They offer better security and performance.
    • If using RSA, ensure a key size of at least 2048 bits, with 4096 bits being recommended for long-term security.
  • Secure Private Key Files:

    • Always ensure your private key files (e.g., ~/.ssh/id_rsa) have strict file permissions. Use chmod 600 to allow read/write access for your user only.
  • Use an SSH Agent:

    • An SSH agent (ssh-agent) is a background program that caches your decrypted private keys in memory. You enter your passphrase once when you add the key to the agent, and you won't have to type it again for the duration of your session. This is both convenient and secure, as the passphrase is not repeatedly typed or stored on disk.
  • Regularly Rotate Keys:

    • Periodically generate new SSH key pairs and decommission old ones. This limits the window of opportunity for an attacker if an old key is ever compromised.
  • Never Share Private Keys:

    • A private key is private. It is your unique identity. Never send it over email, chat, or any other medium. If another person needs access, they should generate their own key pair and provide you with their public key.

Summary

In this lab, you gained hands-on experience with a common security auditing task. You have successfully:

  • Generated a new SSH key pair protected by a passphrase.
  • Used the ssh2john utility to extract a crackable hash from the private key file.
  • Performed a dictionary attack using John the Ripper to crack the weak passphrase.
  • Learned the fundamental principles of SSH key security, including the distinct roles of cryptographic strength and passphrase strength.
  • Reviewed the essential best practices for secure SSH key management.

This exercise demonstrates that even strong cryptographic tools can be undermined by weak human practices. Always protect your SSH keys with strong, unique passphrases to ensure the integrity of your digital identity.