21 August 2016

Linux: Setup SSH Keys Authentication

Install on Server

sudo apt-get update
sudo apt-get install openssh-server
sudo ufw allow 22

Setup a Client Key

  1. Setup key pair on client computer:
    ssh-keygen -t rsa
    1. Optionally create a passphrase (that needs to be entered each time)
  2. Copy the key to the destination server:
    ssh-copy-id <user>@<destination ip>
    or
    cat ~/.ssh/id_rsa.pub | ssh <user>@<destination ip> "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"
NB: when creating keys take care to note what type your server can handle e.g. rsa

Disable password login for SSH

    1. Create a backup of the settings:
      sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults
      sudo chmod a-w /etc/ssh/sshd_config.factory-defaults
    2. Edit the config file:
      sudo vi /etc/ssh/sshd_config
    3. Find PasswordAuthentication yes (/PasswordAuthentication in vi)
      Change to: PasswordAuthentication no
    4. Enable RSA:
      RSAAuthentication yes
      PubkeyAuthentication yes
    5. Optionally:
      1. Disable root login with password also:
        PermitRootLogin without-password
    6. Restart ssh:
      reload ssh
      or
      service sshd restart

To Remove an Authorised Host

vi /root/.ssh/authorized_keys
Delete the line for your client

Troubleshooting

  • Check the logs on the server:
    vi /var/log/secure
    (use G to get to end of file)

Mac

You need to tell Mac to use your Keychain if you want to store the passphrase:
vi ~/.ssh/config
Then enter:
Host *
  IgnoreUnknown UseKeychain,AddKeysToAgent
  UseKeychain yes
  AddKeysToAgent yes
  IdentityFile ~/.ssh/id_rsa

No comments:

Post a Comment