How to Enable SSH Public Key Authentication

October 16, 2023 / Security and Backup

SSH public key authentication allows you to securely log in to a remote server without using a password. It is more secure than password-based authentication and is widely recommended for server access.

Follow the steps:

  1. On the source server, navigate to the /etc/ssh directory, which contains the SSH configuration files. There are different types of SSH keys based on their encryption algorithms (DSA, RSA, ECDSA, Ed25519).
    In this example, RSA-encrypted keys are used.
    If no SSH keys are available, they can be created using the ssh-keygen command.
    For example:

    ssh-keygen -t rsa -b 4096

    This command will generate a public key at:

    /root/.ssh/id_rsa.pub
  2. Copy the Public Key to the Destination Server
    Copy the contents of the public key file from the source server:

    /root/.ssh/id_rsa.pub

    Paste it into the following file on the destination server:

    /root/.ssh/authorized_keys
  3. Verify Ownership and Permissions (Very Important)
    Set the correct permissions using the following command:

    chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys

    If the root user is used to log in via SSH (root@ipAddress), ensure that the authorized_keys file is owned by root and located under /root/.ssh.

  4. Update SSH Configuration
    On the destination server, ensure that the following entries are present in the SSH configuration file:

    vi /etc/ssh/sshd_config
    PermitRootLogin yes
    RSAAuthentication yes
    PubkeyAuthentication yes
    PasswordAuthentication no
    AuthorizedKeysFile .ssh/authorized_keys
  5. Restart the SSH service using:
    systemctl restart sshd
  6. Test SSH Login
    You can now log in to the remote server from the source host using:

    ssh root@remoteIPAddress

By following the above steps, you can enable SSH public key authentication for secure, password-less server access. This helps improve security and prevents unauthorised logins.

Spread the love