Blog | G5 Cyber Security

Secure SSH with Key Pairs

TL;DR

Disable password authentication for SSH and use SSH key pairs instead. This is much more secure than passwords.

How to Secure SSH Access

  1. Generate an SSH Key Pair: On your local machine (the one you’ll be connecting *from*), open a terminal or command prompt.
    • If you don’t already have one, create a new key pair using the following command:
      ssh-keygen -t rsa -b 4096
    • You’ll be prompted for a file to save the key. The default (~/.ssh/id_rsa) is usually fine. Press Enter to accept it.
    • You’ll also be asked for a passphrase. Strongly recommend setting one! This adds an extra layer of security even if your private key file is compromised.
  2. Copy the Public Key to the Server: You need to get the contents of your public key (~/.ssh/id_rsa.pub) onto the server you want to connect to.
    • The easiest way is often using ssh-copy-id:
      ssh-copy-id user@your_server_ip

      (Replace ‘user’ with your username on the server and ‘your_server_ip’ with the server’s address.)

    • You will be prompted for the server password one last time. This command appends your public key to the ~/.ssh/authorized_keys file on the server.
    • If ssh-copy-id isn’t available, you can manually copy and paste the contents of ~/.ssh/id_rsa.pub into the ~/.ssh/authorized_keys file on the server (using a text editor like nano or vim).
  3. Disable Password Authentication: This is the crucial step.
    • Connect to your server using SSH (you might still need your password for this one time):
      ssh user@your_server_ip
    • Edit the SSH daemon configuration file. Usually located at /etc/ssh/sshd_config:
      sudo nano /etc/ssh/sshd_config
    • Find these lines and change them as follows:
      • PasswordAuthentication no
      • ChallengeResponseAuthentication no (if present, set to ‘no’)
    • Save the file (Ctrl+X, Y, Enter in nano).
    • Restart the SSH service:
      sudo systemctl restart sshd

      (or sudo service ssh restart on older systems)

  4. Test Your Connection: Try connecting to your server again.
    • You should now be prompted for the passphrase you set when generating the key pair, *not* your password. If it works, congratulations!
      ssh user@your_server_ip
  5. Optional: Further Security Measures
    • Change SSH Port: Change the default port (22) to a non-standard port in /etc/ssh/sshd_config. This reduces automated attacks.
    • Disable Root Login: In /etc/ssh/sshd_config, set PermitRootLogin no.
    • Use Fail2Ban: Install and configure Fail2Ban to automatically block attackers who repeatedly fail login attempts.
Exit mobile version