Skip to content

Instantly share code, notes, and snippets.

@SirToffski
Last active January 13, 2023 15:54
Show Gist options
  • Save SirToffski/8722c377063871bb25fc80a67cbaa534 to your computer and use it in GitHub Desktop.
Save SirToffski/8722c377063871bb25fc80a67cbaa534 to your computer and use it in GitHub Desktop.
Creating SSH Keys and Disabling Password Auth

Creating the keys

Generate the SSH Key

This will generate two keys:

  1. <key_name>_ed25519 - this is the private key and should be kept safe. Never put this key on the server itself.

  2. <key_name>_ed25519.pub - this is the public key, it will need to be added to the ~/.ssh/authorized_keys on the server.

ssh-keygen -o -a 100 -t ed25519 -f ~/.ssh/<key_name>_ed25519 -C "Enrico Fermi <fermi@paradox.quantum>"

Setting a password on the key is more secure, but less convenient. If an attacker stole the private key - having a password would make it harder to use the key. Password will need to be entered every time you use the key to SSH.

Set local file permissions

Run these commands on our local machine first.

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/<key_name>_ed25519
chmod 644 ~/.ssh/<key_name>_ed25519.pub

Transfer the Public Key to your Server

scp ~/.ssh/<key_name>_ed25519.pub <username>@<server_IP>:/home/<user>/.ssh/<key_name>_ed25519.pub

SSH into your server using the password. Then add the public key to ~/.ssh/authorized_keys and set permissions.

cat ~/.ssh/<key_name>_ed25519.pub >> ~/.ssh/authorized_keys

Set permissions on the server

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 644 ~/.ssh/<key_name>_ed25519.pub

SSH using the key

You should be able to SSH using the key now. To try, on your local machine:

ssh -i ~/.ssh/<key_name>_ed25519 <username>@<server_IP>

If this works, proceed to the next step to disable password auth on the server.

Disable Password Auth

On the server, run the following commands to disable password authentication.

sudo sed -i -E 's/.PermitRootLogin.*/PermitRootLogin no/g' /etc/ssh/sshd_config
sudo sed -i -E 's/.PasswordAuthentication.*/PasswordAuthentication no/g' /etc/ssh/sshd_config
sudo sed -i -E 's/.KbdInteractiveAuthentication.*/KbdInteractiveAuthentication no/g' /etc/ssh/sshd_config

Verify changes:

sudo grep -E 'PermitRootLogin|PasswordAuthentication|KbdInteractiveAuthentication' /etc/ssh/sshd_config

If all are set to no, reboot the server with sudo reboot for changes to take effect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment