Get a Pentest and security assessment of your IT network.

Cyber Security

SSH Public Key Authentication

TL;DR

Yes, you can initiate an SSH session using a public key instead of a password. This is more secure and convenient. Here’s how to set it up.

Setting Up SSH Public Key Authentication

  1. Generate an SSH Key Pair: If you don’t already have one, create a new SSH key pair on your local machine (the computer you are connecting *from*). Open your terminal and run:
    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. You can also set a passphrase for extra security (recommended).

  2. Copy Your Public Key to the Server: There are several ways to do this.
    • Using ssh-copy-id (easiest): If you have password access to the server, use:
      ssh-copy-id user@server_ip_address

      You’ll be prompted for the server’s password.

    • Manually Copying (if ssh-copy-id isn’t available):
      • Display your public key:
        cat ~/.ssh/id_rsa.pub
      • Copy the entire output of this command.
      • Connect to the server using password authentication (e.g., ssh user@server_ip_address).
      • Edit the ~/.ssh/authorized_keys file on the *server*.
        nano ~/.ssh/authorized_keys
      • Paste your public key into this file on a new line. Save and close the file. If the .ssh directory or authorized_keys file doesn’t exist, create them:
        • mkdir -p ~/.ssh
        • chmod 700 ~/.ssh
        • touch ~/.ssh/authorized_keys
        • chmod 600 ~/.ssh/authorized_keys
  3. Test the Connection: Try connecting to the server again:
    ssh user@server_ip_address

    If everything is set up correctly, you should be logged in without being prompted for a password. If it still asks for a password, see the troubleshooting section below.

Troubleshooting

  • Permissions: Make sure the ~/.ssh directory has permissions of 700 (drwx——) and the ~/.ssh/authorized_keys file has permissions of 600 (-rw——-).
  • Correct Public Key: Double-check that you copied the *public* key (id_rsa.pub), not the private key (id_rsa).
  • Authorized Keys File: Ensure your public key is on a single line in the authorized_keys file, with no extra characters or spaces.
  • SSH Server Configuration: Verify that the SSH server configuration allows public key authentication.
    • Edit /etc/ssh/sshd_config (you’ll need root privileges).
    • Make sure these lines are set to ‘yes’:
      • PubkeyAuthentication yes
      • AuthorizedKeysFile .ssh/authorized_keys
    • Restart the SSH service:
      sudo systemctl restart sshd
  • SELinux/Firewall: Check if SELinux or a firewall is blocking SSH access.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation